oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package assist is the only code in Slides that talks to a model.
2//
3// There is one provider, TensorX (Paul, 2026-09-19: zero data
4// retention, treated as local inference), reached as an
5// OpenAI-compatible chat completion, and one call: "here is a deck and
6// a request, propose the operations". What the model answers is a
7// PROPOSAL and nothing more — the caller (internal/slides/assist.go)
8// validates every operation on a scratch copy of the deck before a
9// browser is told about any of them, and the browser applies them as
10// the person's own change. Nothing here writes anything.
11//
12// The shape is memoria's provider package (oficina/memoria,
13// internal/memoria/provider), adopted for the reasons it records: the
14// host is pinned (scheme, host AND port) on every request, proxies from
15// the environment are ignored, redirects are refused, keep-alives are
16// off, the response is read under a detectable cap, and a response the
17// provider marked as cut short is refused whole.
18//
19// **Nothing in this package logs, and no error it returns carries
20// content.** A provider's response body is the deck's words: an
21// OpenAI-compatible 4xx can echo the input that caused it, and a decode
22// error can quote the byte it choked on. Errors here are fixed strings
23// and status codes.
24package assist
25
26import (
27 "bytes"
28 "context"
29 "encoding/json"
30 "errors"
31 "fmt"
32 "io"
33 "net"
34 "net/http"
35 "strings"
36 "time"
37)
38
39const (
40 // BaseURL is TensorX's API root. A constant in production: a
41 // configurable base URL on an OpenAI-compatible client is a way to
42 // interpose a proxy that sees every deck. NewAt exists for the
43 // development override and tests only, and config.go refuses the
44 // override anywhere but development.
45 BaseURL = "https://api.tensorx.ai/v1"
46
47 // Name is how the provider is named to a reader.
48 Name = "TensorX"
49
50 // DefaultModel is offered when SLIDES_AI_MODELS names none: the
51 // suite's measured cheap tier (memoria's model.cheap), a dated id
52 // so the name names weights rather than a floating alias.
53 DefaultModel = "deepseek/deepseek-v4-flash-0731"
54
55 // Deadline bounds one call. A ten-slide deck is several thousand
56 // output tokens, which a flash-tier model writes in well under a
57 // minute; past this the person is told the assistant could not be
58 // reached rather than watching a spinner indefinitely.
59 Deadline = 90 * time.Second
60
61 // MaxTokens is the completion budget sent with every call. Enough
62 // for a twenty-slide deck with notes, and a bound on what one
63 // request can cost.
64 MaxTokens = 16384
65
66 // maxResponse caps what is read from the provider. MaxTokens of
67 // JSON is well under this; one byte past it is refused, never
68 // truncated.
69 maxResponse = 1 << 20
70)
71
72// Errors. Fixed strings: none of them ever carries a byte of a request
73// or a response.
74var (
75 ErrTooLarge = errors.New("assist: response exceeds the cap")
76 ErrMalformed = errors.New("assist: response is not the agreed shape")
77 // ErrTruncated is a response the provider itself marked cut short
78 // (finish_reason "length"). Refused whole: half a batch of
79 // operations is a deck nobody asked for.
80 ErrTruncated = errors.New("assist: response was truncated")
81 // ErrForbiddenHost is a request to anywhere but the pinned host, or
82 // any redirect at all.
83 ErrForbiddenHost = errors.New("assist: refused a host or redirect other than the pinned one")
84 // ErrTransport is every failure to send or read, flattened; the
85 // underlying error is dropped, not wrapped (a url.Error quotes a
86 // Location header the provider chose).
87 ErrTransport = errors.New("assist: transport failure")
88 // ErrMissingKey is a client built with no credential, refused at
89 // construction so a wiring bug fails at boot.
90 ErrMissingKey = errors.New("assist: no credential")
91)
92
93// StatusError is a non-2xx answer. The status and nothing else: the
94// body of a 4xx may echo the deck.
95type StatusError struct{ Code int }
96
97func (e *StatusError) Error() string {
98 return fmt.Sprintf("assist: provider answered status %d", e.Code)
99}
100
101// Message is one chat message.
102type Message struct {
103 Role string `json:"role"`
104 Content string `json:"content"`
105}
106
107// Client calls TensorX (or, in development, the base it was built for).
108type Client struct {
109 hc *http.Client
110 base string
111 key string
112}
113
114// New returns a client for TensorX. There is no exported way to change
115// where it dials other than NewAt, which is development's.
116func New(key string) (*Client, error) { return NewAt(key, BaseURL) }
117
118// NewAt is New pinned to another OpenAI-compatible base — a fake server
119// in tests, or a local one in development. The pin is the same: every
120// request to any other scheme, host or port is refused before it is
121// dialled.
122func NewAt(key, base string) (*Client, error) {
123 if key == "" {
124 return nil, ErrMissingKey
125 }
126 probe, err := http.NewRequest(http.MethodPost, base, nil)
127 if err != nil || probe.URL.Hostname() == "" || probe.URL.User != nil ||
128 (probe.URL.Scheme != "https" && probe.URL.Scheme != "http") {
129 return nil, ErrForbiddenHost
130 }
131 // Our own transport, built fresh rather than cloned from
132 // http.DefaultTransport (which a test may have replaced), with
133 // proxies off — memoria's review found HTTPS_PROXY receiving a
134 // CONNECT while the URL pin passed — and keep-alives off: net/http
135 // logs unsolicited bytes on an idle pooled connection, quoting
136 // them, past every sanitised path here.
137 tr := &http.Transport{
138 Proxy: nil,
139 DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
140 ForceAttemptHTTP2: true,
141 TLSHandshakeTimeout: 10 * time.Second,
142 ResponseHeaderTimeout: Deadline,
143 DisableKeepAlives: true,
144 }
145 return &Client{
146 base: strings.TrimRight(base, "/"),
147 key: key,
148 hc: &http.Client{
149 Transport: &pinnedTransport{
150 scheme: probe.URL.Scheme,
151 authority: authority(probe.URL.Scheme, probe.URL.Hostname(), probe.URL.Port()),
152 next: tr,
153 },
154 // No redirect is legitimate on this API, and following one
155 // hands the bearer key and the deck to wherever it points.
156 CheckRedirect: func(*http.Request, []*http.Request) error { return ErrForbiddenHost },
157 },
158 }, nil
159}
160
161// pinnedTransport refuses every scheme and authority but the one it was
162// built for, port included, before anything is dialled.
163type pinnedTransport struct {
164 scheme, authority string
165 next http.RoundTripper
166}
167
168func (p *pinnedTransport) RoundTrip(r *http.Request) (*http.Response, error) {
169 if r.URL.Scheme != p.scheme || r.URL.User != nil ||
170 authority(r.URL.Scheme, r.URL.Hostname(), r.URL.Port()) != p.authority {
171 return nil, ErrForbiddenHost
172 }
173 return p.next.RoundTrip(r)
174}
175
176// authority is host:port with the scheme's default port made explicit.
177func authority(scheme, host, port string) string {
178 if port == "" {
179 switch scheme {
180 case "https":
181 port = "443"
182 case "http":
183 port = "80"
184 }
185 }
186 return strings.ToLower(host) + ":" + port
187}
188
189type chatRequest struct {
190 Model string `json:"model"`
191 Messages []Message `json:"messages"`
192 ResponseFormat map[string]string `json:"response_format,omitempty"`
193 Temperature float64 `json:"temperature"`
194 MaxTokens int `json:"max_tokens"`
195}
196
197// Complete sends messages to model and returns the reply's content.
198//
199// It asks for a JSON object (response_format json_object). An
200// OpenAI-compatible model that does not support that answers 400, and
201// the call is made once more without it: the caller extracts the
202// object either way, and a 400 for any other reason is a 400 again.
203//
204// The deadline is the caller's context, bounded here by Deadline.
205func (c *Client) Complete(ctx context.Context, model string, messages []Message) (string, error) {
206 ctx, cancel := context.WithTimeout(ctx, Deadline)
207 defer cancel()
208 content, err := c.complete(ctx, model, messages, true)
209 var status *StatusError
210 if errors.As(err, &status) && status.Code == http.StatusBadRequest {
211 content, err = c.complete(ctx, model, messages, false)
212 }
213 return content, err
214}
215
216func (c *Client) complete(ctx context.Context, model string, messages []Message, jsonMode bool) (string, error) {
217 req := chatRequest{Model: model, Messages: messages, Temperature: 0.3, MaxTokens: MaxTokens}
218 if jsonMode {
219 req.ResponseFormat = map[string]string{"type": "json_object"}
220 }
221 body, err := json.Marshal(req)
222 if err != nil {
223 return "", ErrMalformed
224 }
225 hr, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/chat/completions", bytes.NewReader(body))
226 if err != nil {
227 return "", ErrForbiddenHost
228 }
229 hr.Header.Set("Authorization", "Bearer "+c.key)
230 hr.Header.Set("Content-Type", "application/json")
231
232 resp, err := c.hc.Do(hr)
233 if err != nil {
234 return "", transportFailure(ctx, err)
235 }
236 defer resp.Body.Close()
237 if resp.StatusCode < 200 || resp.StatusCode > 299 {
238 return "", &StatusError{Code: resp.StatusCode}
239 }
240 // A cap that is detectable: read one byte past it.
241 raw, err := io.ReadAll(io.LimitReader(resp.Body, maxResponse+1))
242 if err != nil {
243 return "", transportFailure(ctx, err)
244 }
245 if len(raw) > maxResponse {
246 return "", ErrTooLarge
247 }
248 var envelope struct {
249 Choices []struct {
250 Message struct {
251 Content string `json:"content"`
252 } `json:"message"`
253 FinishReason string `json:"finish_reason"`
254 } `json:"choices"`
255 }
256 if err := json.Unmarshal(raw, &envelope); err != nil || len(envelope.Choices) != 1 {
257 return "", ErrMalformed
258 }
259 choice := envelope.Choices[0]
260 switch choice.FinishReason {
261 case "stop":
262 case "length":
263 return "", ErrTruncated
264 default:
265 // A content filter, a tool call, a value never seen: not a
266 // complete answer.
267 return "", ErrMalformed
268 }
269 return choice.Message.Content, nil
270}
271
272// transportFailure turns any failure to send or read into a fixed
273// error. The caller's context decides first, so a deadline is still
274// recognisable; everything else is ErrTransport with the original
275// dropped.
276func transportFailure(ctx context.Context, err error) error {
277 if ctxErr := ctx.Err(); ctxErr != nil {
278 return ctxErr
279 }
280 if errors.Is(err, ErrForbiddenHost) {
281 return ErrForbiddenHost
282 }
283 return ErrTransport
284}
285