mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-10 17:57:54 -10:00
* fix(providers): register Atomic Chat as local OpenAI-compatible runtime Point atomic-chat at the default local API (http://127.0.0.1:1337/v1), mark it Local with no API key, and auto-detect it alongside Ollama and LM Studio. Keep opencode-go-anthropic-compatible in the provider catalog and curated model list after rebasing onto latest main. Co-authored-by: Cursor <[email protected]> * docs(zh): sync Atomic Chat local runtime into README_ZH The English README lists Atomic Chat in the provider list and tells local-model users to run its desktop app on http://127.0.0.1:1337/v1, but the Chinese README still mentioned only Ollama and LM Studio. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(providers): give the local Atomic Chat runtime its own catalog ID Repurposing the existing atomic-chat ID from the hosted, key-gated preset to a keyless local one silently downgraded credential checks for profiles already saved against the remote endpoint: MissingCredentialEnv resolves RequiresAuth from the catalog descriptor, so those profiles were reported as ready and only failed later with an unauthenticated call to api.atomic.chat. Keep the hosted atomic-chat descriptor as it was and register the local runtime under a separate atomic-chat-local ID, mirroring the existing ollama-cloud/ollama split. Stored profiles keep their identity and no migration is needed. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(onboarding): assert the full Atomic Chat local endpoint and default model Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(models): drop the placeholder curated list for atomic-chat-local Atomic Chat's model catalog is a Hugging Face scrape refreshed every 12h plus arbitrary owner/repo lookups, so the served model ID is whichever model the user loaded and no hardcoded list stays accurate. The single local-model entry short-circuited Models() without adding anything: the descriptor is openai-compatible, so modelMatchesProvider never matches a registry entry and the fallback already yields the descriptor's DefaultModel. Output is unchanged; the difference is that local-model is no longer presented as a curated contract. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(onboarding): pin the probed model in the local-runtime adopt command probeLocalRuntime already reads the runtime's /v1/models, but SetupAction dropped the result and emitted 'zero providers add <id> --set-active' with no --model. The add path then persisted the catalog DefaultModel, which for a local runtime is the placeholder 'local-model', and the first completion failed with an unknown-model response. SetupAction now pins the probed id via SetupCommandWithModel. The catalog default wins when the server actually serves it, so an existing Ollama setup does not switch models; otherwise the first advertised id is used. An empty probe result leaves the command on the catalog default rather than inventing an id. Covers a server whose returned id is not 'local-model'. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(onboarding): shell-safe adopt command + reject atomic-chat-local placeholder model commandArg now POSIX single-quotes rendered args instead of strconv.Quote, so a model id from an untrusted /v1/models response cannot expand when the adopt command is pasted into a shell. providerProfileForAdd now errors when atomic-chat-local is added without --model instead of persisting the local-model placeholder that fails the first completion. Adds regression tests for command substitution, backticks, and the require-model guard. * fix(onboarding): finish Atomic Chat setup across supported shells Rebase on current main and keep the hosted Atomic Chat preset intact. Only emit setup arguments that are portable across POSIX, cmd.exe and PowerShell; show interactive guidance for other model IDs. Reject the Atomic Chat placeholder before both CLI and TUI persistence, and stop advertising adoption when discovery finds no usable model. Validation: full Go test suite, focused race suite, vet, release build, smoke, formatting, advisory lint and vulncheck pass with isolated config and inherited Anthropic overrides removed. Onboarding, CLI and TUI test packages cross-compile for Windows and Linux. Regression tests fail on the rebased pre-fix code and pass with these changes. Refs Gitlawb/zero#550 and Gitlawb/zero#592. * fix(onboarding): preserve option-looking model IDs in adopt commands Use the existing --model=value grammar when a discovered model begins with a hyphen. Validate the model separately from the fixed separator so shell safety remains unchanged and '=' is not added to the allowlist. Exercise generated detection actions through shell tokenization, the actual add parser, and profile construction for Atomic Chat, LM Studio and Ollama. Cover leading hyphens, flag-looking IDs, ordinary IDs, spaces, and unsafe inline values. Before the fix, the new regression failed with: generated adoption command rejected by add parser: --model requires a value Validation: full Go suite, focused race tests, formatting, vet, release build, smoke, lint-static and vulncheck passed. Affected test packages cross-compiled for Windows and Linux. Refs Gitlawb/zero#550. * fix(onboarding): select eligible chat models and preserve Ollama defaults P2: apply the existing known-noncoding exclusion before default preference or first-model fallback. When a nonempty list has no eligible model, offer commandless guidance instead of persisting the rejected/default model. P3: recognize an Ollama untagged default's :latest spelling, preserving the advertised ID. Prefer exact matches and leave other tags/providers alone. Add selector tests plus a mock-server integration test through discovery, the generated action, the real add parser, profile persistence, a fresh process, and the chat completion request. Before this fix, that test failed: fresh process sent model "text-embedding-local", want eligible model "-loaded chat model" The Ollama alias case also failed before the fix: AdoptModel() = "qwen3:8b", want "llama3.1:latest" Explicit model choices, shell checks, hosted/local provider identities and Atomic placeholder guards retain their existing behavior. Validation: full Go suite, focused race tests, formatting, vet, release build, smoke, lint-static and vulncheck passed. Affected test packages cross-compiled for Windows and Linux. Integration evidence uses a mock server; native Windows shell and actual runtime behavior are not claimed. Refs Gitlawb/zero#550 and Gitlawb/zero#592. --------- Co-authored-by: Cursor <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: alex <[email protected]>
234 lines
7.6 KiB
Go
234 lines
7.6 KiB
Go
package provideronboarding
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Gitlawb/zero/internal/providercatalog"
|
|
"github.com/Gitlawb/zero/internal/providermodelcatalog"
|
|
)
|
|
|
|
// LocalRuntime describes a local, OpenAI-compatible model server that ZERO can
|
|
// adopt with no API key. These are the runtimes the launch audience is most
|
|
// likely to already be running (Ollama, LM Studio), so the first-run wizard
|
|
// auto-detects them on their default ports and offers them with no key step.
|
|
type LocalRuntime struct {
|
|
CatalogID string
|
|
Name string
|
|
BaseURL string
|
|
DefaultModel string
|
|
RequiresKey bool
|
|
}
|
|
|
|
// DetectedLocalRuntime is a LocalRuntime that has been probed. Reachable reports
|
|
// whether its default endpoint answered the probe; Models is the list of model
|
|
// ids the runtime advertised (best-effort, empty when the probe could not parse
|
|
// a model list).
|
|
type DetectedLocalRuntime struct {
|
|
LocalRuntime
|
|
Reachable bool
|
|
Models []string
|
|
}
|
|
|
|
// LocalDetectOptions configures DetectLocalRuntimes. All fields are optional;
|
|
// the zero value probes the built-in candidates with a short default timeout
|
|
// using http.DefaultClient. Tests inject HTTPClient and Candidates.
|
|
type LocalDetectOptions struct {
|
|
HTTPClient *http.Client
|
|
Timeout time.Duration
|
|
Candidates []LocalRuntime
|
|
}
|
|
|
|
const defaultLocalProbeTimeout = 400 * time.Millisecond
|
|
|
|
// LocalRuntimeCandidates returns the built-in local-runtime candidates derived
|
|
// from the provider catalog. Only catalog entries flagged Local are returned, so
|
|
// the default ports stay the single source of truth (catalog.go).
|
|
func LocalRuntimeCandidates() []LocalRuntime {
|
|
candidates := make([]LocalRuntime, 0, 2)
|
|
for _, descriptor := range providercatalog.All() {
|
|
if !descriptor.Local {
|
|
continue
|
|
}
|
|
candidates = append(candidates, LocalRuntime{
|
|
CatalogID: descriptor.ID,
|
|
Name: descriptor.Name,
|
|
BaseURL: descriptor.DefaultBaseURL,
|
|
DefaultModel: descriptor.DefaultModel,
|
|
RequiresKey: descriptor.RequiresAuth,
|
|
})
|
|
}
|
|
return candidates
|
|
}
|
|
|
|
// DetectLocalRuntimes probes each candidate's default endpoint and returns only
|
|
// the runtimes that answered successfully. A runtime is "reachable" when its
|
|
// OpenAI-compatible models endpoint returns a 2xx; transport errors (closed
|
|
// port), timeouts, and non-2xx responses are treated as "not running" and the
|
|
// candidate is dropped. Detection never errors — a machine with nothing running
|
|
// locally simply yields an empty slice.
|
|
func DetectLocalRuntimes(ctx context.Context, options LocalDetectOptions) []DetectedLocalRuntime {
|
|
candidates := options.Candidates
|
|
if len(candidates) == 0 {
|
|
candidates = LocalRuntimeCandidates()
|
|
}
|
|
timeout := options.Timeout
|
|
if timeout <= 0 {
|
|
timeout = defaultLocalProbeTimeout
|
|
}
|
|
client := options.HTTPClient
|
|
if client == nil {
|
|
client = &http.Client{Timeout: timeout}
|
|
}
|
|
|
|
detected := make([]DetectedLocalRuntime, 0, len(candidates))
|
|
for _, candidate := range candidates {
|
|
models, reachable := probeLocalRuntime(ctx, client, timeout, candidate)
|
|
if !reachable {
|
|
continue
|
|
}
|
|
detected = append(detected, DetectedLocalRuntime{
|
|
LocalRuntime: candidate,
|
|
Reachable: true,
|
|
Models: models,
|
|
})
|
|
}
|
|
return detected
|
|
}
|
|
|
|
// SetupAction returns the no-key onboarding action for a detected local runtime.
|
|
func (runtime DetectedLocalRuntime) SetupAction() Action {
|
|
descriptor := providercatalog.Descriptor{ID: runtime.CatalogID, RequiresAuth: false}
|
|
model := runtime.AdoptModel()
|
|
name := strings.TrimSpace(runtime.Name)
|
|
if name == "" {
|
|
name = runtime.CatalogID
|
|
}
|
|
// Do not fall back to an unserved/default model when all advertised IDs
|
|
// were rejected. Preserve other runtimes' existing empty-response behavior.
|
|
if model == "" && (runtime.CatalogID == "atomic-chat-local" || len(runtime.Models) > 0) {
|
|
return Action{
|
|
Label: "Load a chat model",
|
|
Detail: "Detected " + name + " on " + runtime.BaseURL + " but no usable chat model ID was discovered. Load a chat model in " + name + ", then run zero providers detect again.",
|
|
}
|
|
}
|
|
command := SetupCommandWithModel(descriptor, runtime.Name, model, true)
|
|
if command == "" {
|
|
return Action{
|
|
Label: "Use interactive setup",
|
|
Detail: "A setup value cannot be safely included in a command for all supported shells. Run zero setup and select or enter the model there.",
|
|
}
|
|
}
|
|
detail := "Detected " + name + " on " + runtime.BaseURL + " — no API key required."
|
|
if model != "" {
|
|
detail = "Detected " + name + " on " + runtime.BaseURL + " serving " + model + " — no API key required."
|
|
}
|
|
return Action{
|
|
Label: "Use local runtime",
|
|
Command: command,
|
|
Detail: detail,
|
|
}
|
|
}
|
|
|
|
// AdoptModel returns an advertised model eligible for automatic chat adoption,
|
|
// preferring the catalog default when served. Shell syntax is handled when
|
|
// rendering the command, so eligible IDs are not silently replaced for quoting.
|
|
func (runtime DetectedLocalRuntime) AdoptModel() string {
|
|
want := strings.TrimSpace(runtime.DefaultModel)
|
|
first := ""
|
|
defaultAlias := ""
|
|
for _, raw := range runtime.Models {
|
|
id := strings.TrimSpace(raw)
|
|
if id == "" || providermodelcatalog.IsKnownNonCodingModelID(id) || runtime.CatalogID == "atomic-chat-local" && id == "local-model" {
|
|
continue
|
|
}
|
|
if id == want {
|
|
return id
|
|
}
|
|
// Ollama's untagged default is equivalent to its :latest spelling.
|
|
// Retain the advertised ID and prefer an exact match if one follows.
|
|
if runtime.CatalogID == "ollama" && want != "" && !strings.Contains(want, ":") && id == want+":latest" {
|
|
defaultAlias = id
|
|
}
|
|
if first == "" {
|
|
first = id
|
|
}
|
|
}
|
|
if defaultAlias != "" {
|
|
return defaultAlias
|
|
}
|
|
return first
|
|
}
|
|
|
|
func probeLocalRuntime(ctx context.Context, client *http.Client, timeout time.Duration, candidate LocalRuntime) ([]string, bool) {
|
|
endpoint := localModelsEndpoint(candidate.BaseURL)
|
|
if endpoint == "" {
|
|
return nil, false
|
|
}
|
|
probeCtx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
request, err := http.NewRequestWithContext(probeCtx, http.MethodGet, endpoint, nil)
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
response, err := client.Do(request)
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
defer func() {
|
|
_ = response.Body.Close()
|
|
}()
|
|
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
|
return nil, false
|
|
}
|
|
return decodeLocalModelIDs(response.Body), true
|
|
}
|
|
|
|
// decodeLocalModelIDs best-effort parses the OpenAI-compatible models list
|
|
// ({"data":[{"id":"..."}]}). The body is bounded so a misbehaving local server
|
|
// cannot stream unbounded data into the wizard. A parse failure is not fatal:
|
|
// the runtime is still reachable, we just return no model ids.
|
|
func decodeLocalModelIDs(body io.Reader) []string {
|
|
data, err := io.ReadAll(io.LimitReader(body, 256*1024))
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var parsed struct {
|
|
Data []struct {
|
|
ID string `json:"id"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
|
return nil
|
|
}
|
|
ids := make([]string, 0, len(parsed.Data))
|
|
seen := map[string]bool{}
|
|
for _, entry := range parsed.Data {
|
|
id := strings.TrimSpace(entry.ID)
|
|
if id == "" || seen[id] {
|
|
continue
|
|
}
|
|
seen[id] = true
|
|
ids = append(ids, id)
|
|
}
|
|
if len(ids) == 0 {
|
|
return nil
|
|
}
|
|
return ids
|
|
}
|
|
|
|
// localModelsEndpoint resolves the OpenAI-compatible "list models" path for a
|
|
// base URL. Local base URLs in the catalog already end in /v1, so the endpoint
|
|
// is baseURL + "/models"; a trailing slash is trimmed so we never emit "//".
|
|
func localModelsEndpoint(baseURL string) string {
|
|
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
|
if trimmed == "" {
|
|
return ""
|
|
}
|
|
return trimmed + "/models"
|
|
}
|