api

package
v1.40.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 18 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 (
	AnthropicMessagesURL = "https://api.anthropic.com/v1/messages"
	AnthropicVersion     = "2023-06-01"
	ModelFable51         = "claude-fable-5-1"
	ModelFable           = "claude-fable-5"
	ModelHaiku           = "claude-haiku-4-5-20251001"
	ModelHaiku55         = "claude-haiku-5-5"
	ModelSonnet5         = "claude-sonnet-5"
	ModelSonnet          = "claude-sonnet-4-6"
	ModelOpus55          = "claude-opus-5-5"  // latest Opus; the "opus" shorthand resolves here
	ModelOpus            = "claude-opus-4-8"  // prior Opus, still selectable by full ID
	ModelOpus1M          = ModelOpus + "[1m]" // Claude Code 1M-context selector (Opus 4.8)
	ModelOpus47          = "claude-opus-4-7"  // older Opus, still selectable by full ID
)

Anthropic defaults for smart routing and direct API calls.

View Source
const (
	// CerebrasAPIBase is the default OpenAI-compatible base URL.
	CerebrasAPIBase = "https://api.cerebras.ai/v1"
	// CerebrasDefaultModel is a fast, capable general/coding model on Cerebras.
	CerebrasDefaultModel = "gpt-oss-120b"
	// CerebrasGemma4Model is Google DeepMind's Gemma 4 31B as hosted on
	// Cerebras. It is multimodal (text + image input, text output) and exposes
	// reasoning via the top-level reasoning_effort parameter (off by default).
	// Model ID per the Cerebras + Gemma 4 hackathon docs.
	CerebrasGemma4Model = "gemma-4-31b"
	// CerebrasQwen38Model is Alibaba's Qwen 3.8 as hosted on Cerebras.
	// Announced as coming soon to the Cerebras model catalog; the ID follows
	// Cerebras naming and must be confirmed against the live API at launch.
	CerebrasQwen38Model = "qwen-3.8"
)

Cerebras inference (OpenAI-compatible). The cerebras backend drives the native qmax agent loop — full tool set, native function-calling — through Cerebras's /v1/chat/completions endpoint, which is fast and low-cost.

Auth is a Bearer token (CEREBRAS_API_KEY), not the x-api-key header the Anthropic Messages API uses. Base URL and model are overridable via config or the CEREBRAS_API_BASE / CEREBRAS_MODEL env vars.

View Source
const (
	VisionSidecarAuto   = "auto"
	VisionSidecarAlways = "always"
	VisionSidecarOff    = "off"
)

Vision sidecar modes.

View Source
const DefaultCloudURL = "https://app.qualitymax.io"
View Source
const DefaultPlanWindowHours = 5

DefaultPlanWindowHours is the rolling usage-window length assumed for subscription coding plans (Claude Code, Codex, and OpenCode + Z.AI GLM). Those plans meter usage over a rolling window that opens on the first request and resets once the window elapses. Five hours matches the published behavior of all three at the time of writing; override it with the plan_window_hours config key for a plan whose window differs.

View Source
const LocalOnlyEnv = "QMAX_LOCAL_ONLY"
View Source
const MaxSessionUploadBytes = 4 * 1024 * 1024 // 4 MiB

MaxSessionUploadBytes caps the serialized event payload to avoid server rejection or excessive upload times on very long sessions.

View Source
const QmaxCodeConfigDir = ".qmax-code"

Variables

View Source
var AllowedFrameworks = map[string]bool{
	"":           true,
	"playwright": true,
	"pytest":     true,
	"go":         true,
	"rust":       true,
	"go_test":    true,
	"rust_cargo": true,
	"cargo":      true,
}

AllowedFrameworks mirrors the public framework values accepted by the QualityMax API. We validate client-side so bad values get rejected before hitting the wire and the agent can show a clearer error message.

Functions

func ContextWindow

func ContextWindow(model string) int

ContextWindow returns the assumed context-window size in tokens for a model ID across all backends. It feeds the status-bar fill estimate only, so a conservative 200k default for unknown (non-Anthropic) models is acceptable.

func DeleteFromKeychain

func DeleteFromKeychain(account string) error

DeleteFromKeychain removes a key from the OS keychain.

func DeleteProviderKey

func DeleteProviderKey(id string) error

DeleteProviderKey removes a provider's API key from the OS keychain.

func DetectProjectFromCwd

func DetectProjectFromCwd() (int, string)

DetectProjectFromCwd checks for .qmax.yml or .qualitymax.yml in cwd.

func DiscoverQMaxBinary

func DiscoverQMaxBinary() string

DiscoverQMaxBinary finds the qmax binary, checking multiple locations. Order: ./qmax, ~/.qmax/qmax, then PATH.

func FormatQMaxInstallHint

func FormatQMaxInstallHint() string

FormatQMaxInstallHint returns install instructions when qmax is missing.

func IsCerebrasGemma4Model

func IsCerebrasGemma4Model(modelID string) bool

IsCerebrasGemma4Model reports whether modelID is the Gemma 4 31B variant. Used to gate Gemma-specific behavior (reasoning, multimodal nudges).

func IsValidClaudeModelName

func IsValidClaudeModelName(m string) bool

IsValidClaudeModelName reports whether m is a model name qmax-code knows how to route. Validation is intentionally strict so typos fail locally instead of being forwarded to the Anthropic API or Claude Code.

func LoadFromKeychain

func LoadFromKeychain(account string) (string, error)

LoadFromKeychain retrieves a key from the OS keychain.

func LoadProviderKey

func LoadProviderKey(id string) string

LoadProviderKey retrieves a provider's API key from the OS keychain, falling back to any of the provider's standard environment variables.

func NormalizeCerebrasReasoningEffort

func NormalizeCerebrasReasoningEffort(s string) string

NormalizeCerebrasReasoningEffort canonicalizes a reasoning_effort value. Invalid input maps to "" (omit from the request → Cerebras default = off).

