package connect import ( "bytes" "context" "crypto/tls" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/netip" "slices" "strings" "time" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/wire" ) // API-key providers (connectors spec §2.2): the runner, outside every // namespace, reads the provider's model list with the key and proves the // selected model with a one-token completion. Nothing here logs or // returns the key, a header, or the provider's text. // ErrKeyRefused: the provider refused the key (401 or 403). For TensorX // that is also an empty balance (§4.1). var ErrKeyRefused = errors.New("the provider refused the key") // ErrModelNotFound: the provider does not have the model (HTTP 404, or // a 4xx naming model_not_found). Nothing was billed; the model, not the // key, is at fault (connectors spec §16.4). var ErrModelNotFound = errors.New("the provider does not have the model") // ErrProviderAnswer: the provider's answer was not one this reads. var ErrProviderAnswer = errors.New("the provider's answer could not be read") // errProviderUnreachable: the request did not reach an answer. var errProviderUnreachable = errors.New("the provider could not be reached") // maxAnswer bounds a provider answer read here. const maxAnswer = 1 << 20 // APIClient talks to one API-key provider's OpenAI-compatible API. // Origin is the provider's origin (wire.APIKeyProvider.Upstream; a test // points it at a fake server on 127.0.0.1). type APIClient struct { HTTP *http.Client Origin string Path string // ModelsPath is where the model list is under Origin when it is not // Path+"/models" (wire.APIKeyProvider.ModelsPath: OpenCode Go's). ModelsPath string } func (c APIClient) client() *http.Client { if c.HTTP != nil { return c.HTTP } return SafeClient(nil, nil, nil) } // errUnsafeAddress: the provider's host resolved to an address the // runner does not dial (not public), or to none. var errUnsafeAddress = errors.New("the provider's host did not resolve to public addresses only") // SafeClient is the client an API key's requests use (security round, // finding 5): no ambient proxy; the host resolved once, every answer // required to be public (allow; egress.PublicAddress by default) and the // connection made to an address resolved, never resolved again; TLS // verified for the provider's host name; no redirect followed; a minute // at most. lookup, allow and dial are the tests' seams (nil: the // system's). func SafeClient(lookup func(ctx context.Context, host string) ([]netip.Addr, error), allow func(netip.Addr) bool, dial func(ctx context.Context, network, addr string) (net.Conn, error)) *http.Client { if lookup == nil { lookup = func(ctx context.Context, host string) ([]netip.Addr, error) { return net.DefaultResolver.LookupNetIP(ctx, "ip", host) } } if allow == nil { allow = egress.PublicAddress } if dial == nil { dial = (&net.Dialer{Timeout: 15 * time.Second}).DialContext } pinned := func(ctx context.Context, network, addr string) (net.Conn, error) { host, port, err := net.SplitHostPort(addr) if err != nil { return nil, err } var addrs []netip.Addr if a, err := netip.ParseAddr(host); err == nil { addrs = []netip.Addr{a} } else if addrs, err = lookup(ctx, host); err != nil { return nil, errProviderUnreachable } if len(addrs) == 0 || slices.ContainsFunc(addrs, func(a netip.Addr) bool { return !allow(a.Unmap()) }) { return nil, errUnsafeAddress } var last error for _, a := range addrs { conn, err := dial(ctx, network, net.JoinHostPort(a.Unmap().String(), port)) if err == nil { return conn, nil } last = err } return nil, last } return &http.Client{ Timeout: time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{ Proxy: nil, DialContext: pinned, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 45 * time.Second, MaxResponseHeaderBytes: 64 << 10, MaxIdleConns: 2, IdleConnTimeout: 30 * time.Second, DisableCompression: true, }, } } func (c APIClient) do(ctx context.Context, method, path string, key []byte, body any) ([]byte, error) { var in io.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { return nil, err } in = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, strings.TrimSuffix(c.Origin, "/")+path, in) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+string(key)) req.Header.Set("Accept", "application/json") if body != nil { req.Header.Set("Content-Type", "application/json") } resp, err := c.client().Do(req) if err != nil { // Never the request (its headers hold the key): the category only. if ctx.Err() != nil { return nil, ctx.Err() } return nil, errProviderUnreachable } defer resp.Body.Close() raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer+1)) if err != nil { return nil, err } switch { case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden: return nil, ErrKeyRefused case method == http.MethodPost && (resp.StatusCode == http.StatusNotFound || resp.StatusCode/100 == 4 && bytes.Contains(raw, []byte("model_not_found"))): return nil, ErrModelNotFound case resp.StatusCode/100 != 2 || len(raw) > maxAnswer: return nil, fmt.Errorf("%w: status %d", ErrProviderAnswer, resp.StatusCode) } return raw, nil } // Models lists the models the key may use, sorted, once each. func (c APIClient) Models(ctx context.Context, key []byte) ([]string, error) { path := c.Path + "/models" if c.ModelsPath != "" { path = c.ModelsPath } raw, err := c.do(ctx, http.MethodGet, path, key, nil) if err != nil { return nil, err } var list struct { Data []struct { ID string `json:"id"` } `json:"data"` } if err := json.Unmarshal(raw, &list); err != nil { return nil, ErrProviderAnswer } var out []string for _, m := range list.Data { if m.ID != "" && len(m.ID) <= wire.MaxModelName { out = append(out, m.ID) } } slices.Sort(out) return slices.Compact(out), nil } // ProbeUsage is a one-token completion's usage as the provider reported // it, normalised: input is the uncached part (an OpenAI-compatible // prompt_tokens counts cached tokens inside it); reasoning is part of // output. Reported is false when the answer carried no usage. Model is // the model the provider says answered: the usage is that model's. type ProbeUsage struct { Input, Cached, Output int64 Reasoning *int64 Reported bool Model string } // ErrModelMismatch: another model answered than the one selected, so the // probe proves nothing about the selected model. var ErrModelMismatch = errors.New("another model answered the probe") // probePrompt is the probe's whole request: one word back, one token. const probePrompt = "Reply with the word ok." // Probe proves model with a one-token completion (max_tokens 1). It is // billable: the caller charges its usage like any other attempt's. func (c APIClient) Probe(ctx context.Context, key []byte, model string) (ProbeUsage, error) { body := map[string]any{"model": model, "max_tokens": 1, "stream": false, "messages": []map[string]string{{"role": "user", "content": probePrompt}}} raw, err := c.do(ctx, http.MethodPost, c.Path+"/chat/completions", key, body) if err != nil { return ProbeUsage{}, err } var answer struct { Model string `json:"model"` Usage *struct { Prompt *int64 `json:"prompt_tokens"` Completion *int64 `json:"completion_tokens"` Prompt2 *struct { Cached *int64 `json:"cached_tokens"` } `json:"prompt_tokens_details"` Completion2 *struct { Reasoning *int64 `json:"reasoning_tokens"` } `json:"completion_tokens_details"` } `json:"usage"` } if err := json.Unmarshal(raw, &answer); err != nil { return ProbeUsage{}, ErrProviderAnswer } if len(answer.Model) > wire.MaxModelName { answer.Model = "" } mismatch := error(nil) if answer.Model != model { mismatch = ErrModelMismatch } u := answer.Usage if u == nil || u.Prompt == nil || u.Completion == nil { return ProbeUsage{Model: answer.Model}, mismatch } out := ProbeUsage{Input: *u.Prompt, Output: *u.Completion, Reported: true, Model: answer.Model} if u.Prompt2 != nil && u.Prompt2.Cached != nil { out.Cached = *u.Prompt2.Cached out.Input -= out.Cached } if u.Completion2 != nil { out.Reasoning = u.Completion2.Reasoning } if out.Input < 0 || out.Cached < 0 || out.Output < 0 { return ProbeUsage{Model: answer.Model}, mismatch } return out, mismatch } // Row is the probe's usage row on connection local, under the model that // answered (priced as that model): complete only when the provider // reported the usage and named the model. func (u ProbeUsage) Row(provider, local, model string, attempt int64, ok bool) wire.Usage { if u.Model != "" { model = u.Model } row := wire.Usage{Provider: provider, Connection: local, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: u.Reported && u.Model != ""} if !ok { row.Outcome = wire.OutcomeFailed } if u.Reported { in, cached, out, none := u.Input, u.Cached, u.Output, int64(0) row.InputTokens, row.CachedInputTokens, row.CacheWriteTokens, row.OutputTokens, row.ReasoningOutputTokens = &in, &cached, &none, &out, u.Reasoning } return row }