oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package connect
2
3import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "net"
12 "net/http"
13 "net/netip"
14 "slices"
15 "strings"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/runner/egress"
19 "amadan.net/oficina/equipo/internal/wire"
20)
21
22// API-key providers (connectors spec §2.2): the runner, outside every
23// namespace, reads the provider's model list with the key and proves the
24// selected model with a one-token completion. Nothing here logs or
25// returns the key, a header, or the provider's text.
26
27// ErrKeyRefused: the provider refused the key (401 or 403). For TensorX
28// that is also an empty balance (§4.1).
29var ErrKeyRefused = errors.New("the provider refused the key")
30
31// ErrModelNotFound: the provider does not have the model (HTTP 404, or
32// a 4xx naming model_not_found). Nothing was billed; the model, not the
33// key, is at fault (connectors spec §16.4).
34var ErrModelNotFound = errors.New("the provider does not have the model")
35
36// ErrProviderAnswer: the provider's answer was not one this reads.
37var ErrProviderAnswer = errors.New("the provider's answer could not be read")
38
39// errProviderUnreachable: the request did not reach an answer.
40var errProviderUnreachable = errors.New("the provider could not be reached")
41
42// maxAnswer bounds a provider answer read here.
43const maxAnswer = 1 << 20
44
45// APIClient talks to one API-key provider's OpenAI-compatible API.
46// Origin is the provider's origin (wire.APIKeyProvider.Upstream; a test
47// points it at a fake server on 127.0.0.1).
48type APIClient struct {
49 HTTP *http.Client
50 Origin string
51 Path string
52 // ModelsPath is where the model list is under Origin when it is not
53 // Path+"/models" (wire.APIKeyProvider.ModelsPath: OpenCode Go's).
54 ModelsPath string
55}
56
57func (c APIClient) client() *http.Client {
58 if c.HTTP != nil {
59 return c.HTTP
60 }
61 return SafeClient(nil, nil, nil)
62}
63
64// errUnsafeAddress: the provider's host resolved to an address the
65// runner does not dial (not public), or to none.
66var errUnsafeAddress = errors.New("the provider's host did not resolve to public addresses only")
67
68// SafeClient is the client an API key's requests use (security round,
69// finding 5): no ambient proxy; the host resolved once, every answer
70// required to be public (allow; egress.PublicAddress by default) and the
71// connection made to an address resolved, never resolved again; TLS
72// verified for the provider's host name; no redirect followed; a minute
73// at most. lookup, allow and dial are the tests' seams (nil: the
74// system's).
75func 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 {
76 if lookup == nil {
77 lookup = func(ctx context.Context, host string) ([]netip.Addr, error) {
78 return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
79 }
80 }
81 if allow == nil {
82 allow = egress.PublicAddress
83 }
84 if dial == nil {
85 dial = (&net.Dialer{Timeout: 15 * time.Second}).DialContext
86 }
87 pinned := func(ctx context.Context, network, addr string) (net.Conn, error) {
88 host, port, err := net.SplitHostPort(addr)
89 if err != nil {
90 return nil, err
91 }
92 var addrs []netip.Addr
93 if a, err := netip.ParseAddr(host); err == nil {
94 addrs = []netip.Addr{a}
95 } else if addrs, err = lookup(ctx, host); err != nil {
96 return nil, errProviderUnreachable
97 }
98 if len(addrs) == 0 || slices.ContainsFunc(addrs, func(a netip.Addr) bool { return !allow(a.Unmap()) }) {
99 return nil, errUnsafeAddress
100 }
101 var last error
102 for _, a := range addrs {
103 conn, err := dial(ctx, network, net.JoinHostPort(a.Unmap().String(), port))
104 if err == nil {
105 return conn, nil
106 }
107 last = err
108 }
109 return nil, last
110 }
111 return &http.Client{
112 Timeout: time.Minute,
113 CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
114 Transport: &http.Transport{
115 Proxy: nil,
116 DialContext: pinned,
117 TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
118 TLSHandshakeTimeout: 15 * time.Second,
119 ResponseHeaderTimeout: 45 * time.Second,
120 MaxResponseHeaderBytes: 64 << 10,
121 MaxIdleConns: 2,
122 IdleConnTimeout: 30 * time.Second,
123 DisableCompression: true,
124 },
125 }
126}
127
128func (c APIClient) do(ctx context.Context, method, path string, key []byte, body any) ([]byte, error) {
129 var in io.Reader
130 if body != nil {
131 raw, err := json.Marshal(body)
132 if err != nil {
133 return nil, err
134 }
135 in = bytes.NewReader(raw)
136 }
137 req, err := http.NewRequestWithContext(ctx, method, strings.TrimSuffix(c.Origin, "/")+path, in)
138 if err != nil {
139 return nil, err
140 }
141 req.Header.Set("Authorization", "Bearer "+string(key))
142 req.Header.Set("Accept", "application/json")
143 if body != nil {
144 req.Header.Set("Content-Type", "application/json")
145 }
146 resp, err := c.client().Do(req)
147 if err != nil {
148 // Never the request (its headers hold the key): the category only.
149 if ctx.Err() != nil {
150 return nil, ctx.Err()
151 }
152 return nil, errProviderUnreachable
153 }
154 defer resp.Body.Close()
155 raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer+1))
156 if err != nil {
157 return nil, err
158 }
159 switch {
160 case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
161 return nil, ErrKeyRefused
162 case method == http.MethodPost && (resp.StatusCode == http.StatusNotFound || resp.StatusCode/100 == 4 && bytes.Contains(raw, []byte("model_not_found"))):
163 return nil, ErrModelNotFound
164 case resp.StatusCode/100 != 2 || len(raw) > maxAnswer:
165 return nil, fmt.Errorf("%w: status %d", ErrProviderAnswer, resp.StatusCode)
166 }
167 return raw, nil
168}
169
170// Models lists the models the key may use, sorted, once each.
171func (c APIClient) Models(ctx context.Context, key []byte) ([]string, error) {
172 path := c.Path + "/models"
173 if c.ModelsPath != "" {
174 path = c.ModelsPath
175 }
176 raw, err := c.do(ctx, http.MethodGet, path, key, nil)
177 if err != nil {
178 return nil, err
179 }
180 var list struct {
181 Data []struct {
182 ID string `json:"id"`
183 } `json:"data"`
184 }
185 if err := json.Unmarshal(raw, &list); err != nil {
186 return nil, ErrProviderAnswer
187 }
188 var out []string
189 for _, m := range list.Data {
190 if m.ID != "" && len(m.ID) <= wire.MaxModelName {
191 out = append(out, m.ID)
192 }
193 }
194 slices.Sort(out)
195 return slices.Compact(out), nil
196}
197
198// ProbeUsage is a one-token completion's usage as the provider reported
199// it, normalised: input is the uncached part (an OpenAI-compatible
200// prompt_tokens counts cached tokens inside it); reasoning is part of
201// output. Reported is false when the answer carried no usage. Model is
202// the model the provider says answered: the usage is that model's.
203type ProbeUsage struct {
204 Input, Cached, Output int64
205 Reasoning *int64
206 Reported bool
207 Model string
208}
209
210// ErrModelMismatch: another model answered than the one selected, so the
211// probe proves nothing about the selected model.
212var ErrModelMismatch = errors.New("another model answered the probe")
213
214// probePrompt is the probe's whole request: one word back, one token.
215const probePrompt = "Reply with the word ok."
216
217// Probe proves model with a one-token completion (max_tokens 1). It is
218// billable: the caller charges its usage like any other attempt's.
219func (c APIClient) Probe(ctx context.Context, key []byte, model string) (ProbeUsage, error) {
220 body := map[string]any{"model": model, "max_tokens": 1, "stream": false, "messages": []map[string]string{{"role": "user", "content": probePrompt}}}
221 raw, err := c.do(ctx, http.MethodPost, c.Path+"/chat/completions", key, body)
222 if err != nil {
223 return ProbeUsage{}, err
224 }
225 var answer struct {
226 Model string `json:"model"`
227 Usage *struct {
228 Prompt *int64 `json:"prompt_tokens"`
229 Completion *int64 `json:"completion_tokens"`
230 Prompt2 *struct {
231 Cached *int64 `json:"cached_tokens"`
232 } `json:"prompt_tokens_details"`
233 Completion2 *struct {
234 Reasoning *int64 `json:"reasoning_tokens"`
235 } `json:"completion_tokens_details"`
236 } `json:"usage"`
237 }
238 if err := json.Unmarshal(raw, &answer); err != nil {
239 return ProbeUsage{}, ErrProviderAnswer
240 }
241 if len(answer.Model) > wire.MaxModelName {
242 answer.Model = ""
243 }
244 mismatch := error(nil)
245 if answer.Model != model {
246 mismatch = ErrModelMismatch
247 }
248 u := answer.Usage
249 if u == nil || u.Prompt == nil || u.Completion == nil {
250 return ProbeUsage{Model: answer.Model}, mismatch
251 }
252 out := ProbeUsage{Input: *u.Prompt, Output: *u.Completion, Reported: true, Model: answer.Model}
253 if u.Prompt2 != nil && u.Prompt2.Cached != nil {
254 out.Cached = *u.Prompt2.Cached
255 out.Input -= out.Cached
256 }
257 if u.Completion2 != nil {
258 out.Reasoning = u.Completion2.Reasoning
259 }
260 if out.Input < 0 || out.Cached < 0 || out.Output < 0 {
261 return ProbeUsage{Model: answer.Model}, mismatch
262 }
263 return out, mismatch
264}
265
266// Row is the probe's usage row on connection local, under the model that
267// answered (priced as that model): complete only when the provider
268// reported the usage and named the model.
269func (u ProbeUsage) Row(provider, local, model string, attempt int64, ok bool) wire.Usage {
270 if u.Model != "" {
271 model = u.Model
272 }
273 row := wire.Usage{Provider: provider, Connection: local, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: u.Reported && u.Model != ""}
274 if !ok {
275 row.Outcome = wire.OutcomeFailed
276 }
277 if u.Reported {
278 in, cached, out, none := u.Input, u.Cached, u.Output, int64(0)
279 row.InputTokens, row.CachedInputTokens, row.CacheWriteTokens, row.OutputTokens, row.ReasoningOutputTokens = &in, &cached, &none, &out, u.Reasoning
280 }
281 return row
282}
283