func NormalizeNarrateToolCalls

func NormalizeNarrateToolCalls(mode string) string

NormalizeNarrateToolCalls returns a valid narrate_tool_calls value ("off", "brief", or "full"), falling back to "brief" when the input is empty or unrecognized. Case-insensitive.

func ProbeQMaxStatus

func ProbeQMaxStatus(binary string) string

ProbeQMaxStatus runs `qmax status` to get auth/account info with a timeout.

func ProviderAllowed

func ProviderAllowed(id string) bool

ProviderAllowed is the entitlement seam. Today it returns true for every builtin provider — enablement is purely a local, per-user opt-in. Later this is where a cloud check (QualityMax auth / server-driven entitlement) plugs in so an org can gate which providers a given user may turn on, WITHOUT any change to the /providers UI or the picker: both consult this function, and the visible set is always (entitled ∧ enabled). Keep it the single chokepoint.

func ProviderKeySet

func ProviderKeySet(id string) bool

ProviderKeySet reports whether a usable key exists for the provider.

func ProviderModelLacksVision

func ProviderModelLacksVision(providerID, modelID string) (lacksVision, known bool)

ProviderModelLacksVision reports whether the given opencode model is known to be text-only. The second return (known) distinguishes "known text-only" from "unknown catalogue": custom providers (Z.AI coding plan) have a seeded model list we can answer authoritatively — every GLM model there is text-only, including ids not in the seed list, because the coding-plan endpoint itself accepts no image input. Known providers (Groq, OpenRouter) resolve their catalogue live via models.dev, so we cannot answer for a specific model id and report known=false; callers decide policy for the unknown case (the vision sidecar's auto mode stays out of it).

func ResolveCerebrasModel

func ResolveCerebrasModel(name string) string

ResolveCerebrasModel expands shorthand aliases to full Cerebras model IDs. Unknown values pass through unchanged so users can set raw model IDs.

""            → CerebrasDefaultModel (gpt-oss-120b)
"gemma"       → CerebrasGemma4Model (gemma-4-31b)
"gemma-4-31b" → CerebrasGemma4Model
"qwen"        → CerebrasQwen38Model (qwen-3.8)

func ResolveClaudeModel

func ResolveClaudeModel(m string) string

ResolveClaudeModel expands user-facing shorthand names to concrete Anthropic model IDs. "auto" is preserved as qmax-code's smart-routing sentinel.

func SaveAnthropicKey

func SaveAnthropicKey(key string) error

SaveAnthropicKey securely stores the Anthropic API key in the OS keychain.

func SaveAuth

func SaveAuth(cfg *AuthConfig) error

SaveAuth persists auth credentials to ~/.qmax-code/auth.json.

func SaveCerebrasKey

func SaveCerebrasKey(key string) error

SaveCerebrasKey securely stores the Cerebras API key in the OS keychain.

func SaveProviderKey

func SaveProviderKey(id, key string) error

SaveProviderKey stores a provider's API key in the OS keychain.

func SaveToKeychain

func SaveToKeychain(account, secret string) error

SaveToKeychain securely stores a key in the OS keychain. macOS: Keychain Access, Linux: secret-tool, Fallback: config.json (0600 perms)

func TrimEventsToFit

func TrimEventsToFit(events []any, maxBytes int) []any

TrimEventsToFit drops oldest events until the JSON-encoded payload fits within maxBytes. Returns the original slice if it already fits, or the last event alone if no longer suffix fits.

func ValidCerebrasReasoningEffort

func ValidCerebrasReasoningEffort(s string) bool

ValidCerebrasReasoningEffort reports whether s is an accepted reasoning_effort value. Empty and "none" keep Gemma 4 thinking off (the Cerebras default); "low", "medium", and "high" turn it on.

func ValidClaudeModelsHelp

func ValidClaudeModelsHelp() string

func ValidVisionSidecarMode

func ValidVisionSidecarMode(s string) bool

ValidVisionSidecarMode reports whether s is a storable vision_sidecar value ("" is valid — it means auto).

func ValidateCerebrasKey

func ValidateCerebrasKey(key string) (looksLikeKey bool, err error)

ValidateCerebrasKey sanity-checks a Cerebras API key before it's saved. It catches the common no-echo paste mistakes (an empty value, or a whole shell command / multi-token paste landing in the hidden prompt) by rejecting anything containing whitespace or non-printable bytes. The expected key is a single opaque token (Cerebras keys start with "csk-"); a missing prefix is a soft signal returned via the bool, not a hard error, so future key formats keep working.

func ValidateProviderKey

func ValidateProviderKey(id, key string) (looksLikeKey bool, err error)

ValidateProviderKey applies the same lenient sanity check used for the Cerebras key: reject empty, whitespace, or non-printable pastes (the common no-echo mistakes) while accepting any single opaque token. The bool reports whether the key matches the provider's expected prefix — a soft signal, not a hard failure, so future key formats keep working.

Types

type APIClient

type APIClient struct {
	BaseURL string
	APIKey  string
	HTTP    *http.Client
}

APIClient calls QualityMax REST API directly (no qmax CLI needed).

func NewAPIClient

func NewAPIClient(auth *AuthConfig) *APIClient

NewAPIClient creates a new API client from auth config.

func (*APIClient) AddScriptToFramework

func (c *APIClient) AddScriptToFramework(ctx context.Context, projectID, scriptID int) string

func (*APIClient) CheckBackgroundJob

func (c *APIClient) CheckBackgroundJob(ctx context.Context, jobID string) string

func (*APIClient) CheckTestStatus

func (c *APIClient) CheckTestStatus(ctx context.Context, executionID string) string

func (*APIClient) CompleteAgentSession

func (c *APIClient) CompleteAgentSession(ctx context.Context, cloudID string, totalTokens int, summary string)

CompleteAgentSession finalises a cloud session with status, token count, and summary. Errors are silently dropped — cloud sync failure must not block local operation.

func (*APIClient) ConnectClaudeCode

func (c *APIClient) ConnectClaudeCode(ctx context.Context, authJSON string) (*ClaudeCodeConnection, error)

ConnectClaudeCode attaches Claude Code OAuth credentials JSON to the authenticated QualityMax user. The server derives the target user from this client's bearer token.

func (*APIClient) ConnectCodex

func (c *APIClient) ConnectCodex(ctx context.Context, authJSON string) (*CodexConnection, error)

ConnectCodex attaches Codex OAuth material to the authenticated QualityMax user. The server derives the target user from this client's bearer token.

func (*APIClient) ConvertQTMLToPlaywright

func (c *APIClient) ConvertQTMLToPlaywright(ctx context.Context, qtmlContent string) string

func (*APIClient) CrawlResults

func (c *APIClient) CrawlResults(ctx context.Context, crawlID string) string

func (*APIClient) CrawlStatus

func (c *APIClient) CrawlStatus(ctx context.Context, crawlID string) string

func (*APIClient) CreateAgentSession

func (c *APIClient) CreateAgentSession(ctx context.Context, projectID int, model string) string

CreateAgentSession opens a new cloud-tracked session and returns its UUID. Returns "" on failure or when the project ID is unknown.

func (*APIClient) CreatePR

func (c *APIClient) CreatePR(ctx context.Context, repoID, projectID int) string

func (*APIClient) CreateProject

func (c *APIClient) CreateProject(ctx context.Context, name, description, baseURL string) string

func (*APIClient) CreateTestCase

func (c *APIClient) CreateTestCase(ctx context.Context, projectID int, title, description, category, priority string) string

func (*APIClient) DeleteProject

func (c *APIClient) DeleteProject(ctx context.Context, projectID int) string

func (*APIClient) DeleteTestCase

func (c *APIClient) DeleteTestCase(ctx context.Context, testCaseID int) string

func (*APIClient) EnhanceTestCase

func (c *APIClient) EnhanceTestCase(ctx context.Context, testCaseID int) string

func (*APIClient) ExportFramework

func (c *APIClient) ExportFramework(ctx context.Context, projectID int, framework string) string

func (*APIClient) ExportQTML

func (c *APIClient) ExportQTML(ctx context.Context, projectID int) string

func (*APIClient) GenerateGapTests

func (c *APIClient) GenerateGapTests(ctx context.Context, repoID int) string

func (*APIClient) GenerateTestCode

func (c *APIClient) GenerateTestCode(ctx context.Context, testCaseID int, force bool, framework string) string

func (*APIClient) GetExecutionArtifact

func (c *APIClient) GetExecutionArtifact(ctx context.Context, executionID, artifactType string) string

func (*APIClient) GetInstallCommand

func (c *APIClient) GetInstallCommand(ctx context.Context, projectID int) string

func (*APIClient) GetProjectBySlug

func (c *APIClient) GetProjectBySlug(ctx context.Context, slug string) string

func (*APIClient) GetProjectSummary

func (c *APIClient) GetProjectSummary(ctx context.Context, projectID int) string

func (*APIClient) GetReviewPreferences

func (c *APIClient) GetReviewPreferences(ctx context.Context, repoID int) string

func (*APIClient) GetScript

func (c *APIClient) GetScript(ctx context.Context, scriptID int) string

func (*APIClient) ImportDocument

func (c *APIClient) ImportDocument(ctx context.Context, projectID int, text, sourceName string) string

func (*APIClient) ImportQTML

func (c *APIClient) ImportQTML(ctx context.Context, projectID int, qtmlContent string) string

func (*APIClient) ImportRepo

func (c *APIClient) ImportRepo(ctx context.Context, url string, projectID int, createProject bool, projectName, baseURL, trainingConsent string) string

func (*APIClient) K6CheckStatus

func (c *APIClient) K6CheckStatus(ctx context.Context, executionID string) string

func (*APIClient) K6Convert

func (c *APIClient) K6Convert(ctx context.Context, sourceCode, sourceFramework, testType string) string

func (*APIClient) K6CreateScript

func (c *APIClient) K6CreateScript(ctx context.Context, projectID int, name, testType, targetURL, code string) string

func (*APIClient) K6Generate

func (c *APIClient) K6Generate(ctx context.Context, projectID int, targetURL, testType string, endpoints string) string

func (*APIClient) K6GetScript

func (c *APIClient) K6GetScript(ctx context.Context, scriptID int) string

func (*APIClient) K6ListScripts

func (c *APIClient) K6ListScripts(ctx context.Context, projectID int) string

func (*APIClient) K6Report

func (c *APIClient) K6Report(ctx context.Context, executionID string) string

func (*APIClient) K6RunTest

func (c *APIClient) K6RunTest(ctx context.Context, scriptID, vus int, duration string) string

func (*APIClient) ListAgentSessions

func (c *APIClient) ListAgentSessions(ctx context.Context, projectID, limit int) string

func (*APIClient) ListCrawlJobs

func (c *APIClient) ListCrawlJobs(ctx context.Context, limit int) string

func (*APIClient) ListProjects

func (c *APIClient) ListProjects(ctx context.Context) string

func (*APIClient) ListRepos

func (c *APIClient) ListRepos(ctx context.Context, projectID int) string

func (*APIClient) ListScripts

func (c *APIClient) ListScripts(ctx context.Context, projectID, limit int) string

func (*APIClient) ListTestCases

func (c *APIClient) ListTestCases(ctx context.Context, projectID, limit int, search string) string

func (*APIClient) RepoCoverage

func (c *APIClient) RepoCoverage(ctx context.Context, repoID int) string

func (*APIClient) RepoQuality

func (c *APIClient) RepoQuality(ctx context.Context, repoID int) string

func (*APIClient) ReportLocalResult

func (c *APIClient) ReportLocalResult(ctx context.Context, scriptID int, status, output, framework string, duration float64) string

func (*APIClient) ReviewRepo

func (c *APIClient) ReviewRepo(ctx context.Context, repoID int) string

func (*APIClient) RunNativeTest

func (c *APIClient) RunNativeTest(ctx context.Context, scriptID int, baseURL string) string

RunNativeTest executes a Rust (cargo test) / Go (go test -json) automation script through the QualityMax execution API. The backend dispatches by the script's framework field and returns a normalized result shape.

Use this when the script is framework=rust_cargo or go_test. For Playwright scripts, keep using RunTest — the cloud runner path there handles video recording, which native runs skip.

func (*APIClient) RunTest

func (c *APIClient) RunTest(ctx context.Context, scriptID int, headless bool, browser, baseURL string, useCloudSandbox bool) string

RunTest dispatches a Playwright test to the QualityMax server. When useCloudSandbox is true, the server runs the script inside a QM Cloud Sandbox and the resulting status responses include a `live_browser_url` field that the REPL turns into a /browserfeed launch. The wire field is named `use_e2b` for backwards compatibility with the server's existing contract; we expose a clean name on the client side.

We also send `live_feed_hold_seconds` so the server keeps the sandbox alive briefly after the run finishes — without that, the websockify port goes 502 by the time qmax-code's end-of-turn auto-launch fires.

func (*APIClient) RunTestsBatch

func (c *APIClient) RunTestsBatch(ctx context.Context, scriptIDs, baseURL string, useCloudSandbox bool) string

RunTestsBatch fans a batch of test IDs out to the cloud runner. Same useCloudSandbox semantics as RunTest — when true, each entry runs in a QM Cloud Sandbox and surfaces a `live_browser_url`; the REPL only auto-launches the most recent one.

func (*APIClient) SecurityAuditPRCheck

func (c *APIClient) SecurityAuditPRCheck(ctx context.Context, repoSlug string, prNumber int, baseSHA, headSHA string) string

func (*APIClient) SetReviewPreferences

func (c *APIClient) SetReviewPreferences(ctx context.Context, scope string, repoID int, preferences interface{}) string

func (*APIClient) SetupCICD

func (c *APIClient) SetupCICD(ctx context.Context, repoID int, framework, targetBranch, baseURL string) string

SetupCICD creates a GitHub Actions workflow PR on the linked repo. framework is optional — leave empty to let the server auto-detect from the repo's analyzed languages. For Rust repos the server auto-detects apt packages from Cargo.lock and injects them into the generated workflow.

func (*APIClient) StartCrawl

func (c *APIClient) StartCrawl(ctx context.Context, projectID int, url string, depth, pages int, testType, instructions string, useCloudSandbox bool) string

StartCrawl kicks off an AI crawl. Same useCloudSandbox semantics as RunTest — when true, the crawl runs inside a QM Cloud Sandbox with a headed Chromium against Xvfb, and the status poll responses include `live_browser_url`.

func (*APIClient) StartCrawlFromTestCase

func (c *APIClient) StartCrawlFromTestCase(ctx context.Context, testCaseID int) string

func (*APIClient) TestDeployedEnvironment

func (c *APIClient) TestDeployedEnvironment(ctx context.Context, projectID int, url string) string

func (*APIClient) TriggerFrameworkRun

func (c *APIClient) TriggerFrameworkRun(ctx context.Context, projectID int, frameworkType string) string

func (*APIClient) UpdateProject

func (c *APIClient) UpdateProject(ctx context.Context, projectID int, name, description, baseURL string) string

func (*APIClient) UpdateScript

func (c *APIClient) UpdateScript(ctx context.Context, scriptID int, name, code string) string

func (*APIClient) UpdateTestCase

func (c *APIClient) UpdateTestCase(ctx context.Context, testCaseID int, title, description, category, priority, status string) string

func (*APIClient) UploadSessionEvents

func (c *APIClient) UploadSessionEvents(ctx context.Context, cloudID string, events []any)

UploadSessionEvents POSTs a pre-built events list to the cloud session's /events endpoint. Errors are silently dropped — best-effort sync.

The server expects a discriminated-union body:

{"events": [{"type": "message", "payload": <...>}, ...]}

Valid event types per the server enum: file_edit, message, shell_cmd, test_result, tool_call. Caller is responsible for shape and trimming — see TrimEventsToFit for the standard size-based trimmer.

type APIRequest

type APIRequest struct {
	Model     string          `json:"model"`
	MaxTokens int             `json:"max_tokens"`
	System    string          `json:"system"`
	Messages  []Message       `json:"messages"`
	Tools     []ToolDef       `json:"tools"`
	Stream    bool            `json:"stream"`
	Thinking  *ThinkingConfig `json:"thinking,omitempty"`
}

APIRequest is the Claude API request body.

type APIResponse

type APIResponse struct {
	ID         string         `json:"id"`
	Type       string         `json:"type"`
	Role       string         `json:"role"`
	Content    []ContentBlock `json:"content"`
	StopReason string         `json:"stop_reason"`
	Usage      APIUsage       `json:"usage"`
}

APIResponse is the Claude API response (non-streaming).

type APIUsage

type APIUsage struct {
	InputTokens              int `json:"input_tokens"`
	OutputTokens             int `json:"output_tokens"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
}

APIUsage tracks token usage on a single request/response.

func (APIUsage) TotalInputTokens

func (u APIUsage) TotalInputTokens() int

TotalInputTokens includes cached prompt tokens, which count toward context limits.

type AuthConfig

type AuthConfig struct {
	APIKey   string `json:"api_key"`
	Email    string `json:"email,omitempty"`
	UserID   string `json:"user_id,omitempty"`
	CloudURL string `json:"cloud_url,omitempty"`
}

AuthConfig holds QualityMax authentication credentials.

func LoadAuth

func LoadAuth() *AuthConfig

LoadAuth loads authentication from (in priority order): 1. QUALITYMAX_API_KEY env var 2. ~/.qmax-code/auth.json 3. Legacy ~/.qamax/config.json (backward compat with qmax CLI)

func LoginWithAPIKey

func LoginWithAPIKey(apiKey string) (*AuthConfig, error)

LoginWithAPIKey validates an API key against QualityMax and saves it.

func (*AuthConfig) GetCloudURL

func (a *AuthConfig) GetCloudURL() string

GetCloudURL returns the QualityMax API URL.

func (*AuthConfig) IsAuthenticated

func (a *AuthConfig) IsAuthenticated() bool

IsAuthenticated returns true if we have a valid API key.

type ClaudeCodeConnection

type ClaudeCodeConnection struct {
	Connected    bool   `json:"connected"`
	Status       string `json:"status"`
	AccountLabel string `json:"account_label,omitempty"`
	LastRefresh  string `json:"last_refresh,omitempty"`
}

ClaudeCodeConnection is the non-sensitive connection state returned by QualityMax.

type CodexConnection

type CodexConnection struct {
	Connected    bool   `json:"connected"`
	Status       string `json:"status"`
	AccountLabel string `json:"account_label,omitempty"`
	LastRefresh  string `json:"last_refresh,omitempty"`
}

CodexConnection is the non-sensitive connection state returned by QualityMax.

type Config

type Config struct {
	DefaultModel   string `json:"default_model,omitempty"` // "auto", "sonnet", "opus", "haiku"
	DefaultProject int    `json:"default_project,omitempty"`
	// LocalOnly starts qmax-code without QualityMax authentication or cloud
	// tools. Inference still uses the selected user-owned backend, while the
	// tool catalog is limited to workspace file operations and allowlisted
	// local commands. The --local flag enables the same behavior for one run
	// without changing this persisted preference.
	LocalOnly bool `json:"local_only,omitempty"`
	// DefaultFramework is set by the first-run wizard based on filesystem
	// detection (Cargo.toml → rust_cargo, go.mod → go_test, etc.). The agent
	// reads this to default the `framework` param on generate_test_code so
	// Rust/Go users don't get Playwright scripts by accident.
	DefaultFramework string `json:"default_framework,omitempty"` // "", "playwright", "pytest", "rust_cargo", "go_test"
	Professional     bool   `json:"professional,omitempty"`      // disable cat personality
	AutoSave         bool   `json:"auto_save"`                   // auto-save session on exit (default true)
	MaxTokenBudget   int    `json:"max_token_budget,omitempty"`
	AnthropicKey     string `json:"-"` // NOT stored in JSON — use keychain instead

	// Ollama integration — use a self-hosted local model for chat and,
	// optionally, tool dispatch.
	OllamaURL        string `json:"ollama_url,omitempty"`         // e.g. "https://user:pass@llm.example.com"
	OllamaModel      string `json:"ollama_model,omitempty"`       // e.g. "gemma3:4b-it-q4_K_M" (chat)
	OllamaAgentModel string `json:"ollama_agent_model,omitempty"` // e.g. "gemma3:12b-it-q4_K_M" (tools, heavier tasks)

	// Cerebras integration — drive the native agent loop through
	// Cerebras's OpenAI-compatible inference, which is fast and low-cost. Selected
	// via backend="cerebras". Unlike the Ollama path (prompt-based dispatch over a
	// handful of actions), Cerebras uses native function-calling against the
	// active connected or standalone qmax tool set.
	// The API key is stored in the OS keychain, never in JSON.
	CerebrasKey     string `json:"-"`
	CerebrasModel   string `json:"cerebras_model,omitempty"`    // default "gpt-oss-120b"; "gemma-4-31b" for Gemma 4
	CerebrasBaseURL string `json:"cerebras_base_url,omitempty"` // default "https://api.cerebras.ai/v1"
	// CerebrasReasoningEffort toggles Gemma 4 thinking on Cerebras. Empty or
	// "none" keeps reasoning off (fastest, the Cerebras default). "low" /
	// "medium" / "high" turn it on, trading latency for more thorough answers.
	// Maps to the top-level reasoning_effort Chat Completions parameter.
	CerebrasReasoningEffort string `json:"cerebras_reasoning_effort,omitempty"`

	// Backend selects the LLM inference backend.
	//   ""  / "api" → Anthropic API directly (default, requires ANTHROPIC_API_KEY)
	//   "cc"        → Claude Code CLI subprocess (no QM API key; `claude --print`
	//                 uses Claude Code's configured subscription or provider billing)
	//   "codex"     → OpenAI Codex CLI subprocess (uses OpenAI subscription, no API key needed)
	//   "agy"       → Google Antigravity CLI subprocess (Google OAuth via
	//                 interactive `agy` Google sign-in; same Google account as AI Studio.
	//                 No Gemini API key required.)
	//   "cerebras"  → Cerebras OpenAI-compatible API (requires CEREBRAS_API_KEY).
	//                 Drives the native qmax agent loop with the full tool set via
	//                 native function calling — fast and low-cost.
	//   "opencode"  → opencode CLI subprocess. Inherits opencode's broad provider
	//                 support (Z.AI, Groq, OpenRouter, …); the specific model is
	//                 ModelOverride in "provider/model" form. Providers are opted
	//                 into per-user via EnabledProviders + the /providers command.
	// In the CLI modes (cc/codex/agy/opencode) qmax tools are served via an embedded MCP server.
	Backend string `json:"backend,omitempty"`

	// EnabledProviders is the per-user opt-in set of opencode provider IDs
	// (e.g. "zai-coding-plan", "groq", "openrouter"). Empty by default —
	// nothing is enabled for everyone. A provider only appears in this user's
	// model picker once they turn it on via /providers and supply a key. See
	// internal/api/providers.go for the registry and the entitlement seam.
	EnabledProviders []string `json:"enabled_providers,omitempty"`

	// ModelOverride is the specific model ID selected via the /orch TUI picker.
	// Empty means "let the backend pick its default". Used by CC and opencode.
	ModelOverride string `json:"model_override,omitempty"`

	// CodexModel is an optional exact model ID; empty uses Codex configuration.
	// Keep this separate so switching backends preserves the Claude preference.
	CodexModel string `json:"codex_model,omitempty"`

	// Effort controls how thorough the CLI agent should be: "low", "medium", "high".
	// Injected into the system prompt on every turn.
	Effort string `json:"effort,omitempty"`

	// OrchPermissionMode records the autonomy level the user consented to for
	// CC, Antigravity, and opencode backends. Codex uses its own approval and sandbox policy:
	//   ""           = no consent yet; activation will prompt
	//   "standard"   = curated allowlist auto-approved (reads, test runners,
	//                  qmax MCP tools); edits and destructive shell still gated
	//   "unattended" = --dangerously-skip-permissions / --full-auto, full autonomy
	// Persistence avoids re-prompting once chosen; user can revoke via /orch.
	OrchPermissionMode string `json:"orch_permission_mode,omitempty"`

	// OrchGlobalInstall records that the user opted into writing the qmax MCP
	// entry into the CLI's global config (~/.claude/settings.json or
	// ~/.codex/config.toml). False = use a per-session temp config only.
	OrchGlobalInstall bool `json:"orch_global_install,omitempty"`

	// VisionSidecar controls when image attachments on CLI-backend turns are
	// read by the Gemma 4 vision sidecar (Cerebras) and injected into the
	// CLI prompt as text descriptions, instead of diverting the whole turn
	// to the embedded multimodal backend:
	//   "" / "auto"   → sidecar only when the active CLI model is known to be
	//                   text-only (e.g. Z.AI GLM coding-plan models)
	//   "always"      → sidecar for every CLI backend turn with images
	//   "off"         → never; images follow the pre-sidecar behavior
	// Requires a Cerebras API key; without one every mode degrades to "off".
	VisionSidecar string `json:"vision_sidecar,omitempty"`

	// Theme selects the terminal color scheme.
	// Available: historic, ocean, neon, ember, aurora (dark) or paper, sky, sparkling, radiance, goldenhour (light). Empty defaults to "historic".
	Theme string `json:"theme,omitempty"`

	// OutputVerbose controls the user-facing answer style for CLI backends.
	// false = compact terminal reports; true = previous detailed report style.
	OutputVerbose bool `json:"output_verbose,omitempty"`

	// NarrateToolCalls controls how much the CLI agent prefaces each tool call
	// in the transcript. Applies to all subprocess backends (cc/codex/agy/opencode).
	//   "off"   = no preface; chained tool-call icons with only end-summary prose
	//   "brief" = one-line preface quoting the command or snippet (default)
	//   "full"  = preface + quoted key output line after; snippets always shown
	// Injected into the turn-1 system prompt via narrationDirective.
	NarrateToolCalls string `json:"narrate_tool_calls,omitempty"`

	// CloudSync controls whether sessions are synced to the QualityMax cloud.
	// nil = not asked yet (prompt fires on the next eligible session).
	// true = opted in, false = opted out.
	CloudSync *bool `json:"cloud_sync,omitempty"`

	// LiveFeed opts every test run / AI crawl into running inside a QM Cloud
	// Sandbox so the browser is streamed live into the terminal. When true,
	// MCP tool wrappers (run_test, run_tests_batch, start_crawl) flip the
	// server's use_e2b flag and the REPL auto-launches /browserfeed at the
	// end of each agent turn that produced a live URL.
	//
	// Default false — sandbox runs cost more than the pooled runners, and
	// users should opt in deliberately. Toggle via /live on|off or
	// /set live_feed true|false.
	LiveFeed bool `json:"live_feed,omitempty"`

	// PlanWindowHours overrides the assumed rolling usage-window length, in
	// hours, of the active subscription coding plan (cc / codex / opencode).
	// It drives the /plan tracker and the status-bar "resets in …" readout.
	// 0 or unset means the 5-hour default (DefaultPlanWindowHours), which
	// matches Claude Code, Codex, and OpenCode + Z.AI GLM plans.
	PlanWindowHours int `json:"plan_window_hours,omitempty"`
}

Config holds persistent user preferences for qmax-code.

func DefaultConfig

func DefaultConfig() *Config

func LoadQMaxCodeConfig

func LoadQMaxCodeConfig() *Config

LoadQMaxCodeConfig reads persistent user preferences from ~/.qmax-code/config.json and loads the Anthropic key from the OS keychain.

func (*Config) ActiveProviders

func (c *Config) ActiveProviders() []Provider

ActiveProviders returns the providers that are BOTH enabled by the user AND allowed by the entitlement seam — i.e. exactly what should be visible in the picker and driven through opencode.

func (*Config) DisableProviderID

func (c *Config) DisableProviderID(id string)

DisableProviderID removes a provider from the user's opt-in set.

func (*Config) EnableProviderID

func (c *Config) EnableProviderID(id string)

EnableProviderID adds a provider to the user's opt-in set (idempotent, sorted).

func (*Config) IsProviderEnabled

func (c *Config) IsProviderEnabled(id string) bool

IsProviderEnabled reports whether the user opted this provider in.

func (*Config) Save

func (c *Config) Save() error

Save persists the config to ~/.qmax-code/config.json.

func (*Config) VisionSidecarMode

func (c *Config) VisionSidecarMode() string

VisionSidecarMode returns the normalized sidecar mode: an unset value defaults to "auto".

type ContentBlock

type ContentBlock struct {
	Type      string       `json:"type"`
	Text      string       `json:"text,omitempty"`
	ID        string       `json:"id,omitempty"`
	Name      string       `json:"name,omitempty"`
	Input     interface{}  `json:"input,omitempty"`
	ToolUseID string       `json:"tool_use_id,omitempty"`
	Content   string       `json:"content,omitempty"`
	Source    *ImageSource `json:"source,omitempty"` // for type="image"
}

ContentBlock is a typed content block in a message.

type ConversationState

type ConversationState struct {
	Transcript []Message                     `json:"transcript"`
	Native     map[string]NativeConversation `json:"native,omitempty"`
	Handoff    *HandoffState                 `json:"handoff,omitempty"`
}

ConversationState retains the complete portable transcript separately from the model's compacted working history. Native cursors count transcript entries.

type GitInfo

type GitInfo struct {
	Branch        string
	RemoteURL     string
	RecentCommits string
	ChangedFiles  []string
}

GitInfo holds basic git context from the current directory.

func DetectGitInfo

func DetectGitInfo() *GitInfo

DetectGitInfo reads basic git info from the current directory.

type HTTPStatusError

type HTTPStatusError struct {
	StatusCode int
	Message    string
}

HTTPStatusError preserves the response status so callers can recover from expired QualityMax authentication without inspecting an error string.

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

type HandoffState

type HandoffState struct {
	RejectedApproaches []RejectedApproach `json:"rejected_approaches"`
}

HandoffState holds explicit user decisions independently of compacted history. A non-nil, empty checkpoint supersedes notes that the user has removed.

type ImageSource

type ImageSource struct {
	Type      string `json:"type"`       // "base64"
	MediaType string `json:"media_type"` // "image/png", "image/jpeg", "image/gif", "image/webp"
	Data      string `json:"data"`       // base64-encoded image data
}

ImageSource is the source data for an image content block.

type Message

type Message struct {
	Role    string      `json:"role"`
	Content interface{} `json:"content"` // string or []ContentBlock
}

Message represents a conversation message.

type NativeConversation

type NativeConversation struct {
	ID          string `json:"id"`
	Model       string `json:"model,omitempty"`
	RolloutPath string `json:"rollout_path,omitempty"`
	Directory   string `json:"directory"`
	Cursor      int    `json:"cursor"`
	// Handoff is a digest of the checkpoint this native session last received,
	// so an unchanged checkpoint is not repeated into its history every turn.
	Handoff string `json:"handoff,omitempty"`
}

NativeConversation identifies a CLI conversation on the machine/workspace that created it. It contains no credentials or provider configuration.

type PlanWindow

type PlanWindow struct {
	WindowLen  time.Duration // rolling window length (defaults to 5h)
	StartedAt  time.Time     // zero until the first turn opens a window
	Turns      int           // turns recorded in the current window
	InputToks  int           // input tokens recorded in the current window
	OutputToks int           // output tokens recorded in the current window

	// Exhausted marks that the provider refused a turn because the plan limit
	// was reached. ExhaustedReset is the provider-reported reset time when the
	// error carried one, otherwise the zero value.
	Exhausted      bool
	ExhaustedReset time.Time
}

PlanWindow tracks the current rolling usage window of a subscription coding plan so the UI can show how much of it is spent and when it resets.

It is a time-based estimate: qmax-code has no privileged access to the provider's real quota, so the window opens locally on the first orchestrated turn and rolls over once WindowLen elapses. When a provider does report an authoritative limit hit — e.g. a 429 carrying a reset/Retry-After header — MarkExhausted records it so the display reflects the real stop instead of the estimate.

PlanWindow is not safe for concurrent use; the REPL drives it from the single turn loop, the same place it folds token usage into api.TokenUsage.

func NewPlanWindow

func NewPlanWindow(windowLen time.Duration) *PlanWindow

NewPlanWindow returns a tracker with the given window length. A non-positive length falls back to the 5-hour default.

func PlanWindowFromConfig

func PlanWindowFromConfig(cfg *Config) *PlanWindow

PlanWindowFromConfig builds a tracker honoring the plan_window_hours config value (0 or unset → the 5-hour default).

func (*PlanWindow) Active

func (w *PlanWindow) Active(now time.Time) bool

Active reports whether a window is currently open (started, and either not elapsed or flagged exhausted with time still on the provider's clock).

func (*PlanWindow) Elapsed

func (w *PlanWindow) Elapsed(now time.Time) time.Duration

Elapsed is how long the current window has been open (0 if none), clamped to WindowLen.

func (*PlanWindow) MarkExhausted

func (w *PlanWindow) MarkExhausted(now time.Time, reset time.Time)

MarkExhausted records that the provider refused a turn because the plan limit was reached. reset is the provider-reported reset time, or the zero value if the error carried none (the display then falls back to the window estimate).

func (*PlanWindow) Record

func (w *PlanWindow) Record(now time.Time, inputToks, outputToks int)

Record folds one completed turn into the window. If no window is open, or the open one has reached its reset time, a fresh window starts at now. Token counts may be zero for backends that do not report usage — the time window is still tracked, so "when it resets" stays accurate even when "how full" is unknown.

Rollover uses the window's effective reset time rather than WindowLen alone. When a provider reported an authoritative reset — a 429 carrying Retry-After, say — that time wins over the local estimate, so a turn the provider accepts after it opens a fresh window instead of landing in the exhausted one and leaving the UI showing a limit that no longer applies.

func (*PlanWindow) Remaining

func (w *PlanWindow) Remaining(now time.Time) time.Duration

Remaining is how long until the current window resets (0 if none or elapsed). A provider-reported reset time wins over the local estimate.

func (*PlanWindow) ResetAt

func (w *PlanWindow) ResetAt() time.Time

ResetAt is the wall-clock time the current window resets (zero if none).

func (*PlanWindow) Started

func (w *PlanWindow) Started() bool

Started reports whether any window has been opened yet.

func (*PlanWindow) TotalTokens

func (w *PlanWindow) TotalTokens() int

TotalTokens returns the tokens recorded in the current window.

type Provider

type Provider struct {
	ID          string // opencode provider id, e.g. "zai-coding-plan", "groq"
	DisplayName string // human label shown in /providers and the picker
	SignupURL   string // where a user gets an API key

	Custom  bool            // true → write an openai-compatible provider block
	BaseURL string          // custom only: OpenAI-compatible endpoint
	Models  []ProviderModel // custom only: seed models exposed to opencode

	// KeyEnvVars are the environment variable names to set to the API key when
	// launching the opencode subprocess. For custom providers this is our own
	// substitution var referenced as "{env:...}" in the provider block. For
	// known providers these are opencode's standard vars (e.g. GROQ_API_KEY),
	// which opencode reads directly.
	KeyEnvVars []string

	KeyPrefix string // optional soft-validation hint (e.g. "gsk_" for Groq)
}

Provider describes a user-selectable, opt-in inference provider reachable through the opencode backend. These are OpenAI-compatible endpoints (Z.AI's coding plan, Groq, OpenRouter, …) that a user turns on individually via the /providers command. Nothing here is enabled for everyone by default: a provider only appears in a user's model picker once THAT user opts in and supplies a key.

Two kinds of provider:

  • Custom (Custom=true): not known to opencode/models.dev, so we write a full provider block into the managed opencode config (npm openai-compatible adapter + baseURL + a seeded model list). Z.AI's coding plan is the case.
  • Known (Custom=false): recognised by opencode via models.dev (Groq, OpenRouter). We don't define a block — supplying the standard provider env var is enough for opencode to auto-discover the live model catalogue.

func BuiltinProviders

func BuiltinProviders() []Provider

BuiltinProviders returns the catalogue of opt-in opencode providers.

func ProviderByID

func ProviderByID(id string) (Provider, bool)

ProviderByID looks up a builtin provider definition.

type ProviderModel

type ProviderModel struct {
	ID   string // model id opencode uses after the "provider/" prefix
	Name string // display name in the opencode config models map
}

ProviderModel is one model exposed by a custom provider block.

type QMaxConfig

type QMaxConfig struct {
	CloudURL string `json:"api_url"`
	Token    string `json:"token"`
	Email    string `json:"email"`
	AgentID  string `json:"agent_id"`
	APIKey   string `json:"api_key"`
}

QMaxConfig mirrors the qmax CLI config (~/.qamax/config.json).

func LoadQMaxConfig

func LoadQMaxConfig() QMaxConfig

LoadQMaxConfig reads the qmax CLI config file. Returns an empty config if the file doesn't exist — the user can log in via the qmax CLI.

type RejectedApproach

type RejectedApproach struct {
	Approach string `json:"approach"`
	Evidence string `json:"evidence"`
}

RejectedApproach records what was ruled out and the evidence supplied by the user.

type SessionContext

type SessionContext struct {
	ProjectID   int
	LocalOnly   bool // true = no QualityMax auth/cloud tools for this process
	QMaxCfg     QMaxConfig
	QMaxBin     string      // resolved path to legacy qmax binary; empty for direct API/local-only paths
	QMaxInfo    string      // output of `qmax status` at startup
	GitInfo     *GitInfo    // git context from cwd
	ProjectFile string      // name of .qmax.yml file if detected
	API         *APIClient  // direct QualityMax API client (no legacy qmax CLI needed)
	Auth        *AuthConfig // authentication credentials
	Backend     string      // "" | "cc" | "codex" | "agy" | "opencode" — active CLI inference backend

	// LiveFeed enables QM Cloud Sandbox execution for run_test / start_crawl
	// and turns on auto-launch of /browserfeed when a poll response surfaces
	// a live URL. Mirrors Config.LiveFeed; refreshed on every /set live_feed
	// or /live toggle so the dispatcher always sees the current value.
	LiveFeed bool

	// LastLiveURL holds the most recent `live_browser_url` extracted from a
	// run/crawl status poll. The REPL drains this between agent turns to
	// auto-launch the feed; tool handlers write to it via captureLiveURL.
	LastLiveURL string

	// turn-scoped diagnostic flags reset by the REPL before each agent
	// invocation. Make captureLiveURL chatty *once* per turn rather than
	// per poll, so users see "live URL captured" or a fallback warning
	// without having every poll spam the screen.
	LiveURLLogged       bool
	SandboxModeLogged   bool
	SandboxFallbackSeen bool
}

SessionContext holds the runtime context for the agent session.

type ThinkingConfig

type ThinkingConfig struct {
	Type string `json:"type"`
}

ThinkingConfig controls Anthropic thinking without sending sampling parameters.

func DefaultThinking

func DefaultThinking(model string) *ThinkingConfig

DefaultThinking reserves Haiku 5.5's response budget for visible text and tools. qmax-code does not retain the signed thinking blocks needed for replay.

type TokenUsage

type TokenUsage struct {
	InputTokens              int
	OutputTokens             int
	Requests                 int
	CacheReadInputTokens     int      `json:",omitempty"`
	CacheCreationInputTokens int      `json:",omitempty"`
	CostUSD                  *float64 `json:",omitempty"`
}

TokenUsage tracks cumulative token usage across the session.

func (*TokenUsage) EstimatedCost

func (u *TokenUsage) EstimatedCost(model string) float64

EstimatedCost returns recorded per-request estimates when available. Legacy aggregate-only usage is estimated using the supplied model and current rates. Cache writes use the five-minute rate; CLI plan billing is provider-owned.

func (*TokenUsage) RecordRequest

func (u *TokenUsage) RecordRequest(model string, usage APIUsage)

RecordRequest retains each request's estimated API cost before totals lose its model, pricing date, and prompt-size tier. Legacy sessions without costs use their aggregate estimate for the existing portion of the session.

func (*TokenUsage) TotalInputTokens

func (u *TokenUsage) TotalInputTokens() int

TotalInputTokens includes both uncached and cached prompt tokens.

func (*TokenUsage) TotalTokens

func (u *TokenUsage) TotalTokens() int

TotalTokens returns the total token count.

type ToolDef

type ToolDef struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	InputSchema map[string]interface{} `json:"input_schema"`
}

ToolDef is a Claude API tool definition.

Jump to

Keyboard shortcuts

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