agent

package
v1.40.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 31 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

Index

Constants

View Source
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

func AgyOAuthTokenPath(home string) string

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

func BuildMCPToolDefs() []api.ToolDef

BuildMCPToolDefs returns the tool definitions exposed via the MCP server — the public set minus native-only tools (see nativeOnlyToolNames).

func BuildMCPToolDefsForMode

func BuildMCPToolDefsForMode(localOnly bool) []api.ToolDef

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

func BuildToolDefs() []api.ToolDef

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

func BuildToolDefsForMode(localOnly bool) []api.ToolDef

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

func CerebrasTTFTSec(ti map[string]interface{}) float64

CerebrasTTFTSec pulls time-to-first-token (in seconds) from time_info if present.

func CerebrasTokensPerSecond

func CerebrasTokensPerSecond(ti map[string]interface{}) float64

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

func CodexMCPEntryExists(config string) bool

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

func IsLocalTool(name string) bool

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

func OpenCodeProviderEnv(cfg *api.Config) map[string]string

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

func PlaintextKeyInUserOpenCodeConfig() (path string, found bool)

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

func ShouldUseVisionSidecar(cfg *api.Config, backend string) bool

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

func SummarizeToolResult(name, output string) string

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 ToolCost

func ToolCost(name string) string

ToolCost classifies tools by cost impact.

func ValidateOllamaURL

func ValidateOllamaURL(ollamaURL string) error

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

func WriteAgyMCPEntry(path string, env map[string]string) (alreadyHad bool, err error)

WriteAgyMCPEntry merges the qmax MCP stdio server into an Antigravity mcp_config.json, preserving unrelated servers.

func WriteCodexMCPEntry

func WriteCodexMCPEntry(path string, env map[string]string) (alreadyHad bool, err error)

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 NewAgent

func NewAgent(cfg AgentConfig) *Agent

NewAgent creates a new LLM agent.

func (*Agent) AppendHistory

func (a *Agent) AppendHistory(messages ...api.Message)

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

func (a *Agent) ForgetRejectedApproach(number int) error

ForgetRejectedApproach removes a one-based entry, preserving the user's correction in the transcript as well as the current checkpoint.

func (*Agent) HandoffContext

func (a *Agent) HandoffContext() string

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

func (a *Agent) HandoffSwitchHint() string

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

func (a *Agent) RejectApproach(approach, evidence string) error

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

func (a *Agent) Run(prompt string) (string, error)

Run executes a prompt through the agent loop and returns the final text response. Used for non-interactive (one-shot) mode.

func (*Agent) RunCLI

func (a *Agent) RunCLI(cli CLIAgent, prompt string, term *tui.Terminal) (string, error)

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

func (a *Agent) RunCerebrasAgent(term *tui.Terminal) (string, bool)

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

func (a *Agent) RunOllamaAgent(term *tui.Terminal) (string, bool)

RunOllamaAgent runs a full conversation turn using only Ollama. Returns the final text response and whether it succeeded.

func (*Agent) RunStreaming

func (a *Agent) RunStreaming(prompt string, term *tui.Terminal) (string, error)

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:

  1. qmax-code merges the qmax MCP server into ~/.gemini/config/mcp_config.json
  2. qmax-code spawns: agy --output-format stream-json --add-dir <cwd> [--conversation <id>] [-p prompt]
  3. agy spawns qmax-code serve --mcp and runs the native agent harness
  4. qmax-code parses NDJSON events and renders them
  5. 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) Cancel

func (a *AgyAgent) Cancel()

func (*AgyAgent) Cleanup

func (a *AgyAgent) Cleanup()

func (*AgyAgent) LastPlanLimit

func (a *AgyAgent) LastPlanLimit() (reset time.Time, hit bool)

func (*AgyAgent) LastTurnStats

func (a *AgyAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)

func (*AgyAgent) ResetConversation

func (a *AgyAgent) ResetConversation()

func (*AgyAgent) Run

func (a *AgyAgent) Run(userMsg string, term *tui.Terminal) (string, error)

Run executes one conversation turn through an agy subprocess.

func (*AgyAgent) SetOutputVerbose

func (a *AgyAgent) SetOutputVerbose(verbose bool)

func (*AgyAgent) WriteMCPConfig

func (a *AgyAgent) WriteMCPConfig() error

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:

  1. qmax-code spawns: claude --print "msg" --output-format stream-json --append-system-prompt <QA_PROMPT> --mcp-config <temp_file> [--resume <cc_session_id>]
  2. CC spawns: qmax-code serve --mcp (our MCP server subprocess)
  3. CC uses qmax tools via MCP, metered to the user's Claude account
  4. qmax-code parses CC's stream-json and renders in the terminal
  5. 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) Cleanup

func (a *CCAgent) Cleanup()

Cleanup removes the temp MCP config file.

func (*CCAgent) LastTurnStats

func (a *CCAgent) LastTurnStats() (inputTokens, outputTokens int, ok bool)

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

func (a *CCAgent) Run(userMsg string, term *tui.Terminal) (string, error)

Run executes one conversation turn through a CC subprocess. CC's subscription handles inference; qmax handles tools via MCP.

func (*CCAgent) SetOutputVerbose

func (a *CCAgent) SetOutputVerbose(verbose bool)

func (*CCAgent) WriteMCPConfig

func (a *CCAgent) WriteMCPConfig() error

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:

  1. qmax-code writes ~/.codex/config.toml with the qmax MCP server entry
  2. qmax-code starts or resumes a Codex thread through codexrunner
  3. Codex picks up the MCP config and spawns qmax-code serve --mcp
  4. Codex uses qmax tools natively with its configured authentication
  5. 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) Run

func (a *CodexAgent) Run(userMsg string, term *tui.Terminal) (string, error)

Run executes one conversation turn through a Codex subprocess.

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).

func (*OllamaClient) ChatStreamingWithModel

func (o *OllamaClient) ChatStreamingWithModel(ctx context.Context, model, system string, history []api.Message, term *tui.Terminal) (string, error)

ChatStreamingWithModel is like ChatStreaming but uses a specific model.

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:

  1. qmax-code writes ~/.qmax-code/opencode.json (provider blocks + qmax MCP)
  2. qmax-code spawns: opencode run --format json --model <provider>/<model> [--session <id>] [--auto] -- "msg" with OPENCODE_CONFIG + key env set
  3. opencode picks up the MCP config and spawns qmax-code serve --mcp
  4. opencode runs the turn on the user's provider, using qmax tools via MCP
  5. 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

func (a *OpenCodeAgent) Run(userMsg string, term *tui.Terminal) (string, error)

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

type PlanLimitReporter interface {
	LastPlanLimit() (reset time.Time, hit bool)
}

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 PlanStep

type PlanStep struct {
	Title  string
	Status string // pending | in_progress | done
}

PlanStep is a single entry in the agent's task plan, surfaced via update_plan.

type TurnStatsProvider

type TurnStatsProvider interface {
	LastTurnStats() (inputTokens, outputTokens int, ok bool)
}

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.

Jump to

Keyboard shortcuts

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