oficina / slides Public

Add the assistant's TensorX client

internal/slides/assist is the only code in Slides that talks to a
model: one OpenAI-compatible chat completion to TensorX, pinned to its
scheme, host and port, proxies and redirects refused, keep-alives off,
the response read under a detectable cap, a truncated answer refused
whole, and no error that carries a byte of the deck (memoria's provider
posture). It asks for a JSON object and asks again without
response_format if a model answers 400 to it. ParseReply takes the
{summary, ops} object out of whatever wrapping a model puts round it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 99fe0b83f945d21820d783b592b00e8d460296e7 parent ab97638
3 files changed, +547 −0
  • internal/slides/assist/provider.go +284 −0
  • internal/slides/assist/provider_test.go +183 −0
  • internal/slides/assist/reply.go +80 −0
diff --git a/internal/slides/assist/provider.go b/internal/slides/assist/provider.go
new file mode 100644
index 0000000..11b7b42
--- /dev/null
+++ b/internal/slides/assist/provider.go
@@ -0,0 +1,284 @@
+// Package assist is the only code in Slides that talks to a model.
+//
+// There is one provider, TensorX (Paul, 2026-09-19: zero data
+// retention, treated as local inference), reached as an
+// OpenAI-compatible chat completion, and one call: "here is a deck and
+// a request, propose the operations". What the model answers is a
+// PROPOSAL and nothing more — the caller (internal/slides/assist.go)
+// validates every operation on a scratch copy of the deck before a
+// browser is told about any of them, and the browser applies them as
+// the person's own change. Nothing here writes anything.
+//
+// The shape is memoria's provider package (oficina/memoria,
+// internal/memoria/provider), adopted for the reasons it records: the
+// host is pinned (scheme, host AND port) on every request, proxies from
+// the environment are ignored, redirects are refused, keep-alives are
+// off, the response is read under a detectable cap, and a response the
+// provider marked as cut short is refused whole.
+//
+// **Nothing in this package logs, and no error it returns carries
+// content.** A provider's response body is the deck's words: an
+// OpenAI-compatible 4xx can echo the input that caused it, and a decode
+// error can quote the byte it choked on. Errors here are fixed strings
+// and status codes.
+package assist
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "strings"
+ "time"
+)
+
+const (
+ // BaseURL is TensorX's API root. A constant in production: a
+ // configurable base URL on an OpenAI-compatible client is a way to
+ // interpose a proxy that sees every deck. NewAt exists for the
+ // development override and tests only, and config.go refuses the
+ // override anywhere but development.
+ BaseURL = "https://api.tensorx.ai/v1"
+
+ // Name is how the provider is named to a reader.
+ Name = "TensorX"
+
+ // DefaultModel is offered when SLIDES_AI_MODELS names none: the
+ // suite's measured cheap tier (memoria's model.cheap), a dated id
+ // so the name names weights rather than a floating alias.
+ DefaultModel = "deepseek/deepseek-v4-flash-0731"
+
+ // Deadline bounds one call. A ten-slide deck is several thousand
+ // output tokens, which a flash-tier model writes in well under a
+ // minute; past this the person is told the assistant could not be
+ // reached rather than watching a spinner indefinitely.
+ Deadline = 90 * time.Second
+
+ // MaxTokens is the completion budget sent with every call. Enough
+ // for a twenty-slide deck with notes, and a bound on what one
+ // request can cost.
+ MaxTokens = 16384
+
+ // maxResponse caps what is read from the provider. MaxTokens of
+ // JSON is well under this; one byte past it is refused, never
+ // truncated.
+ maxResponse = 1 << 20
+)
+
+// Errors. Fixed strings: none of them ever carries a byte of a request
+// or a response.
+var (
+ ErrTooLarge = errors.New("assist: response exceeds the cap")
+ ErrMalformed = errors.New("assist: response is not the agreed shape")
+ // ErrTruncated is a response the provider itself marked cut short
+ // (finish_reason "length"). Refused whole: half a batch of
+ // operations is a deck nobody asked for.
+ ErrTruncated = errors.New("assist: response was truncated")
+ // ErrForbiddenHost is a request to anywhere but the pinned host, or
+ // any redirect at all.
+ ErrForbiddenHost = errors.New("assist: refused a host or redirect other than the pinned one")
+ // ErrTransport is every failure to send or read, flattened; the
+ // underlying error is dropped, not wrapped (a url.Error quotes a
+ // Location header the provider chose).
+ ErrTransport = errors.New("assist: transport failure")
+ // ErrMissingKey is a client built with no credential, refused at
+ // construction so a wiring bug fails at boot.
+ ErrMissingKey = errors.New("assist: no credential")
+)
+
+// StatusError is a non-2xx answer. The status and nothing else: the
+// body of a 4xx may echo the deck.
+type StatusError struct{ Code int }
+
+func (e *StatusError) Error() string {
+ return fmt.Sprintf("assist: provider answered status %d", e.Code)
+}
+
+// Message is one chat message.
+type Message struct {
+ Role string `json:"role"`
+ Content string `json:"content"`
+}
+
+// Client calls TensorX (or, in development, the base it was built for).
+type Client struct {
+ hc *http.Client
+ base string
+ key string
+}
+
+// New returns a client for TensorX. There is no exported way to change
+// where it dials other than NewAt, which is development's.
+func New(key string) (*Client, error) { return NewAt(key, BaseURL) }
+
+// NewAt is New pinned to another OpenAI-compatible base — a fake server
+// in tests, or a local one in development. The pin is the same: every
+// request to any other scheme, host or port is refused before it is
+// dialled.
+func NewAt(key, base string) (*Client, error) {
+ if key == "" {
+ return nil, ErrMissingKey
+ }
+ probe, err := http.NewRequest(http.MethodPost, base, nil)
+ if err != nil || probe.URL.Hostname() == "" || probe.URL.User != nil ||
+ (probe.URL.Scheme != "https" && probe.URL.Scheme != "http") {
+ return nil, ErrForbiddenHost
+ }
+ // Our own transport, built fresh rather than cloned from
+ // http.DefaultTransport (which a test may have replaced), with
+ // proxies off — memoria's review found HTTPS_PROXY receiving a
+ // CONNECT while the URL pin passed — and keep-alives off: net/http
+ // logs unsolicited bytes on an idle pooled connection, quoting
+ // them, past every sanitised path here.
+ tr := &http.Transport{
+ Proxy: nil,
+ DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
+ ForceAttemptHTTP2: true,
+ TLSHandshakeTimeout: 10 * time.Second,
+ ResponseHeaderTimeout: Deadline,
+ DisableKeepAlives: true,
+ }
+ return &Client{
+ base: strings.TrimRight(base, "/"),
+ key: key,
+ hc: &http.Client{
+ Transport: &pinnedTransport{
+ scheme: probe.URL.Scheme,
+ authority: authority(probe.URL.Scheme, probe.URL.Hostname(), probe.URL.Port()),
+ next: tr,
+ },
+ // No redirect is legitimate on this API, and following one
+ // hands the bearer key and the deck to wherever it points.
+ CheckRedirect: func(*http.Request, []*http.Request) error { return ErrForbiddenHost },
+ },
+ }, nil
+}
+
+// pinnedTransport refuses every scheme and authority but the one it was
+// built for, port included, before anything is dialled.
+type pinnedTransport struct {
+ scheme, authority string
+ next http.RoundTripper
+}
+
+func (p *pinnedTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ if r.URL.Scheme != p.scheme || r.URL.User != nil ||
+ authority(r.URL.Scheme, r.URL.Hostname(), r.URL.Port()) != p.authority {
+ return nil, ErrForbiddenHost
+ }
+ return p.next.RoundTrip(r)
+}
+
+// authority is host:port with the scheme's default port made explicit.
+func authority(scheme, host, port string) string {
+ if port == "" {
+ switch scheme {
+ case "https":
+ port = "443"
+ case "http":
+ port = "80"
+ }
+ }
+ return strings.ToLower(host) + ":" + port
+}
+
+type chatRequest struct {
+ Model string `json:"model"`
+ Messages []Message `json:"messages"`
+ ResponseFormat map[string]string `json:"response_format,omitempty"`
+ Temperature float64 `json:"temperature"`
+ MaxTokens int `json:"max_tokens"`
+}
+
+// Complete sends messages to model and returns the reply's content.
+//
+// It asks for a JSON object (response_format json_object). An
+// OpenAI-compatible model that does not support that answers 400, and
+// the call is made once more without it: the caller extracts the
+// object either way, and a 400 for any other reason is a 400 again.
+//
+// The deadline is the caller's context, bounded here by Deadline.
+func (c *Client) Complete(ctx context.Context, model string, messages []Message) (string, error) {
+ ctx, cancel := context.WithTimeout(ctx, Deadline)
+ defer cancel()
+ content, err := c.complete(ctx, model, messages, true)
+ var status *StatusError
+ if errors.As(err, &status) && status.Code == http.StatusBadRequest {
+ content, err = c.complete(ctx, model, messages, false)
+ }
+ return content, err
+}
+
+func (c *Client) complete(ctx context.Context, model string, messages []Message, jsonMode bool) (string, error) {
+ req := chatRequest{Model: model, Messages: messages, Temperature: 0.3, MaxTokens: MaxTokens}
+ if jsonMode {
+ req.ResponseFormat = map[string]string{"type": "json_object"}
+ }
+ body, err := json.Marshal(req)
+ if err != nil {
+ return "", ErrMalformed
+ }
+ hr, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/chat/completions", bytes.NewReader(body))
+ if err != nil {
+ return "", ErrForbiddenHost
+ }
+ hr.Header.Set("Authorization", "Bearer "+c.key)
+ hr.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.hc.Do(hr)
+ if err != nil {
+ return "", transportFailure(ctx, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode > 299 {
+ return "", &StatusError{Code: resp.StatusCode}
+ }
+ // A cap that is detectable: read one byte past it.
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, maxResponse+1))
+ if err != nil {
+ return "", transportFailure(ctx, err)
+ }
+ if len(raw) > maxResponse {
+ return "", ErrTooLarge
+ }
+ var envelope struct {
+ Choices []struct {
+ Message struct {
+ Content string `json:"content"`
+ } `json:"message"`
+ FinishReason string `json:"finish_reason"`
+ } `json:"choices"`
+ }
+ if err := json.Unmarshal(raw, &envelope); err != nil || len(envelope.Choices) != 1 {
+ return "", ErrMalformed
+ }
+ choice := envelope.Choices[0]
+ switch choice.FinishReason {
+ case "stop":
+ case "length":
+ return "", ErrTruncated
+ default:
+ // A content filter, a tool call, a value never seen: not a
+ // complete answer.
+ return "", ErrMalformed
+ }
+ return choice.Message.Content, nil
+}
+
+// transportFailure turns any failure to send or read into a fixed
+// error. The caller's context decides first, so a deadline is still
+// recognisable; everything else is ErrTransport with the original
+// dropped.
+func transportFailure(ctx context.Context, err error) error {
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return ctxErr
+ }
+ if errors.Is(err, ErrForbiddenHost) {
+ return ErrForbiddenHost
+ }
+ return ErrTransport
+}
diff --git a/internal/slides/assist/provider_test.go b/internal/slides/assist/provider_test.go
new file mode 100644
index 0000000..14de6cf
--- /dev/null
+++ b/internal/slides/assist/provider_test.go
@@ -0,0 +1,183 @@
+package assist
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// fake is an OpenAI-compatible server answering what each test says.
+type fake struct {
+ mu sync.Mutex
+ requests []map[string]any
+ auth []string
+ answer func(n int, req map[string]any) (int, string)
+}
+
+func (f *fake) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ var req map[string]any
+ _ = json.Unmarshal(body, &req)
+ f.mu.Lock()
+ f.requests = append(f.requests, req)
+ f.auth = append(f.auth, r.Header.Get("Authorization"))
+ n := len(f.requests)
+ f.mu.Unlock()
+ if r.URL.Path != "/v1/chat/completions" {
+ http.NotFound(w, r)
+ return
+ }
+ status, out := f.answer(n, req)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ io.WriteString(w, out)
+}
+
+func completion(content, finish string) string {
+ b, _ := json.Marshal(map[string]any{"choices": []any{map[string]any{
+ "message": map[string]any{"role": "assistant", "content": content}, "finish_reason": finish}}})
+ return string(b)
+}
+
+func serve(t *testing.T, f *fake) *Client {
+ t.Helper()
+ srv := httptest.NewServer(f)
+ t.Cleanup(srv.Close)
+ c, err := NewAt("secret-key", srv.URL+"/v1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+func TestCompleteAsksForJSONAndReturnsTheContent(t *testing.T) {
+ f := &fake{answer: func(int, map[string]any) (int, string) { return 200, completion(`{"ops":[]}`, "stop") }}
+ c := serve(t, f)
+ got, err := c.Complete(context.Background(), "deepseek/x", []Message{{Role: "user", Content: "hi"}})
+ if err != nil || got != `{"ops":[]}` {
+ t.Fatalf("Complete = %q, %v", got, err)
+ }
+ req := f.requests[0]
+ if req["model"] != "deepseek/x" || req["response_format"].(map[string]any)["type"] != "json_object" || req["max_tokens"].(float64) != MaxTokens {
+ t.Errorf("request = %v", req)
+ }
+ if f.auth[0] != "Bearer secret-key" {
+ t.Errorf("Authorization = %q", f.auth[0])
+ }
+}
+
+func TestCompleteRetriesWithoutJSONModeOnA400(t *testing.T) {
+ f := &fake{answer: func(n int, req map[string]any) (int, string) {
+ if _, json := req["response_format"]; json {
+ return 400, `{"error":{"message":"response_format unsupported, you said: SECRET DECK TEXT"}}`
+ }
+ return 200, completion("ok", "stop")
+ }}
+ got, err := serve(t, f).Complete(context.Background(), "m", nil)
+ if err != nil || got != "ok" || len(f.requests) != 2 {
+ t.Fatalf("Complete = %q, %v after %d requests", got, err, len(f.requests))
+ }
+}
+
+func TestCompleteFailuresCarryNoContent(t *testing.T) {
+ for name, tc := range map[string]struct {
+ status int
+ body string
+ want error
+ }{
+ "a 500": {500, `{"error":"SECRET DECK TEXT"}`, nil},
+ "cut short": {200, completion("SECRET DECK TEXT", "length"), ErrTruncated},
+ "a content filter": {200, completion("SECRET DECK TEXT", "content_filter"), ErrMalformed},
+ "two choices": {200, `{"choices":[{"finish_reason":"stop"},{"finish_reason":"stop"}]}`, ErrMalformed},
+ "not json": {200, `SECRET DECK TEXT`, ErrMalformed},
+ "over the cap": {200, `{"x":"` + strings.Repeat("a", maxResponse) + `"}`, ErrTooLarge},
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := &fake{answer: func(int, map[string]any) (int, string) { return tc.status, tc.body }}
+ _, err := serve(t, f).Complete(context.Background(), "m", nil)
+ if err == nil {
+ t.Fatal("no error")
+ }
+ if strings.Contains(err.Error(), "SECRET") {
+ t.Errorf("the error quotes the response: %v", err)
+ }
+ var status *StatusError
+ if tc.want == nil && !errors.As(err, &status) {
+ t.Errorf("err = %v, want a StatusError", err)
+ }
+ if tc.want != nil && !errors.Is(err, tc.want) {
+ t.Errorf("err = %v, want %v", err, tc.want)
+ }
+ })
+ }
+}
+
+func TestClientDialsOnlyItsOwnHostAndFollowsNoRedirect(t *testing.T) {
+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Error("the other server was reached")
+ }))
+ defer other.Close()
+ redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, other.URL+"/v1/chat/completions", http.StatusTemporaryRedirect)
+ }))
+ defer redirect.Close()
+ c, err := NewAt("k", redirect.URL+"/v1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.Complete(context.Background(), "m", nil); !errors.Is(err, ErrForbiddenHost) {
+ t.Errorf("a redirect: err = %v, want ErrForbiddenHost", err)
+ }
+ // The pin, directly: a request to another port on the same host.
+ c.base = other.URL + "/v1"
+ if _, err := c.Complete(context.Background(), "m", nil); !errors.Is(err, ErrForbiddenHost) {
+ t.Errorf("another port: err = %v, want ErrForbiddenHost", err)
+ }
+ if _, err := New(""); !errors.Is(err, ErrMissingKey) {
+ t.Errorf("New without a key: %v", err)
+ }
+ for _, base := range []string{"ftp://example.com/v1", "https://user:pw@example.com/v1", "not a url"} {
+ if _, err := NewAt("k", base); !errors.Is(err, ErrForbiddenHost) {
+ t.Errorf("NewAt(%q): %v", base, err)
+ }
+ }
+}
+
+func TestParseReplyTakesTheObjectOutOfItsWrapping(t *testing.T) {
+ for name, content := range map[string]string{
+ "bare": `{"summary":"Done.","ops":[{"op":"set_meta","title":"x"}]}`,
+ "fenced": "```json\n{\"summary\":\"Done.\",\"ops\":[{\"op\":\"set_meta\",\"title\":\"x\"}]}\n```",
+ "chatty": "Here you go:\n{\"summary\":\"Done.\",\"ops\":[{\"op\":\"set_meta\",\"title\":\"x\"}],\"thoughts\":\"ignored\"}",
+ } {
+ t.Run(name, func(t *testing.T) {
+ r, err := ParseReply(content)
+ if err != nil || r.Summary != "Done." || len(r.Ops) != 1 || string(r.Ops[0]["op"]) != `"set_meta"` {
+ t.Errorf("ParseReply = %+v, %v", r, err)
+ }
+ })
+ }
+ for name, content := range map[string]string{
+ "no object": "I cannot do that.",
+ "no ops": `{"summary":"x"}`,
+ "ops not a list": `{"ops":{"op":"x"}}`,
+ "a null op": `{"ops":[null]}`,
+ "two objects": `{"ops":[]} {"ops":[{"op":"remove_slide"}]}`,
+ "summary not text": `{"ops":[],"summary":["x"]}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ if _, err := ParseReply(content); !errors.Is(err, ErrMalformed) {
+ t.Errorf("err = %v, want ErrMalformed", err)
+ }
+ })
+ }
+ long, _ := ParseReply(`{"ops":[],"summary":"` + strings.Repeat("word ", 200) + `"}`)
+ if n := len([]rune(long.Summary)); n > MaxSummary+1 || !strings.HasSuffix(long.Summary, "…") {
+ t.Errorf("a long summary is %d runes: %q", n, long.Summary)
+ }
+}
diff --git a/internal/slides/assist/reply.go b/internal/slides/assist/reply.go
new file mode 100644
index 0000000..92037c0
--- /dev/null
+++ b/internal/slides/assist/reply.go
@@ -0,0 +1,80 @@
+package assist
+
+import (
+ "bytes"
+ "encoding/json"
+ "strings"
+ "unicode/utf8"
+)
+
+// MaxSummary is the most of the model's summary a person is shown, in
+// runes. A summary is a sentence or two; anything longer is cut at a
+// word, not refused, since the operations are what matter.
+const MaxSummary = 400
+
+// Reply is what the model proposed: operations, unvalidated, and a
+// sentence saying what they do. Every op stays raw JSON so the caller
+// rebuilds it key by key rather than trusting its shape.
+type Reply struct {
+ Summary string
+ Ops []map[string]json.RawMessage
+}
+
+// ParseReply reads the model's content as one JSON object
+// {"summary": "...", "ops": [...]}.
+//
+// Tolerant of the wrapping models put around JSON even when asked not
+// to (a ```json fence, a sentence before it): the object is taken from
+// the first '{' to the last '}'. Strict about the object itself: it
+// must decode, "ops" must be an array of objects, and nothing may
+// follow it. Unknown top-level keys are ignored — they carry nothing
+// the caller would act on. Every failure is ErrMalformed and quotes
+// nothing.
+func ParseReply(content string) (Reply, error) {
+ start := strings.IndexByte(content, '{')
+ end := strings.LastIndexByte(content, '}')
+ if start < 0 || end < start {
+ return Reply{}, ErrMalformed
+ }
+ dec := json.NewDecoder(bytes.NewReader([]byte(content[start : end+1])))
+ var out struct {
+ Summary json.RawMessage `json:"summary"`
+ Ops []map[string]json.RawMessage `json:"ops"`
+ }
+ if err := dec.Decode(&out); err != nil {
+ return Reply{}, ErrMalformed
+ }
+ if _, err := dec.Token(); err == nil {
+ // Two objects pretending to be one.
+ return Reply{}, ErrMalformed
+ }
+ if out.Ops == nil {
+ return Reply{}, ErrMalformed
+ }
+ for _, op := range out.Ops {
+ if op == nil {
+ return Reply{}, ErrMalformed
+ }
+ }
+ var summary string
+ if len(out.Summary) > 0 && string(out.Summary) != "null" {
+ if err := json.Unmarshal(out.Summary, &summary); err != nil {
+ return Reply{}, ErrMalformed
+ }
+ }
+ return Reply{Summary: clip(strings.TrimSpace(summary), MaxSummary), Ops: out.Ops}, nil
+}
+
+// clip shortens s to at most n runes, at a space where there is one
+// near the end, with an ellipsis.
+func clip(s string, n int) string {
+ if utf8.RuneCountInString(s) <= n {
+ return s
+ }
+ r := []rune(s)[:n]
+ cut := string(r)
+ if i := strings.LastIndexByte(cut, ' '); i > len(cut)*3/4 {
+ cut = cut[:i]
+ }
+ return strings.TrimRight(cut, " ,.;:") + "…"
+}