{"modulePath":"github.com/Quality-Max/qmax-code","version":"v1.40.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package api\n\n## Constants\n\n```go\nconst (\n\tAnthropicMessagesURL = \"https://api.anthropic.com/v1/messages\"\n\tAnthropicVersion     = \"2023-06-01\"\n\tModelFable51         = \"claude-fable-5-1\"\n\tModelFable           = \"claude-fable-5\"\n\tModelHaiku           = \"claude-haiku-4-5-20251001\"\n\tModelHaiku55         = \"claude-haiku-5-5\"\n\tModelSonnet5         = \"claude-sonnet-5\"\n\tModelSonnet          = \"claude-sonnet-4-6\"\n\tModelOpus55          = \"claude-opus-5-5\"  // latest Opus; the \"opus\" shorthand resolves here\n\tModelOpus            = \"claude-opus-4-8\"  // prior Opus, still selectable by full ID\n\tModelOpus1M          = ModelOpus + \"[1m]\" // Claude Code 1M-context selector (Opus 4.8)\n\tModelOpus47          = \"claude-opus-4-7\"  // older Opus, still selectable by full ID\n)\n```\nAnthropic defaults for smart routing and direct API calls.\n\n```go\nconst (\n\t// CerebrasAPIBase is the default OpenAI-compatible base URL.\n\tCerebrasAPIBase = \"https://api.cerebras.ai/v1\"\n\t// CerebrasDefaultModel is a fast, capable general/coding model on Cerebras.\n\tCerebrasDefaultModel = \"gpt-oss-120b\"\n\t// CerebrasGemma4Model is Google DeepMind's Gemma 4 31B as hosted on\n\t// Cerebras. It is multimodal (text + image input, text output) and exposes\n\t// reasoning via the top-level reasoning_effort parameter (off by default).\n\t// Model ID per the Cerebras + Gemma 4 hackathon docs.\n\tCerebrasGemma4Model = \"gemma-4-31b\"\n\t// CerebrasQwen38Model is Alibaba's Qwen 3.8 as hosted on Cerebras.\n\t// Announced as coming soon to the Cerebras model catalog; the ID follows\n\t// Cerebras naming and must be confirmed against the live API at launch.\n\tCerebrasQwen38Model = \"qwen-3.8\"\n)\n```\nCerebras 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.\n\nAuth 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.\n\n```go\nconst (\n\tVisionSidecarAuto   = \"auto\"\n\tVisionSidecarAlways = \"always\"\n\tVisionSidecarOff    = \"off\"\n)\n```\nVision sidecar modes.\n\n```go\nconst DefaultCloudURL = \"https://app.qualitymax.io\"\n```\n\n```go\nconst DefaultPlanWindowHours = 5\n```\nDefaultPlanWindowHours 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.\n\n```go\nconst LocalOnlyEnv = \"QMAX_LOCAL_ONLY\"\n```\n\n```go\nconst MaxSessionUploadBytes = 4 * 1024 * 1024 // 4 MiB\n\n```\nMaxSessionUploadBytes caps the serialized event payload to avoid server rejection or excessive upload times on very long sessions.\n\n```go\nconst QmaxCodeConfigDir = \".qmax-code\"\n```\n\n## Variables\n\n```go\nvar AllowedFrameworks = map[string]bool{\n\t\"\":           true,\n\t\"playwright\": true,\n\t\"pytest\":     true,\n\t\"go\":         true,\n\t\"rust\":       true,\n\t\"go_test\":    true,\n\t\"rust_cargo\": true,\n\t\"cargo\":      true,\n}\n```\nAllowedFrameworks 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.\n\n## Functions\n\n```go\nfunc ContextWindow(model string) int\n```\nContextWindow 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.\n\n```go\nfunc DeleteFromKeychain(account string) error\n```\nDeleteFromKeychain removes a key from the OS keychain.\n\n```go\nfunc DeleteProviderKey(id string) error\n```\nDeleteProviderKey removes a provider's API key from the OS keychain.\n\n```go\nfunc DetectProjectFromCwd() (int, string)\n```\nDetectProjectFromCwd checks for .qmax.yml or .qualitymax.yml in cwd.\n\n```go\nfunc DiscoverQMaxBinary() string\n```\nDiscoverQMaxBinary finds the qmax binary, checking multiple locations. Order: ./qmax, ~/.qmax/qmax, then PATH.\n\n```go\nfunc FormatQMaxInstallHint() string\n```\nFormatQMaxInstallHint returns install instructions when qmax is missing.\n\n```go\nfunc IsCerebrasGemma4Model(modelID string) bool\n```\nIsCerebrasGemma4Model reports whether modelID is the Gemma 4 31B variant. Used to gate Gemma-specific behavior (reasoning, multimodal nudges).\n\n```go\nfunc IsValidClaudeModelName(m string) bool\n```\nIsValidClaudeModelName 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.\n\n```go\nfunc LoadFromKeychain(account string) (string, error)\n```\nLoadFromKeychain retrieves a key from the OS keychain.\n\n```go\nfunc LoadProviderKey(id string) string\n```\nLoadProviderKey retrieves a provider's API key from the OS keychain, falling back to any of the provider's standard environment variables.\n\n```go\nfunc NormalizeCerebrasReasoningEffort(s string) string\n```\nNormalizeCerebrasReasoningEffort canonicalizes a reasoning\\_effort value. Invalid input maps to \"\" (omit from the request → Cerebras default = off).\n\n```go\nfunc NormalizeNarrateToolCalls(mode string) string\n```\nNormalizeNarrateToolCalls returns a valid narrate\\_tool\\_calls value (\"off\", \"brief\", or \"full\"), falling back to \"brief\" when the input is empty or unrecognized. Case-insensitive.\n\n```go\nfunc ProbeQMaxStatus(binary string) string\n```\nProbeQMaxStatus runs \\`qmax status\\` to get auth/account info with a timeout.\n\n```go\nfunc ProviderAllowed(id string) bool\n```\nProviderAllowed 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.\n\n```go\nfunc ProviderKeySet(id string) bool\n```\nProviderKeySet reports whether a usable key exists for the provider.\n\n```go\nfunc ProviderModelLacksVision(providerID, modelID string) (lacksVision, known bool)\n```\nProviderModelLacksVision 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).\n\n```go\nfunc ResolveCerebrasModel(name string) string\n```\nResolveCerebrasModel expands shorthand aliases to full Cerebras model IDs. Unknown values pass through unchanged so users can set raw model IDs.\n\n\t\"\"            → CerebrasDefaultModel (gpt-oss-120b)\n\t\"gemma\"       → CerebrasGemma4Model (gemma-4-31b)\n\t\"gemma-4-31b\" → CerebrasGemma4Model\n\t\"qwen\"        → CerebrasQwen38Model (qwen-3.8)\n\n```go\nfunc ResolveClaudeModel(m string) string\n```\nResolveClaudeModel expands user-facing shorthand names to concrete Anthropic model IDs. \"auto\" is preserved as qmax-code's smart-routing sentinel.\n\n```go\nfunc SaveAnthropicKey(key string) error\n```\nSaveAnthropicKey securely stores the Anthropic API key in the OS keychain.\n\n```go\nfunc SaveAuth(cfg *AuthConfig) error\n```\nSaveAuth persists auth credentials to ~/.qmax-code/auth.json.\n\n```go\nfunc SaveCerebrasKey(key string) error\n```\nSaveCerebrasKey securely stores the Cerebras API key in the OS keychain.\n\n```go\nfunc SaveProviderKey(id, key string) error\n```\nSaveProviderKey stores a provider's API key in the OS keychain.\n\n```go\nfunc SaveToKeychain(account, secret string) error\n```\nSaveToKeychain securely stores a key in the OS keychain. macOS: Keychain Access, Linux: secret-tool, Fallback: config.json (0600 perms)\n\n```go\nfunc TrimEventsToFit(events []any, maxBytes int) []any\n```\nTrimEventsToFit 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.\n\n```go\nfunc ValidCerebrasReasoningEffort(s string) bool\n```\nValidCerebrasReasoningEffort 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.\n\n```go\nfunc ValidClaudeModelsHelp() string\n```\n\n```go\nfunc ValidVisionSidecarMode(s string) bool\n```\nValidVisionSidecarMode reports whether s is a storable vision\\_sidecar value (\"\" is valid — it means auto).\n\n```go\nfunc ValidateCerebrasKey(key string) (looksLikeKey bool, err error)\n```\nValidateCerebrasKey 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.\n\n```go\nfunc ValidateProviderKey(id, key string) (looksLikeKey bool, err error)\n```\nValidateProviderKey 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.\n\n## Types\n\n```go\ntype APIClient struct {\n\tBaseURL string\n\tAPIKey  string\n\tHTTP    *http.Client\n}\n```\nAPIClient calls QualityMax REST API directly (no qmax CLI needed).\n\n```go\nfunc NewAPIClient(auth *AuthConfig) *APIClient\n```\nNewAPIClient creates a new API client from auth config.\n\n```go\nfunc (c *APIClient) AddScriptToFramework(ctx context.Context, projectID, scriptID int) string\n```\n\n```go\nfunc (c *APIClient) CheckBackgroundJob(ctx context.Context, jobID string) string\n```\n\n```go\nfunc (c *APIClient) CheckTestStatus(ctx context.Context, executionID string) string\n```\n\n```go\nfunc (c *APIClient) CompleteAgentSession(ctx context.Context, cloudID string, totalTokens int, summary string)\n```\nCompleteAgentSession finalises a cloud session with status, token count, and summary. Errors are silently dropped — cloud sync failure must not block local operation.\n\n```go\nfunc (c *APIClient) ConnectClaudeCode(ctx context.Context, authJSON string) (*ClaudeCodeConnection, error)\n```\nConnectClaudeCode attaches Claude Code OAuth credentials JSON to the authenticated QualityMax user. The server derives the target user from this client's bearer token.\n\n```go\nfunc (c *APIClient) ConnectCodex(ctx context.Context, authJSON string) (*CodexConnection, error)\n```\nConnectCodex attaches Codex OAuth material to the authenticated QualityMax user. The server derives the target user from this client's bearer token.\n\n```go\nfunc (c *APIClient) ConvertQTMLToPlaywright(ctx context.Context, qtmlContent string) string\n```\n\n```go\nfunc (c *APIClient) CrawlResults(ctx context.Context, crawlID string) string\n```\n\n```go\nfunc (c *APIClient) CrawlStatus(ctx context.Context, crawlID string) string\n```\n\n```go\nfunc (c *APIClient) CreateAgentSession(ctx context.Context, projectID int, model string) string\n```\nCreateAgentSession opens a new cloud-tracked session and returns its UUID. Returns \"\" on failure or when the project ID is unknown.\n\n```go\nfunc (c *APIClient) CreatePR(ctx context.Context, repoID, projectID int) string\n```\n\n```go\nfunc (c *APIClient) CreateProject(ctx context.Context, name, description, baseURL string) string\n```\n\n```go\nfunc (c *APIClient) CreateTestCase(ctx context.Context, projectID int, title, description, category, priority string) string\n```\n\n```go\nfunc (c *APIClient) DeleteProject(ctx context.Context, projectID int) string\n```\n\n```go\nfunc (c *APIClient) DeleteTestCase(ctx context.Context, testCaseID int) string\n```\n\n```go\nfunc (c *APIClient) EnhanceTestCase(ctx context.Context, testCaseID int) string\n```\n\n```go\nfunc (c *APIClient) ExportFramework(ctx context.Context, projectID int, framework string) string\n```\n\n```go\nfunc (c *APIClient) ExportQTML(ctx context.Context, projectID int) string\n```\n\n```go\nfunc (c *APIClient) GenerateGapTests(ctx context.Context, repoID int) string\n```\n\n```go\nfunc (c *APIClient) GenerateTestCode(ctx context.Context, testCaseID int, force bool, framework string) string\n```\n\n```go\nfunc (c *APIClient) GetExecutionArtifact(ctx context.Context, executionID, artifactType string) string\n```\n\n```go\nfunc (c *APIClient) GetInstallCommand(ctx context.Context, projectID int) string\n```\n\n```go\nfunc (c *APIClient) GetProjectBySlug(ctx context.Context, slug string) string\n```\n\n```go\nfunc (c *APIClient) GetProjectSummary(ctx context.Context, projectID int) string\n```\n\n```go\nfunc (c *APIClient) GetReviewPreferences(ctx context.Context, repoID int) string\n```\n\n```go\nfunc (c *APIClient) GetScript(ctx context.Context, scriptID int) string\n```\n\n```go\nfunc (c *APIClient) ImportDocument(ctx context.Context, projectID int, text, sourceName string) string\n```\n\n```go\nfunc (c *APIClient) ImportQTML(ctx context.Context, projectID int, qtmlContent string) string\n```\n\n```go\nfunc (c *APIClient) ImportRepo(ctx context.Context, url string, projectID int, createProject bool, projectName, baseURL, trainingConsent string) string\n```\n\n```go\nfunc (c *APIClient) K6CheckStatus(ctx context.Context, executionID string) string\n```\n\n```go\nfunc (c *APIClient) K6Convert(ctx context.Context, sourceCode, sourceFramework, testType string) string\n```\n\n```go\nfunc (c *APIClient) K6CreateScript(ctx context.Context, projectID int, name, testType, targetURL, code string) string\n```\n\n```go\nfunc (c *APIClient) K6Generate(ctx context.Context, projectID int, targetURL, testType string, endpoints string) string\n```\n\n```go\nfunc (c *APIClient) K6GetScript(ctx context.Context, scriptID int) string\n```\n\n```go\nfunc (c *APIClient) K6ListScripts(ctx context.Context, projectID int) string\n```\n\n```go\nfunc (c *APIClient) K6Report(ctx context.Context, executionID string) string\n```\n\n```go\nfunc (c *APIClient) K6RunTest(ctx context.Context, scriptID, vus int, duration string) string\n```\n\n```go\nfunc (c *APIClient) ListAgentSessions(ctx context.Context, projectID, limit int) string\n```\n\n```go\nfunc (c *APIClient) ListCrawlJobs(ctx context.Context, limit int) string\n```\n\n```go\nfunc (c *APIClient) ListProjects(ctx context.Context) string\n```\n\n```go\nfunc (c *APIClient) ListRepos(ctx context.Context, projectID int) string\n```\n\n```go\nfunc (c *APIClient) ListScripts(ctx context.Context, projectID, limit int) string\n```\n\n```go\nfunc (c *APIClient) ListTestCases(ctx context.Context, projectID, limit int, search string) string\n```\n\n```go\nfunc (c *APIClient) RepoCoverage(ctx context.Context, repoID int) string\n```\n\n```go\nfunc (c *APIClient) RepoQuality(ctx context.Context, repoID int) string\n```\n\n```go\nfunc (c *APIClient) ReportLocalResult(ctx context.Context, scriptID int, status, output, framework string, duration float64) string\n```\n\n```go\nfunc (c *APIClient) ReviewRepo(ctx context.Context, repoID int) string\n```\n\n```go\nfunc (c *APIClient) RunNativeTest(ctx context.Context, scriptID int, baseURL string) string\n```\nRunNativeTest 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.\n\nUse 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.\n\n```go\nfunc (c *APIClient) RunTest(ctx context.Context, scriptID int, headless bool, browser, baseURL string, useCloudSandbox bool) string\n```\nRunTest 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.\n\nWe 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.\n\n```go\nfunc (c *APIClient) RunTestsBatch(ctx context.Context, scriptIDs, baseURL string, useCloudSandbox bool) string\n```\nRunTestsBatch 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.\n\n```go\nfunc (c *APIClient) SecurityAuditPRCheck(ctx context.Context, repoSlug string, prNumber int, baseSHA, headSHA string) string\n```\n\n```go\nfunc (c *APIClient) SetReviewPreferences(ctx context.Context, scope string, repoID int, preferences interface{}) string\n```\n\n```go\nfunc (c *APIClient) SetupCICD(ctx context.Context, repoID int, framework, targetBranch, baseURL string) string\n```\nSetupCICD 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.\n\n```go\nfunc (c *APIClient) StartCrawl(ctx context.Context, projectID int, url string, depth, pages int, testType, instructions string, useCloudSandbox bool) string\n```\nStartCrawl 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\\`.\n\n```go\nfunc (c *APIClient) StartCrawlFromTestCase(ctx context.Context, testCaseID int) string\n```\n\n```go\nfunc (c *APIClient) TestDeployedEnvironment(ctx context.Context, projectID int, url string) string\n```\n\n```go\nfunc (c *APIClient) TriggerFrameworkRun(ctx context.Context, projectID int, frameworkType string) string\n```\n\n```go\nfunc (c *APIClient) UpdateProject(ctx context.Context, projectID int, name, description, baseURL string) string\n```\n\n```go\nfunc (c *APIClient) UpdateScript(ctx context.Context, scriptID int, name, code string) string\n```\n\n```go\nfunc (c *APIClient) UpdateTestCase(ctx context.Context, testCaseID int, title, description, category, priority, status string) string\n```\n\n```go\nfunc (c *APIClient) UploadSessionEvents(ctx context.Context, cloudID string, events []any)\n```\nUploadSessionEvents POSTs a pre-built events list to the cloud session's /events endpoint. Errors are silently dropped — best-effort sync.\n\nThe server expects a discriminated-union body:\n\n\t{\"events\": [{\"type\": \"message\", \"payload\": \u003c...\u003e}, ...]}\n\nValid 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.\n\n```go\ntype APIRequest struct {\n\tModel     string          `json:\"model\"`\n\tMaxTokens int             `json:\"max_tokens\"`\n\tSystem    string          `json:\"system\"`\n\tMessages  []Message       `json:\"messages\"`\n\tTools     []ToolDef       `json:\"tools\"`\n\tStream    bool            `json:\"stream\"`\n\tThinking  *ThinkingConfig `json:\"thinking,omitempty\"`\n}\n```\nAPIRequest is the Claude API request body.\n\n```go\ntype APIResponse struct {\n\tID         string         `json:\"id\"`\n\tType       string         `json:\"type\"`\n\tRole       string         `json:\"role\"`\n\tContent    []ContentBlock `json:\"content\"`\n\tStopReason string         `json:\"stop_reason\"`\n\tUsage      APIUsage       `json:\"usage\"`\n}\n```\nAPIResponse is the Claude API response (non-streaming).\n\n```go\ntype APIUsage struct {\n\tInputTokens              int `json:\"input_tokens\"`\n\tOutputTokens             int `json:\"output_tokens\"`\n\tCacheReadInputTokens     int `json:\"cache_read_input_tokens\"`\n\tCacheCreationInputTokens int `json:\"cache_creation_input_tokens\"`\n}\n```\nAPIUsage tracks token usage on a single request/response.\n\n```go\nfunc (u APIUsage) TotalInputTokens() int\n```\nTotalInputTokens includes cached prompt tokens, which count toward context limits.\n\n```go\ntype AuthConfig struct {\n\tAPIKey   string `json:\"api_key\"`\n\tEmail    string `json:\"email,omitempty\"`\n\tUserID   string `json:\"user_id,omitempty\"`\n\tCloudURL string `json:\"cloud_url,omitempty\"`\n}\n```\nAuthConfig holds QualityMax authentication credentials.\n\n```go\nfunc LoadAuth() *AuthConfig\n```\nLoadAuth 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)\n\n```go\nfunc LoginWithAPIKey(apiKey string) (*AuthConfig, error)\n```\nLoginWithAPIKey validates an API key against QualityMax and saves it.\n\n```go\nfunc (a *AuthConfig) GetCloudURL() string\n```\nGetCloudURL returns the QualityMax API URL.\n\n```go\nfunc (a *AuthConfig) IsAuthenticated() bool\n```\nIsAuthenticated returns true if we have a valid API key.\n\n```go\ntype ClaudeCodeConnection struct {\n\tConnected    bool   `json:\"connected\"`\n\tStatus       string `json:\"status\"`\n\tAccountLabel string `json:\"account_label,omitempty\"`\n\tLastRefresh  string `json:\"last_refresh,omitempty\"`\n}\n```\nClaudeCodeConnection is the non-sensitive connection state returned by QualityMax.\n\n```go\ntype CodexConnection struct {\n\tConnected    bool   `json:\"connected\"`\n\tStatus       string `json:\"status\"`\n\tAccountLabel string `json:\"account_label,omitempty\"`\n\tLastRefresh  string `json:\"last_refresh,omitempty\"`\n}\n```\nCodexConnection is the non-sensitive connection state returned by QualityMax.\n\n```go\ntype Config struct {\n\tDefaultModel   string `json:\"default_model,omitempty\"` // \"auto\", \"sonnet\", \"opus\", \"haiku\"\n\tDefaultProject int    `json:\"default_project,omitempty\"`\n\t// LocalOnly starts qmax-code without QualityMax authentication or cloud\n\t// tools. Inference still uses the selected user-owned backend, while the\n\t// tool catalog is limited to workspace file operations and allowlisted\n\t// local commands. The --local flag enables the same behavior for one run\n\t// without changing this persisted preference.\n\tLocalOnly bool `json:\"local_only,omitempty\"`\n\t// DefaultFramework is set by the first-run wizard based on filesystem\n\t// detection (Cargo.toml → rust_cargo, go.mod → go_test, etc.). The agent\n\t// reads this to default the `framework` param on generate_test_code so\n\t// Rust/Go users don't get Playwright scripts by accident.\n\tDefaultFramework string `json:\"default_framework,omitempty\"` // \"\", \"playwright\", \"pytest\", \"rust_cargo\", \"go_test\"\n\tProfessional     bool   `json:\"professional,omitempty\"`      // disable cat personality\n\tAutoSave         bool   `json:\"auto_save\"`                   // auto-save session on exit (default true)\n\tMaxTokenBudget   int    `json:\"max_token_budget,omitempty\"`\n\tAnthropicKey     string `json:\"-\"` // NOT stored in JSON — use keychain instead\n\n\t// Ollama integration — use a self-hosted local model for chat and,\n\t// optionally, tool dispatch.\n\tOllamaURL        string `json:\"ollama_url,omitempty\"`         // e.g. \"https://user:pass@llm.example.com\"\n\tOllamaModel      string `json:\"ollama_model,omitempty\"`       // e.g. \"gemma3:4b-it-q4_K_M\" (chat)\n\tOllamaAgentModel string `json:\"ollama_agent_model,omitempty\"` // e.g. \"gemma3:12b-it-q4_K_M\" (tools, heavier tasks)\n\n\t// Cerebras integration — drive the native agent loop through\n\t// Cerebras's OpenAI-compatible inference, which is fast and low-cost. Selected\n\t// via backend=\"cerebras\". Unlike the Ollama path (prompt-based dispatch over a\n\t// handful of actions), Cerebras uses native function-calling against the\n\t// active connected or standalone qmax tool set.\n\t// The API key is stored in the OS keychain, never in JSON.\n\tCerebrasKey     string `json:\"-\"`\n\tCerebrasModel   string `json:\"cerebras_model,omitempty\"`    // default \"gpt-oss-120b\"; \"gemma-4-31b\" for Gemma 4\n\tCerebrasBaseURL string `json:\"cerebras_base_url,omitempty\"` // default \"https://api.cerebras.ai/v1\"\n\t// CerebrasReasoningEffort toggles Gemma 4 thinking on Cerebras. Empty or\n\t// \"none\" keeps reasoning off (fastest, the Cerebras default). \"low\" /\n\t// \"medium\" / \"high\" turn it on, trading latency for more thorough answers.\n\t// Maps to the top-level reasoning_effort Chat Completions parameter.\n\tCerebrasReasoningEffort string `json:\"cerebras_reasoning_effort,omitempty\"`\n\n\t// Backend selects the LLM inference backend.\n\t//   \"\"  / \"api\" → Anthropic API directly (default, requires ANTHROPIC_API_KEY)\n\t//   \"cc\"        → Claude Code CLI subprocess (no QM API key; `claude --print`\n\t//                 uses Claude Code's configured subscription or provider billing)\n\t//   \"codex\"     → OpenAI Codex CLI subprocess (uses OpenAI subscription, no API key needed)\n\t//   \"agy\"       → Google Antigravity CLI subprocess (Google OAuth via\n\t//                 interactive `agy` Google sign-in; same Google account as AI Studio.\n\t//                 No Gemini API key required.)\n\t//   \"cerebras\"  → Cerebras OpenAI-compatible API (requires CEREBRAS_API_KEY).\n\t//                 Drives the native qmax agent loop with the full tool set via\n\t//                 native function calling — fast and low-cost.\n\t//   \"opencode\"  → opencode CLI subprocess. Inherits opencode's broad provider\n\t//                 support (Z.AI, Groq, OpenRouter, …); the specific model is\n\t//                 ModelOverride in \"provider/model\" form. Providers are opted\n\t//                 into per-user via EnabledProviders + the /providers command.\n\t// In the CLI modes (cc/codex/agy/opencode) qmax tools are served via an embedded MCP server.\n\tBackend string `json:\"backend,omitempty\"`\n\n\t// EnabledProviders is the per-user opt-in set of opencode provider IDs\n\t// (e.g. \"zai-coding-plan\", \"groq\", \"openrouter\"). Empty by default —\n\t// nothing is enabled for everyone. A provider only appears in this user's\n\t// model picker once they turn it on via /providers and supply a key. See\n\t// internal/api/providers.go for the registry and the entitlement seam.\n\tEnabledProviders []string `json:\"enabled_providers,omitempty\"`\n\n\t// ModelOverride is the specific model ID selected via the /orch TUI picker.\n\t// Empty means \"let the backend pick its default\". Used by CC and opencode.\n\tModelOverride string `json:\"model_override,omitempty\"`\n\n\t// CodexModel is an optional exact model ID; empty uses Codex configuration.\n\t// Keep this separate so switching backends preserves the Claude preference.\n\tCodexModel string `json:\"codex_model,omitempty\"`\n\n\t// Effort controls how thorough the CLI agent should be: \"low\", \"medium\", \"high\".\n\t// Injected into the system prompt on every turn.\n\tEffort string `json:\"effort,omitempty\"`\n\n\t// OrchPermissionMode records the autonomy level the user consented to for\n\t// CC, Antigravity, and opencode backends. Codex uses its own approval and sandbox policy:\n\t//   \"\"           = no consent yet; activation will prompt\n\t//   \"standard\"   = curated allowlist auto-approved (reads, test runners,\n\t//                  qmax MCP tools); edits and destructive shell still gated\n\t//   \"unattended\" = --dangerously-skip-permissions / --full-auto, full autonomy\n\t// Persistence avoids re-prompting once chosen; user can revoke via /orch.\n\tOrchPermissionMode string `json:\"orch_permission_mode,omitempty\"`\n\n\t// OrchGlobalInstall records that the user opted into writing the qmax MCP\n\t// entry into the CLI's global config (~/.claude/settings.json or\n\t// ~/.codex/config.toml). False = use a per-session temp config only.\n\tOrchGlobalInstall bool `json:\"orch_global_install,omitempty\"`\n\n\t// VisionSidecar controls when image attachments on CLI-backend turns are\n\t// read by the Gemma 4 vision sidecar (Cerebras) and injected into the\n\t// CLI prompt as text descriptions, instead of diverting the whole turn\n\t// to the embedded multimodal backend:\n\t//   \"\" / \"auto\"   → sidecar only when the active CLI model is known to be\n\t//                   text-only (e.g. Z.AI GLM coding-plan models)\n\t//   \"always\"      → sidecar for every CLI backend turn with images\n\t//   \"off\"         → never; images follow the pre-sidecar behavior\n\t// Requires a Cerebras API key; without one every mode degrades to \"off\".\n\tVisionSidecar string `json:\"vision_sidecar,omitempty\"`\n\n\t// Theme selects the terminal color scheme.\n\t// Available: historic, ocean, neon, ember, aurora (dark) or paper, sky, sparkling, radiance, goldenhour (light). Empty defaults to \"historic\".\n\tTheme string `json:\"theme,omitempty\"`\n\n\t// OutputVerbose controls the user-facing answer style for CLI backends.\n\t// false = compact terminal reports; true = previous detailed report style.\n\tOutputVerbose bool `json:\"output_verbose,omitempty\"`\n\n\t// NarrateToolCalls controls how much the CLI agent prefaces each tool call\n\t// in the transcript. Applies to all subprocess backends (cc/codex/agy/opencode).\n\t//   \"off\"   = no preface; chained tool-call icons with only end-summary prose\n\t//   \"brief\" = one-line preface quoting the command or snippet (default)\n\t//   \"full\"  = preface + quoted key output line after; snippets always shown\n\t// Injected into the turn-1 system prompt via narrationDirective.\n\tNarrateToolCalls string `json:\"narrate_tool_calls,omitempty\"`\n\n\t// CloudSync controls whether sessions are synced to the QualityMax cloud.\n\t// nil = not asked yet (prompt fires on the next eligible session).\n\t// true = opted in, false = opted out.\n\tCloudSync *bool `json:\"cloud_sync,omitempty\"`\n\n\t// LiveFeed opts every test run / AI crawl into running inside a QM Cloud\n\t// Sandbox so the browser is streamed live into the terminal. When true,\n\t// MCP tool wrappers (run_test, run_tests_batch, start_crawl) flip the\n\t// server's use_e2b flag and the REPL auto-launches /browserfeed at the\n\t// end of each agent turn that produced a live URL.\n\t//\n\t// Default false — sandbox runs cost more than the pooled runners, and\n\t// users should opt in deliberately. Toggle via /live on|off or\n\t// /set live_feed true|false.\n\tLiveFeed bool `json:\"live_feed,omitempty\"`\n\n\t// PlanWindowHours overrides the assumed rolling usage-window length, in\n\t// hours, of the active subscription coding plan (cc / codex / opencode).\n\t// It drives the /plan tracker and the status-bar \"resets in …\" readout.\n\t// 0 or unset means the 5-hour default (DefaultPlanWindowHours), which\n\t// matches Claude Code, Codex, and OpenCode + Z.AI GLM plans.\n\tPlanWindowHours int `json:\"plan_window_hours,omitempty\"`\n}\n```\nConfig holds persistent user preferences for qmax-code.\n\n```go\nfunc DefaultConfig() *Config\n```\n\n```go\nfunc LoadQMaxCodeConfig() *Config\n```\nLoadQMaxCodeConfig reads persistent user preferences from ~/.qmax-code/config.json and loads the Anthropic key from the OS keychain.\n\n```go\nfunc (c *Config) ActiveProviders() []Provider\n```\nActiveProviders 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.\n\n```go\nfunc (c *Config) DisableProviderID(id string)\n```\nDisableProviderID removes a provider from the user's opt-in set.\n\n```go\nfunc (c *Config) EnableProviderID(id string)\n```\nEnableProviderID adds a provider to the user's opt-in set (idempotent, sorted).\n\n```go\nfunc (c *Config) IsProviderEnabled(id string) bool\n```\nIsProviderEnabled reports whether the user opted this provider in.\n\n```go\nfunc (c *Config) Save() error\n```\nSave persists the config to ~/.qmax-code/config.json.\n\n```go\nfunc (c *Config) VisionSidecarMode() string\n```\nVisionSidecarMode returns the normalized sidecar mode: an unset value defaults to \"auto\".\n\n```go\ntype ContentBlock struct {\n\tType      string       `json:\"type\"`\n\tText      string       `json:\"text,omitempty\"`\n\tID        string       `json:\"id,omitempty\"`\n\tName      string       `json:\"name,omitempty\"`\n\tInput     interface{}  `json:\"input,omitempty\"`\n\tToolUseID string       `json:\"tool_use_id,omitempty\"`\n\tContent   string       `json:\"content,omitempty\"`\n\tSource    *ImageSource `json:\"source,omitempty\"` // for type=\"image\"\n}\n```\nContentBlock is a typed content block in a message.\n\n```go\ntype ConversationState struct {\n\tTranscript []Message                     `json:\"transcript\"`\n\tNative     map[string]NativeConversation `json:\"native,omitempty\"`\n\tHandoff    *HandoffState                 `json:\"handoff,omitempty\"`\n}\n```\nConversationState retains the complete portable transcript separately from the model's compacted working history. Native cursors count transcript entries.\n\n```go\ntype GitInfo struct {\n\tBranch        string\n\tRemoteURL     string\n\tRecentCommits string\n\tChangedFiles  []string\n}\n```\nGitInfo holds basic git context from the current directory.\n\n```go\nfunc DetectGitInfo() *GitInfo\n```\nDetectGitInfo reads basic git info from the current directory.\n\n```go\ntype HTTPStatusError struct {\n\tStatusCode int\n\tMessage    string\n}\n```\nHTTPStatusError preserves the response status so callers can recover from expired QualityMax authentication without inspecting an error string.\n\n```go\nfunc (e *HTTPStatusError) Error() string\n```\n\n```go\ntype HandoffState struct {\n\tRejectedApproaches []RejectedApproach `json:\"rejected_approaches\"`\n}\n```\nHandoffState holds explicit user decisions independently of compacted history. A non-nil, empty checkpoint supersedes notes that the user has removed.\n\n```go\ntype ImageSource struct {\n\tType      string `json:\"type\"`       // \"base64\"\n\tMediaType string `json:\"media_type\"` // \"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"\n\tData      string `json:\"data\"`       // base64-encoded image data\n}\n```\nImageSource is the source data for an image content block.\n\n```go\ntype Message struct {\n\tRole    string      `json:\"role\"`\n\tContent interface{} `json:\"content\"` // string or []ContentBlock\n}\n```\nMessage represents a conversation message.\n\n```go\ntype NativeConversation struct {\n\tID          string `json:\"id\"`\n\tModel       string `json:\"model,omitempty\"`\n\tRolloutPath string `json:\"rollout_path,omitempty\"`\n\tDirectory   string `json:\"directory\"`\n\tCursor      int    `json:\"cursor\"`\n\t// Handoff is a digest of the checkpoint this native session last received,\n\t// so an unchanged checkpoint is not repeated into its history every turn.\n\tHandoff string `json:\"handoff,omitempty\"`\n}\n```\nNativeConversation identifies a CLI conversation on the machine/workspace that created it. It contains no credentials or provider configuration.\n\n```go\ntype PlanWindow struct {\n\tWindowLen  time.Duration // rolling window length (defaults to 5h)\n\tStartedAt  time.Time     // zero until the first turn opens a window\n\tTurns      int           // turns recorded in the current window\n\tInputToks  int           // input tokens recorded in the current window\n\tOutputToks int           // output tokens recorded in the current window\n\n\t// Exhausted marks that the provider refused a turn because the plan limit\n\t// was reached. ExhaustedReset is the provider-reported reset time when the\n\t// error carried one, otherwise the zero value.\n\tExhausted      bool\n\tExhaustedReset time.Time\n}\n```\nPlanWindow 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.\n\nIt 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.\n\nPlanWindow 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.\n\n```go\nfunc NewPlanWindow(windowLen time.Duration) *PlanWindow\n```\nNewPlanWindow returns a tracker with the given window length. A non-positive length falls back to the 5-hour default.\n\n```go\nfunc PlanWindowFromConfig(cfg *Config) *PlanWindow\n```\nPlanWindowFromConfig builds a tracker honoring the plan\\_window\\_hours config value (0 or unset → the 5-hour default).\n\n```go\nfunc (w *PlanWindow) Active(now time.Time) bool\n```\nActive reports whether a window is currently open (started, and either not elapsed or flagged exhausted with time still on the provider's clock).\n\n```go\nfunc (w *PlanWindow) Elapsed(now time.Time) time.Duration\n```\nElapsed is how long the current window has been open (0 if none), clamped to WindowLen.\n\n```go\nfunc (w *PlanWindow) MarkExhausted(now time.Time, reset time.Time)\n```\nMarkExhausted 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).\n\n```go\nfunc (w *PlanWindow) Record(now time.Time, inputToks, outputToks int)\n```\nRecord 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.\n\nRollover 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.\n\n```go\nfunc (w *PlanWindow) Remaining(now time.Time) time.Duration\n```\nRemaining is how long until the current window resets (0 if none or elapsed). A provider-reported reset time wins over the local estimate.\n\n```go\nfunc (w *PlanWindow) ResetAt() time.Time\n```\nResetAt is the wall-clock time the current window resets (zero if none).\n\n```go\nfunc (w *PlanWindow) Started() bool\n```\nStarted reports whether any window has been opened yet.\n\n```go\nfunc (w *PlanWindow) TotalTokens() int\n```\nTotalTokens returns the tokens recorded in the current window.\n\n```go\ntype Provider struct {\n\tID          string // opencode provider id, e.g. \"zai-coding-plan\", \"groq\"\n\tDisplayName string // human label shown in /providers and the picker\n\tSignupURL   string // where a user gets an API key\n\n\tCustom  bool            // true → write an openai-compatible provider block\n\tBaseURL string          // custom only: OpenAI-compatible endpoint\n\tModels  []ProviderModel // custom only: seed models exposed to opencode\n\n\t// KeyEnvVars are the environment variable names to set to the API key when\n\t// launching the opencode subprocess. For custom providers this is our own\n\t// substitution var referenced as \"{env:...}\" in the provider block. For\n\t// known providers these are opencode's standard vars (e.g. GROQ_API_KEY),\n\t// which opencode reads directly.\n\tKeyEnvVars []string\n\n\tKeyPrefix string // optional soft-validation hint (e.g. \"gsk_\" for Groq)\n}\n```\nProvider 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.\n\nTwo kinds of provider:\n\n  - 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.\n  - 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.\n\n```go\nfunc BuiltinProviders() []Provider\n```\nBuiltinProviders returns the catalogue of opt-in opencode providers.\n\n```go\nfunc ProviderByID(id string) (Provider, bool)\n```\nProviderByID looks up a builtin provider definition.\n\n```go\ntype ProviderModel struct {\n\tID   string // model id opencode uses after the \"provider/\" prefix\n\tName string // display name in the opencode config models map\n}\n```\nProviderModel is one model exposed by a custom provider block.\n\n```go\ntype QMaxConfig struct {\n\tCloudURL string `json:\"api_url\"`\n\tToken    string `json:\"token\"`\n\tEmail    string `json:\"email\"`\n\tAgentID  string `json:\"agent_id\"`\n\tAPIKey   string `json:\"api_key\"`\n}\n```\nQMaxConfig mirrors the qmax CLI config (~/.qamax/config.json).\n\n```go\nfunc LoadQMaxConfig() QMaxConfig\n```\nLoadQMaxConfig 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.\n\n```go\ntype RejectedApproach struct {\n\tApproach string `json:\"approach\"`\n\tEvidence string `json:\"evidence\"`\n}\n```\nRejectedApproach records what was ruled out and the evidence supplied by the user.\n\n```go\ntype SessionContext struct {\n\tProjectID   int\n\tLocalOnly   bool // true = no QualityMax auth/cloud tools for this process\n\tQMaxCfg     QMaxConfig\n\tQMaxBin     string      // resolved path to legacy qmax binary; empty for direct API/local-only paths\n\tQMaxInfo    string      // output of `qmax status` at startup\n\tGitInfo     *GitInfo    // git context from cwd\n\tProjectFile string      // name of .qmax.yml file if detected\n\tAPI         *APIClient  // direct QualityMax API client (no legacy qmax CLI needed)\n\tAuth        *AuthConfig // authentication credentials\n\tBackend     string      // \"\" | \"cc\" | \"codex\" | \"agy\" | \"opencode\" — active CLI inference backend\n\n\t// LiveFeed enables QM Cloud Sandbox execution for run_test / start_crawl\n\t// and turns on auto-launch of /browserfeed when a poll response surfaces\n\t// a live URL. Mirrors Config.LiveFeed; refreshed on every /set live_feed\n\t// or /live toggle so the dispatcher always sees the current value.\n\tLiveFeed bool\n\n\t// LastLiveURL holds the most recent `live_browser_url` extracted from a\n\t// run/crawl status poll. The REPL drains this between agent turns to\n\t// auto-launch the feed; tool handlers write to it via captureLiveURL.\n\tLastLiveURL string\n\n\t// turn-scoped diagnostic flags reset by the REPL before each agent\n\t// invocation. Make captureLiveURL chatty *once* per turn rather than\n\t// per poll, so users see \"live URL captured\" or a fallback warning\n\t// without having every poll spam the screen.\n\tLiveURLLogged       bool\n\tSandboxModeLogged   bool\n\tSandboxFallbackSeen bool\n}\n```\nSessionContext holds the runtime context for the agent session.\n\n```go\ntype ThinkingConfig struct {\n\tType string `json:\"type\"`\n}\n```\nThinkingConfig controls Anthropic thinking without sending sampling parameters.\n\n```go\nfunc DefaultThinking(model string) *ThinkingConfig\n```\nDefaultThinking reserves Haiku 5.5's response budget for visible text and tools. qmax-code does not retain the signed thinking blocks needed for replay.\n\n```go\ntype TokenUsage struct {\n\tInputTokens              int\n\tOutputTokens             int\n\tRequests                 int\n\tCacheReadInputTokens     int      `json:\",omitempty\"`\n\tCacheCreationInputTokens int      `json:\",omitempty\"`\n\tCostUSD                  *float64 `json:\",omitempty\"`\n}\n```\nTokenUsage tracks cumulative token usage across the session.\n\n```go\nfunc (u *TokenUsage) EstimatedCost(model string) float64\n```\nEstimatedCost 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.\n\n```go\nfunc (u *TokenUsage) RecordRequest(model string, usage APIUsage)\n```\nRecordRequest 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.\n\n```go\nfunc (u *TokenUsage) TotalInputTokens() int\n```\nTotalInputTokens includes both uncached and cached prompt tokens.\n\n```go\nfunc (u *TokenUsage) TotalTokens() int\n```\nTotalTokens returns the total token count.\n\n```go\ntype ToolDef struct {\n\tName        string                 `json:\"name\"`\n\tDescription string                 `json:\"description\"`\n\tInputSchema map[string]interface{} `json:\"input_schema\"`\n}\n```\nToolDef is a Claude API tool definition.\n\n","path":"github.com/Quality-Max/qmax-code/internal/api","name":"api","synopsis":"","isRedistributable":true}
