Documentation
¶
Index ¶
- Constants
- func AgyFileTokenPresent() bool
- func AgyOAuthTokenPath(home string) string
- func BuildMCPToolDefs() []api.ToolDef
- func BuildMCPToolDefsForMode(localOnly bool) []api.ToolDef
- func BuildSidecarAugmentedPrompt(userPrompt string, imgs []tui.ImageAttachment, description string) (string, error)
- func BuildToolDefs() []api.ToolDef
- func BuildToolDefsForMode(localOnly bool) []api.ToolDef
- func BuildUserContent(text string, images []tui.ImageAttachment) interface{}
- func CerebrasTTFTSec(ti map[string]interface{}) float64
- func CerebrasTokensPerSecond(ti map[string]interface{}) float64
- func CleanupStaleMCPConfigs()
- func CodexMCPEntryExists(config string) bool
- func DescribeImagesWithGemma(ctx context.Context, cfg *api.Config, imgs []tui.ImageAttachment, ...) (string, error)
- func ExecuteTool(name string, rawInput interface{}, sctx *api.SessionContext, ...) string
- func FindAgy() string
- func FindClaudeCode() string
- func FindCodex() string
- func FindOpenCode() string
- func IsLocalTool(name string) bool
- func OpenCodeConfigPath() string
- func OpenCodeModels(bin, configPath string, providerEnv map[string]string, providerID string) ([]string, error)
- func OpenCodeProviderEnv(cfg *api.Config) map[string]string
- func PlaintextKeyInUserOpenCodeConfig() (path string, found bool)
- func ShouldUseVisionSidecar(cfg *api.Config, backend string) bool
- func SummarizeToolResult(name, output string) string
- func ToolCost(name string) string
- func ValidateOllamaURL(ollamaURL string) error
- func WriteAgyMCPEntry(path string, env map[string]string) (alreadyHad bool, err error)
- func WriteCodexMCPEntry(path string, env map[string]string) (alreadyHad bool, err error)
- func WriteOpenCodeConfig(cfg *api.Config, sctx *api.SessionContext, permissionMode string) (string, error)
- type Agent
- func (a *Agent) AppendHistory(messages ...api.Message)
- func (a *Agent) CancelCurrent()
- func (a *Agent) CleanupConversation()
- func (a *Agent) ClearHistory()
- func (a *Agent) EnsureTranscript()
- func (a *Agent) ForgetRejectedApproach(number int) error
- func (a *Agent) HandoffContext() string
- func (a *Agent) HandoffSwitchHint() string
- func (a *Agent) RejectApproach(approach, evidence string) error
- func (a *Agent) RestoreConversation(history []api.Message, state api.ConversationState)
- func (a *Agent) Run(prompt string) (string, error)
- func (a *Agent) RunCLI(cli CLIAgent, prompt string, term *tui.Terminal) (string, error)
- func (a *Agent) RunCerebrasAgent(term *tui.Terminal) (string, bool)
- func (a *Agent) RunOllamaAgent(term *tui.Terminal) (string, bool)
- func (a *Agent) RunStreaming(prompt string, term *tui.Terminal) (string, error)
- func (a *Agent) RunStreamingWithImages(prompt string, images []tui.ImageAttachment, term *tui.Terminal) (string, error)
- type AgentConfig
- type AgyAgent
- func (a *AgyAgent) Cancel()
- func (a *AgyAgent) Cleanup()
- func (a *AgyAgent) LastPlanLimit() (reset time.Time, hit bool)
- func (a *AgyAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)
- func (a *AgyAgent) ResetConversation()
- func (a *AgyAgent) Run(userMsg string, term *tui.Terminal) (string, error)
- func (a *AgyAgent) SetOutputVerbose(verbose bool)
- func (a *AgyAgent) WriteMCPConfig() error
- type CCAgent
- func (a *CCAgent) Cancel()
- func (a *CCAgent) Cleanup()
- func (a *CCAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)
- func (a *CCAgent) ResetConversation()
- func (a *CCAgent) Run(userMsg string, term *tui.Terminal) (string, error)
- func (a *CCAgent) SetOutputVerbose(verbose bool)
- func (a *CCAgent) WriteMCPConfig() error
- type CLIAgent
- type CerebrasClient
- type CodexAgent
- func (a *CodexAgent) Cancel()
- func (a *CodexAgent) Cleanup()
- func (a *CodexAgent) ClearHistory()
- func (a *CodexAgent) LastPlanLimit() (reset time.Time, hit bool)
- func (a *CodexAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)
- func (a *CodexAgent) ResetConversation()
- func (a *CodexAgent) Run(userMsg string, term *tui.Terminal) (string, error)
- func (a *CodexAgent) SetOutputVerbose(verbose bool)
- func (a *CodexAgent) WriteMCPConfig() error
- type ConversationResetter
- type OllamaClient
- func (o *OllamaClient) Available() bool
- func (o *OllamaClient) ChatStreaming(ctx context.Context, system string, history []api.Message, term *tui.Terminal) (string, error)
- func (o *OllamaClient) ChatStreamingWithModel(ctx context.Context, model, system string, history []api.Message, ...) (string, error)
- type OllamaMode
- type OpenCodeAgent
- func (a *OpenCodeAgent) Cancel()
- func (a *OpenCodeAgent) Cleanup()
- func (a *OpenCodeAgent) ClearSession()
- func (a *OpenCodeAgent) LastPlanLimit() (reset time.Time, hit bool)
- func (a *OpenCodeAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)
- func (a *OpenCodeAgent) ResetConversation()
- func (a *OpenCodeAgent) Run(userMsg string, term *tui.Terminal) (string, error)
- func (a *OpenCodeAgent) SetOutputVerbose(verbose bool)
- type PlanLimitReporter
- type PlanStep
- type TurnStatsProvider
- type TurnTranscript
Constants ¶
const QmaxMCPCommand = "qmax-code"
QmaxMCPCommand is the binary name written into the Codex MCP config so the CLI can spawn the qmax MCP server. Centralised here because both runtime (codex_agent.go writing per-session config) and setup orchestration (cmd/qmax setup) need the same value.
Variables ¶
This section is empty.
Functions ¶
func AgyFileTokenPresent ¶
func AgyFileTokenPresent() bool
AgyFileTokenPresent reports whether the file-backed Google OAuth token exists. A false result does not mean the user is logged out: macOS Keychain credentials are invisible here.
func AgyOAuthTokenPath ¶
AgyOAuthTokenPath is the file-storage fallback for Google OAuth tokens (~/.gemini/antigravity-cli/antigravity-oauth-token). On macOS the token usually lives in the OS keyring instead; this path is the Linux/CI fallback.
func BuildMCPToolDefs ¶
BuildMCPToolDefs returns the tool definitions exposed via the MCP server — the public set minus native-only tools (see nativeOnlyToolNames).
func BuildMCPToolDefsForMode ¶
BuildMCPToolDefsForMode applies the standalone boundary and then removes native-agent-only tools that would collide with the consuming CLI.
func BuildSidecarAugmentedPrompt ¶
func BuildSidecarAugmentedPrompt(userPrompt string, imgs []tui.ImageAttachment, description string) (string, error)
BuildSidecarAugmentedPrompt injects the sidecar description into the CLI turn's user prompt under explicit delimiters, so the text-only model knows exactly where the image content came from and what it covers.
func BuildToolDefs ¶
BuildToolDefs returns the connected-mode public tool definitions exposed to the LLM agent. Experimental tools are filtered out unless QMAX_EXPERIMENTAL=1 is set.
func BuildToolDefsForMode ¶
BuildToolDefsForMode returns the public tool definitions for the requested runtime boundary. Standalone mode exposes only tools that require no QualityMax account or service.
func BuildUserContent ¶
func BuildUserContent(text string, images []tui.ImageAttachment) interface{}
If images are provided, it builds a multi-block content array (text + images). Otherwise, it returns the plain string (simpler, lower token usage).
func CerebrasTTFTSec ¶
CerebrasTTFTSec pulls time-to-first-token (in seconds) from time_info if present.
func CerebrasTokensPerSecond ¶
CerebrasTokensPerSecond pulls a tokens/sec figure from a Cerebras time_info object, trying common key names. Returns 0 if unavailable.
func CleanupStaleMCPConfigs ¶
func CleanupStaleMCPConfigs()
CleanupStaleMCPConfigs removes qmax-mcp-<pid>-*.json files left in the OS temp dir by previous qmax-code instances that crashed before their Cleanup() could run. Safe to call on every startup — skips files whose PID is alive.
func CodexMCPEntryExists ¶ added in v1.40.2
CodexMCPEntryExists reports whether valid TOML defines a qmax MCP entry.
func DescribeImagesWithGemma ¶
func DescribeImagesWithGemma(ctx context.Context, cfg *api.Config, imgs []tui.ImageAttachment, userPrompt string) (string, error)
DescribeImagesWithGemma makes one Cerebras call with gemma-4-31b (always the multimodal model, even when the user's active Cerebras model is a text-only one) and returns a per-image text description. All usable attachments go in a single request — one round trip, and cross-image context (e.g. before/after screenshots) stays available to the model.
func ExecuteTool ¶
func ExecuteTool(name string, rawInput interface{}, sctx *api.SessionContext, ctx context.Context) string
ExecuteTool executes a tool and returns the output string. Uses the API client for QualityMax operations (no qmax CLI needed). Falls back to qmax CLI if API client is not available.
func FindAgy ¶
func FindAgy() string
FindAgy returns the path to the Antigravity CLI binary, or "" if not found.
func FindClaudeCode ¶
func FindClaudeCode() string
FindClaudeCode returns the path to the claude CLI binary, or "" if not installed.
func FindCodex ¶
func FindCodex() string
FindCodex returns the path to the codex CLI binary, or "" if not installed.
func FindOpenCode ¶
func FindOpenCode() string
FindOpenCode returns the path to the opencode CLI binary, or "" if not found.
func IsLocalTool ¶
IsLocalTool reports whether name is implemented entirely inside qmax-code and therefore must never be forwarded to QualityMax cloud. MCP uses this as an execution boundary, not merely a discovery filter.
func OpenCodeConfigPath ¶
func OpenCodeConfigPath() string
OpenCodeConfigPath is the qmax-managed opencode config file. It is pointed at the opencode subprocess via the OPENCODE_CONFIG env var, which opencode MERGES on top of the user's own ~/.config/opencode/opencode.jsonc — so we never clobber the user's config. Kept under ~/.qmax-code so it lives beside the rest of qmax's state and is easy to sync.
func OpenCodeModels ¶
func OpenCodeModels(bin, configPath string, providerEnv map[string]string, providerID string) ([]string, error)
OpenCodeModels lists the models opencode exposes for one provider, as "provider/model" strings. It shells out to `opencode models <providerID>` with OPENCODE_CONFIG pointed at the managed config so custom providers (whose models come from our seeded block) resolve too. providerEnv MUST carry the provider API keys (from OpenCodeProviderEnv): opencode 1.17 reports "Provider not found" for known providers like groq/openrouter when their key env var is absent, so without it those providers would never reach the picker.
The query is a live network round-trip (models.dev / provider catalog) that takes seconds warm and can take far longer cold. It used to return nil silently on timeout or failure, which made /orch show a partial model list with no explanation — new models would "go missing" for no visible reason. It now retries once and returns the error so callers can surface it.
func OpenCodeProviderEnv ¶
OpenCodeProviderEnv returns the environment variables that carry each enabled provider's API key into the opencode subprocess. For custom providers this is the "{env:VAR}" name referenced in the config block; for known providers it's opencode's standard var (GROQ_API_KEY, …). Keys are read from the OS keychain at launch — never written to the config file.
func PlaintextKeyInUserOpenCodeConfig ¶
PlaintextKeyInUserOpenCodeConfig reports whether the user's OWN opencode config files contain a plaintext apiKey (not an {env:}/{file:} reference), and the path where one was found. Used to warn a user — when they move a provider under qmax's keychain-backed management — that a live key is still sitting in cleartext in their opencode config and should be rotated/removed.
func ShouldUseVisionSidecar ¶
ShouldUseVisionSidecar decides whether a CLI-backend turn with image attachments should run the sidecar. It is the single policy chokepoint:
- off → never
- always → every CLI backend (global image read by Cerebras)
- auto (unset) → only when the active model is KNOWN text-only (opencode on a Z.AI GLM coding-plan model)
Every mode requires a Cerebras key; without one the sidecar silently degrades to off and callers fall back to the pre-sidecar behavior.
func SummarizeToolResult ¶
SummarizeToolResult parses common JSON responses and returns human-readable summaries. The summary is shown in the terminal AND sent to the LLM to save tokens.
func ValidateOllamaURL ¶
ValidateOllamaURL checks that ollamaURL is a syntactically valid http or https URL. Returns an error otherwise. Used by callers (REPL, /set ollama, /orch picker) to gate OllamaURL inputs read from on-disk config before they're handed to NewOllamaClient — defends against schemes like file:// or javascript: ending up in HTTP request URLs.
func WriteAgyMCPEntry ¶
WriteAgyMCPEntry merges the qmax MCP stdio server into an Antigravity mcp_config.json, preserving unrelated servers.
func WriteCodexMCPEntry ¶
WriteCodexMCPEntry merges the qmax MCP entry into Codex's TOML config at path. The env map is rendered into the entry's `env = { ... }` block. The returned alreadyHad flag tells the caller whether an entry was already present (used by setup orchestration to phrase its progress message).
func WriteOpenCodeConfig ¶
func WriteOpenCodeConfig(cfg *api.Config, sctx *api.SessionContext, permissionMode string) (string, error)
WriteOpenCodeConfig regenerates the managed opencode config from the user's enabled providers, the qmax MCP server entry, and the permission policy for permissionMode ("standard" | "unattended"), and returns its path.
Secrets never land in this file: custom providers reference their key via opencode's "{env:VAR}" substitution, and the real key is injected into the subprocess environment at launch (see OpenCodeProviderEnv). The file is therefore safe to sync while no plaintext key touches disk.
Types ¶
type Agent ¶
type Agent struct {
Cfg AgentConfig
AppConfig *api.Config // persistent user preferences
History []api.Message
Conversation api.ConversationState
SessionID string
Usage api.TokenUsage
// LastContextTokens is the input-token count reported by the most recent
// model request. Unlike Usage.InputTokens, it is not cumulative and can be
// used to estimate the currently occupied context window in the TUI.
LastContextTokens int
Logger *sysutil.Logger
Ollama *OllamaClient // optional self-hosted LLM
Mode OllamaMode // off, chat, or full
Cerebras *CerebrasClient // optional Cerebras backend; when set, owns the whole turn
// contains filtered or unexported fields
}
Agent is the LLM-powered QA orchestration engine.
Several fields are exported because the REPL (cmd/qmax) drives session state from the outside — appending to History on resume, reading Usage to print cost, wiring an Ollama client after construction, etc. The unexported fields (tools, client, cancel, priorSessions, sessionsFetched) are pure internals.
func (*Agent) AppendHistory ¶
AppendHistory adds messages to both the working context and lossless archive.
func (*Agent) CancelCurrent ¶
func (a *Agent) CancelCurrent()
CancelCurrent cancels the current streaming request if one is in progress. Safe to call from any goroutine concurrently with RunStreaming.
func (*Agent) CleanupConversation ¶
func (a *Agent) CleanupConversation()
CleanupConversation removes ephemeral context files when clearing or exiting. Saved session files are retained independently according to auto-save settings.
func (*Agent) ClearHistory ¶
func (a *Agent) ClearHistory()
ClearHistory resets conversation history.
func (*Agent) EnsureTranscript ¶
func (a *Agent) EnsureTranscript()
EnsureTranscript imports legacy sessions before any working-history compaction.
func (*Agent) ForgetRejectedApproach ¶
ForgetRejectedApproach removes a one-based entry, preserving the user's correction in the transcript as well as the current checkpoint.
func (*Agent) HandoffContext ¶
HandoffContext keeps explicit decisions visible on every backend turn, even when a native session has no missing transcript entries or history is compacted.
func (*Agent) HandoffSwitchHint ¶
HandoffSwitchHint suggests recording a ruled-out approach after a backend switch when work happened since the checkpoint last changed. It never records one itself: a failure can also mean a flaky test, an unavailable dependency, or unfinished work, so only the user can decide what is ruled out.
func (*Agent) RejectApproach ¶
RejectApproach records an explicit user decision; command failures alone are insufficient evidence that an approach should never be retried.
func (*Agent) RestoreConversation ¶
func (a *Agent) RestoreConversation(history []api.Message, state api.ConversationState)
RestoreConversation replaces both histories and all native session cursors.
func (*Agent) Run ¶
Run executes a prompt through the agent loop and returns the final text response. Used for non-interactive (one-shot) mode.
func (*Agent) RunCLI ¶
RunCLI synchronizes a CLI's native session with the shared transcript before running a turn, then retains partial output and tool activity even on error.
func (*Agent) RunCerebrasAgent ¶
RunCerebrasAgent runs a complete conversation turn through Cerebras using native OpenAI function-calling against the active mode's qmax tool set. It owns the whole multi-round tool loop (call → execute tools → feed results → repeat) and returns the final assistant text plus whether it succeeded.
On any hard failure it returns ok=false. There is no Claude fallback here: when backend=cerebras the user has no Anthropic key, so we surface the error rather than silently switching providers.
func (*Agent) RunOllamaAgent ¶
RunOllamaAgent runs a full conversation turn using only Ollama. Returns the final text response and whether it succeeded.
func (*Agent) RunStreaming ¶
func (*Agent) RunStreamingWithImages ¶
func (a *Agent) RunStreamingWithImages(prompt string, images []tui.ImageAttachment, term *tui.Terminal) (string, error)
RunStreamingWithImages is like RunStreaming but supports image attachments.
type AgentConfig ¶
type AgentConfig struct {
AnthropicKey string
Model string // base model (used for tool execution loops)
ChatModel string // cheaper model for conversational responses
Verbose bool
OutputVerbose bool // user-facing answer style; false = compact, true = detailed
Context *api.SessionContext
AutoRoute bool // true = haiku for chat, sonnet for tools
Professional bool // disable cat personality, be direct
}
AgentConfig holds configuration for the LLM agent.
type AgyAgent ¶
type AgyAgent struct {
TurnTranscript
// contains filtered or unexported fields
}
AgyAgent orchestrates an Antigravity CLI (`agy`) subprocess for LLM inference. Authentication is Google OAuth: run interactive `agy` once so the CLI can open a browser sign-in (the same Google account as AI Studio). qmax-code does not ask for a Gemini API key and does not set modelProvider=gemini.
Per-message flow:
- qmax-code merges the qmax MCP server into ~/.gemini/config/mcp_config.json
- qmax-code spawns: agy --output-format stream-json --add-dir <cwd> [--conversation <id>] [-p prompt]
- agy spawns qmax-code serve --mcp and runs the native agent harness
- qmax-code parses NDJSON events and renders them
- conversation_id is kept for --conversation on the next turn
func NewAgyAgent ¶
func NewAgyAgent(bin, modelID, effort, permissionMode string, outputVerbose bool, narrateToolCalls string, sctx *api.SessionContext) *AgyAgent
NewAgyAgent creates an Antigravity subprocess orchestrator.
func (*AgyAgent) LastTurnStats ¶
func (*AgyAgent) ResetConversation ¶
func (a *AgyAgent) ResetConversation()
func (*AgyAgent) SetOutputVerbose ¶
func (*AgyAgent) WriteMCPConfig ¶
WriteMCPConfig merges the qmax MCP server into Antigravity's global MCP config. agy has no per-invocation --mcp-config flag, so this is the attach path (same class as Codex writing ~/.codex/config.toml).
type CCAgent ¶
type CCAgent struct {
TurnTranscript
// contains filtered or unexported fields
}
CCAgent orchestrates a Claude Code CLI subprocess for LLM inference. Inference runs through the user's Claude Code login, so qmax-code does not need a QM-held Anthropic API key. `claude --print` uses Claude Code's configured authentication and billing, including inherited API credentials. qmax tools are exposed to CC as an MCP server so CC can call them natively via its own tool-use mechanism.
Per-message flow:
- qmax-code spawns: claude --print "msg" --output-format stream-json --append-system-prompt <QA_PROMPT> --mcp-config <temp_file> [--resume <cc_session_id>]
- CC spawns: qmax-code serve --mcp (our MCP server subprocess)
- CC uses qmax tools via MCP, metered to the user's Claude account
- qmax-code parses CC's stream-json and renders in the terminal
- CC session ID is saved for --resume on the next turn
func NewCCAgent ¶
func NewCCAgent(claudeBin, modelID, effort, permissionMode string, outputVerbose bool, narrateToolCalls string, sctx *api.SessionContext) *CCAgent
NewCCAgent creates a CC subprocess orchestrator. modelID is passed as --model to the claude CLI (empty = CC's default). effort is "low" | "medium" | "high" (empty defaults to "high"). permissionMode is "standard" (curated allowlist) or "unattended" (--dangerously-skip-permissions). Both require explicit user consent.
func (*CCAgent) Cancel ¶
func (a *CCAgent) Cancel()
Cancel interrupts a Run call that is in progress. Safe to call from any goroutine.
func (*CCAgent) LastTurnStats ¶
LastTurnStats returns Claude Code's usage from the most recently completed turn. It is intentionally optional so other CLI backends need not invent token figures when their protocol does not expose them.
func (*CCAgent) ResetConversation ¶
func (a *CCAgent) ResetConversation()
ResetConversation ensures /clear and /resume cannot reuse a different session.
func (*CCAgent) Run ¶
Run executes one conversation turn through a CC subprocess. CC's subscription handles inference; qmax handles tools via MCP.
func (*CCAgent) SetOutputVerbose ¶
func (*CCAgent) WriteMCPConfig ¶
WriteMCPConfig writes a temp JSON file that tells CC where to find our MCP server. The file is written once per qmax session and reused for all turns.
type CLIAgent ¶
type CLIAgent interface {
Run(userMsg string, term *tui.Terminal) (string, error)
// Cancel interrupts a Run call in progress. Safe to call from another goroutine.
Cancel()
SetOutputVerbose(verbose bool)
Cleanup()
}
CLIAgent is the interface implemented by both CCAgent (claude CLI) and CodexAgent (codex CLI). It lets main.go switch backends without caring which CLI is underneath.
type CerebrasClient ¶
type CerebrasClient struct {
BaseURL string // e.g. "https://api.cerebras.ai/v1"
Model string // e.g. "gpt-oss-120b" or "gemma-4-31b"
APIKey string
ReasoningEffort string // "", "none", "low", "medium", "high" (Gemma 4 thinking)
HTTP *http.Client
}
CerebrasClient wraps HTTP calls to a Cerebras (OpenAI-compatible) endpoint.
func NewCerebrasClient ¶
func NewCerebrasClient(cfg *api.Config) *CerebrasClient
NewCerebrasClient builds a client from config, or returns nil if no API key is configured. Base URL and model fall back to the package defaults.
func (*CerebrasClient) Chat ¶
func (c *CerebrasClient) Chat(ctx context.Context, msgs []oaiMessage, tools []oaiTool) (*oaiChatResponse, error)
Chat performs a single non-streaming chat completion. Cerebras is fast enough (~1000+ tok/s) that non-streaming keeps the tool loop simple and the tool-call parsing reliable.
type CodexAgent ¶
type CodexAgent struct {
TurnTranscript
// contains filtered or unexported fields
}
CodexAgent orchestrates an OpenAI Codex CLI subprocess for LLM inference. Inference uses Codex's configured authentication and billing, including ChatGPT subscription login or API credentials. qmax tools are served via the same MCP server used for CC mode.
Per-message flow:
- qmax-code writes ~/.codex/config.toml with the qmax MCP server entry
- qmax-code starts or resumes a Codex thread through codexrunner
- Codex picks up the MCP config and spawns qmax-code serve --mcp
- Codex uses qmax tools natively with its configured authentication
- qmax-code streams Codex's stdout to the terminal
func NewCodexAgent ¶
func NewCodexAgent(bin, modelID, effort string, outputVerbose bool, narrateToolCalls string, sctx *api.SessionContext) *CodexAgent
NewCodexAgent creates a Codex subprocess orchestrator. An empty modelID uses Codex configuration. Approval and sandbox choices always come from Codex.
func (*CodexAgent) Cancel ¶
func (a *CodexAgent) Cancel()
Cancel interrupts a Run call that is in progress. Safe to call from any goroutine.
func (*CodexAgent) Cleanup ¶
func (a *CodexAgent) Cleanup()
Cleanup is a no-op for CodexAgent (no temp files to remove).
func (*CodexAgent) ClearHistory ¶
func (a *CodexAgent) ClearHistory()
ClearHistory resets native Codex continuity (used when the user types /clear).
func (*CodexAgent) LastPlanLimit ¶
func (a *CodexAgent) LastPlanLimit() (reset time.Time, hit bool)
LastPlanLimit reports whether the plan limit was hit on the most recent turn. codex errors carry no reset header, so the reset time is the zero value and the window falls back to its time estimate. Satisfies PlanLimitReporter.
func (*CodexAgent) LastTurnStats ¶
func (a *CodexAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)
LastTurnStats returns codex's token usage for the most recent turn, when its stream carried any. Satisfies TurnStatsProvider.
func (*CodexAgent) ResetConversation ¶
func (a *CodexAgent) ResetConversation()
ResetConversation implements ConversationResetter.
func (*CodexAgent) SetOutputVerbose ¶
func (a *CodexAgent) SetOutputVerbose(verbose bool)
func (*CodexAgent) WriteMCPConfig ¶
func (a *CodexAgent) WriteMCPConfig() error
WriteMCPConfig writes the qmax MCP server into ~/.codex/config.toml so Codex picks it up for every invocation.
type ConversationResetter ¶
type ConversationResetter interface {
ResetConversation()
}
ConversationResetter is implemented by CLI backends that keep native conversation continuity outside the built-in agent history.
type OllamaClient ¶
type OllamaClient struct {
BaseURL string // e.g. "https://user:pass@llm.example.com"
Model string // e.g. "gemma3:4b-it-q4_K_M" (fast, for chat)
AgentModel string // e.g. "gemma3:12b-it-q4_K_M" (smarter, for tool dispatch)
HTTP *http.Client
// contains filtered or unexported fields
}
OllamaClient wraps HTTP calls to an Ollama instance with a circuit breaker.
func NewOllamaClient ¶
func NewOllamaClient(cfg *api.Config) *OllamaClient
NewOllamaClient creates a client if URL and model are configured. Returns nil if not configured or the URL is invalid.
func (*OllamaClient) Available ¶
func (o *OllamaClient) Available() bool
Available returns true if the circuit breaker is closed (not tripped).
func (*OllamaClient) ChatStreaming ¶
func (o *OllamaClient) ChatStreaming(ctx context.Context, system string, history []api.Message, term *tui.Terminal) (string, error)
ChatStreaming sends a chat request to Ollama and streams the response. Returns the full text, or an error (caller should fall back to Claude).
type OllamaMode ¶
type OllamaMode int
OllamaMode controls how much work Ollama handles.
const ( OllamaModeOff OllamaMode = iota // All calls go to Claude OllamaModeChat // Chat only (simple Q&A), tools via Claude OllamaModeFull // Everything including tool dispatch )
func (OllamaMode) String ¶
func (m OllamaMode) String() string
type OpenCodeAgent ¶
type OpenCodeAgent struct {
TurnTranscript
// contains filtered or unexported fields
}
OpenCodeAgent orchestrates an opencode CLI subprocess for LLM inference. Inference runs through whichever provider the user opted into (Z.AI, Groq, OpenRouter, …) using the user's own key — qmax-code consumes no QM-held tokens. qmax tools are exposed to opencode via an MCP server entry in the managed opencode config, so opencode can call them natively.
opencode supports native session resume (--session) and a rich NDJSON event stream (opencode run --format json), so it retains its provider session ID much like CodexAgent retains its exact native thread checkpoint.
Per-message flow:
- qmax-code writes ~/.qmax-code/opencode.json (provider blocks + qmax MCP)
- qmax-code spawns: opencode run --format json --model <provider>/<model> [--session <id>] [--auto] -- "msg" with OPENCODE_CONFIG + key env set
- opencode picks up the MCP config and spawns qmax-code serve --mcp
- opencode runs the turn on the user's provider, using qmax tools via MCP
- qmax-code parses opencode's NDJSON and renders it; session id → --session
func NewOpenCodeAgent ¶
func NewOpenCodeAgent(bin, modelID, effort, permissionMode string, outputVerbose bool, cfg *api.Config, sctx *api.SessionContext) *OpenCodeAgent
NewOpenCodeAgent creates an opencode subprocess orchestrator. modelID is the full "provider/model" string selected via the picker. effort is "low" | "medium" | "high" (empty defaults to "high"). permissionMode is "standard" or "unattended" (adds --auto).
func (*OpenCodeAgent) Cancel ¶
func (a *OpenCodeAgent) Cancel()
Cancel interrupts a Run call that is in progress. Safe to call from any goroutine.
func (*OpenCodeAgent) Cleanup ¶
func (a *OpenCodeAgent) Cleanup()
Cleanup is a no-op: the managed opencode config is persistent and syncable, not a per-session temp file.
func (*OpenCodeAgent) ClearSession ¶
func (a *OpenCodeAgent) ClearSession()
ClearSession forgets the opencode session id so the next turn starts fresh (used when the user types /clear).
func (*OpenCodeAgent) LastPlanLimit ¶
func (a *OpenCodeAgent) LastPlanLimit() (reset time.Time, hit bool)
LastPlanLimit reports whether the plan limit was hit on the most recent turn and, when known, the provider-reported reset time. Satisfies PlanLimitReporter.
func (*OpenCodeAgent) LastTurnStats ¶
func (a *OpenCodeAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)
LastTurnStats returns opencode's token usage for the most recent turn, when its stream carried any. Satisfies TurnStatsProvider.
func (*OpenCodeAgent) ResetConversation ¶
func (a *OpenCodeAgent) ResetConversation()
ResetConversation implements ConversationResetter.
func (*OpenCodeAgent) Run ¶
Run executes one conversation turn through an opencode subprocess. When the subprocess dies with no result, it distinguishes two failure classes:
- A provider error event was in the stream (auth, entitlement refusal, quota) — deterministic, so the real message is surfaced immediately instead of a bare "exit status 1". opencode masks these as a status-code-less "Unexpected server error", with the full text only in its own log, which the error message points at.
- No error event at all — opencode itself crashed (e.g. an internal JS TypeError mid-stream). Transient, so the turn is retried once before giving up with the stderr tail included.
func (*OpenCodeAgent) SetOutputVerbose ¶
func (a *OpenCodeAgent) SetOutputVerbose(verbose bool)
type PlanLimitReporter ¶
PlanLimitReporter is optionally implemented by CLI agents that can detect the subscription plan's usage limit being hit on the most recent Run — e.g. a 429 / "usage limit reached" event in the backend's stream. The REPL marks the coding-plan window exhausted so /plan and the status bar reflect the real stop. reset is the provider-reported reset time when the error carried one (Retry-After / rate-limit header), otherwise the zero value.
type TurnStatsProvider ¶
TurnStatsProvider is optionally implemented by CLI agents that can report token usage for their most recent Run. The REPL folds these numbers into the session totals shown in the input status bar; backends whose stream carries no usage information simply don't implement it (or return ok=false).
type TurnTranscript ¶
type TurnTranscript struct {
// contains filtered or unexported fields
}
TurnTranscript collects only exposed conversation/tool content, never raw stream envelopes, configuration, usage metadata, or hidden reasoning. Guarded like the rest of the CLI agent state it is embedded in: stream parsing and RunCLI's drain are on one goroutine today, but the surrounding structs are all mutex-protected and this should not be the exception.