diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ffb256cf4..3054af3eb 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1639,6 +1639,48 @@ round's numbers and its gaps. Tests: [`session_speed_test.go`](../../internal/ga (`TestSessionCurveFromARealStream`, `TestSessionCurveFromCodexOwnSignIn`) and `sessions-speed.test.cjs`. +## DeepSeek's chat page + +`/deepseek-chat/` is DeepSeek's open-source web chat page +([deepseek-ai/chat-demo](https://github.com/deepseek-ai/chat-demo), MIT, +release v0.1.1) served by the gateway, so any of magpie's models chats in +it and its search and link reading are magpie's (@yanghonghang on X). The +release zip is embedded as published (`chatDemoZip`, its LICENSE served at +`/deepseek-chat/LICENSE`; `TestChatPageIsTheRelease` holds it to the +release's sha256). Nothing is built: the one place the bundle names +`https://api.deepseek.com` is served as `location.origin+"/deepseek-chat"`, +so the page calls the routes below at whatever address it was opened at. +`chatpage/magpie.js`, added to its index.html, gives the page the key +`magpie-deepseek-chat` on this computer (an agent key, counted as +`deepseek-chat`) and draws a model picker in its top bar, read from +`GET /deepseek-chat/models` (the caller's models, a DeepSeek flash model +first as the page's default) and sent as the `magpie_chat_model` cookie. + +- Files: the page's own files (GET and HEAD) are the only keyless routes, + in `readOnlyRoutes` and, while shared, `lanGuard`'s `chatPageOpen`, the + same bytes for everyone like the key page. A strict CSP keeps it to its + own origin and scripts. Every call it makes needs a key, which another + computer's user types into the page. +- `POST /deepseek-chat/anthropic/v1/messages` (`chatMessages`): the page's + tools `deepseek_web_search` and `deepseek_read_url` become Anthropic's + `web_search_20250305` (magpie's own search for a model that can't + search, with its citations) and a `read_url` function tool, which magpie + runs with `fetchPage` between rounds, all said to the page as one reply + in its own shapes (`chatTurn`). Each round goes through the gateway's + own Messages route, so routing, masking, limits and usage apply as to + any agent. The page shows sources only from text blocks' `citations`; a + model that names URLs in its text without citing gets no source chips. +- Files the page uploads (`/anthropic/v1/files`) are kept in memory for + the key that uploaded them until magpie restarts: images, PDFs and + text; Word, PowerPoint and EPUB files are refused. +- Voice input and read-aloud (`/v1/tools/asr`, `/v1/tools/tts`) use the + first speech-to-text or text-to-speech model a provider serves, and say + so when there is none. + +Tests: `TestChatPageOpensWithoutAKey`, `TestChatPageConversation`, +`TestChatPageSearchesAndReadsLinks`, `TestChatPageFiles`, +`TestTextCallsCitationAfterItsBlock`, `gateway-chat-page.test.cjs`. + ## Turning provider search off [Settings](../../internal/settings/settings.go)' `searcher: "off"` disables magpie's provider-assisted search, diff --git a/internal/gateway/chatpage.go b/internal/gateway/chatpage.go new file mode 100644 index 000000000..f88f4f64f --- /dev/null +++ b/internal/gateway/chatpage.go @@ -0,0 +1,481 @@ +package gateway + +import ( + "archive/zip" + "bytes" + _ "embed" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "mime/multipart" + "net/http" + "net/url" + "path" + "regexp" + "slices" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// ChatPagePath is DeepSeek's open-source web chat page (deepseek-ai/ +// chat-demo, MIT, its release v0.1.1 as built) served by the gateway, so +// any of magpie's models chats in it, with magpie's own web search and +// page reading behind its search and link tools (@yanghonghang on X). +// The release's bundle names https://api.deepseek.com once, as the +// origin it calls; it is served with the gateway's address and this path +// in its place, so the page calls the routes below at the address it was +// opened at. Nothing is built: the zip is embedded as released, and +// TestChatPageZip holds it to the release's own sha256. +const ChatPagePath = "/deepseek-chat" + +//go:embed chatpage/chat-demo-v0.1.1.zip +var chatDemoZip []byte + +//go:embed chatpage/magpie.js +var chatPageJS []byte + +// chatDemoSHA256 is the release asset's digest, as GitHub lists it for +// chat-demo-v0.1.1.zip. +const chatDemoSHA256 = "a7881be425c5c6ba63bc4909fb4c5cc8af4350ec7a9bd50486908f264d370b17" + +// chatDemoOrigin is the one place the bundle names the API it calls, and +// chatOrigin what it is served as instead: the address the page was +// opened at, this path after it. +const ( + chatDemoMain = "static/js/main.9820cd3a.js" + chatDemoOrigin = `let m="https://api.deepseek.com"` + chatOrigin = `let m=location.origin+"` + ChatPagePath + `"` +) + +// chatPageKeyAgent is the key the page is given on this computer, so its +// calls are counted under a name of their own (TokenFor). +const chatPageKeyAgent = "deepseek-chat" + +// chatPageFiles are the release's files by path, the main script and +// index.html as served; an error when the embedded zip isn't the +// release's. +var chatPageFiles = sync.OnceValues(func() (map[string][]byte, error) { + zr, err := zip.NewReader(bytes.NewReader(chatDemoZip), int64(len(chatDemoZip))) + if err != nil { + return nil, err + } + files := map[string][]byte{} + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + rc, err := f.Open() + if err != nil { + return nil, err + } + b, err := io.ReadAll(io.LimitReader(rc, 32<<20)) + rc.Close() + if err != nil { + return nil, err + } + files[path.Clean(f.Name)] = b + } + main := files[chatDemoMain] + if n := bytes.Count(main, []byte(chatDemoOrigin)); n != 1 { + return nil, fmt.Errorf("the page's script names its API origin %d times, not once", n) + } + files[chatDemoMain] = bytes.Replace(main, []byte(chatDemoOrigin), []byte(chatOrigin), 1) + index := files["index.html"] + at := bytes.Index(index, []byte(``), index[at:]) + files["magpie.js"] = chatPageJS + return files, nil +}) + +// chatPageFile is the release's file r asks for ("" for none): a GET or +// HEAD of the page's own path, clean, of a file the release has. +func chatPageFile(r *http.Request) string { + if r.Method != http.MethodGet && r.Method != http.MethodHead || r.URL.RawPath != "" { + return "" + } + rest, ok := strings.CutPrefix(r.URL.Path, ChatPagePath+"/") + if !ok { + return "" + } + if rest == "" { + rest = "index.html" + } + if path.Clean(rest) != rest || strings.HasPrefix(rest, "/") { + return "" + } + files, err := chatPageFiles() + if err != nil { + return "" + } + if _, ok := files[rest]; !ok { + return "" + } + return rest +} + +// chatPageOpen: r asks for one of the page's files, which lanGuard serves +// to another machine without a key while magpie is shared, as it does the +// key page: the same bytes for everyone, with nothing of the user's in +// them. Every call the page makes needs the key, which its holder types +// into the page. +func chatPageOpen(r *http.Request) bool { + return r.URL.Path == ChatPagePath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead) || chatPageFile(r) != "" +} + +// chatPageCSP keeps the page to its own files and its own origin: no +// script but the release's and magpie.js runs (the markdown it renders +// from a model's answer can't carry one), nothing is fetched from +// elsewhere, and it can't be framed. +const chatPageCSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" + +// chatPage serves the page's files. +func (s *Server) chatPage(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == ChatPagePath { + http.Redirect(w, r, ChatPagePath+"/", http.StatusFound) + return + } + files, err := chatPageFiles() + if err != nil { + writeError(w, provider.Chat, http.StatusInternalServerError, "the chat page can't be served: "+err.Error()) + return + } + name := chatPageFile(r) + if name == "" { + http.NotFound(w, r) + return + } + h := w.Header() + ct := mime.TypeByExtension(path.Ext(name)) + switch path.Ext(name) { + case ".js": + ct = "text/javascript; charset=utf-8" + case ".html": + ct = "text/html; charset=utf-8" + case ".woff2": + ct = "font/woff2" + case ".woff": + ct = "font/woff" + case ".ttf": + ct = "font/ttf" + case "": + ct = "text/plain; charset=utf-8" + } + if ct == "" { + ct = "application/octet-stream" + } + h.Set("Content-Type", ct) + h.Set("Content-Security-Policy", chatPageCSP) + h.Set("X-Frame-Options", "DENY") + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + if strings.HasPrefix(name, "static/") { + // hashed names: a new release is new names + h.Set("Cache-Control", "public, max-age=31536000, immutable") + } else { + h.Set("Cache-Control", "no-cache") + } + b := files[name] + h.Set("Content-Length", fmt.Sprint(len(b))) + if r.Method == http.MethodHead { + return + } + w.Write(b) +} + +// chatModelCookie is the model the page's picker (magpie.js) chose; the +// page itself always asks for deepseek-flash. +const chatModelCookie = "magpie_chat_model" + +// chatPageModels lists the models the caller may chat with, for the +// page's picker, and checks the key the page was given (the page's own +// GET /models). +func (s *Server) chatPageModels(w http.ResponseWriter, r *http.Request) { + shown := catalogFor(r) + data := make([]map[string]any, 0, len(shown)) + for _, e := range shown { + data = append(data, map[string]any{"id": e.ID, "object": "model", "display_name": e.PlainName()}) + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data, "default": chatDefaultModel(shown)}) +} + +var chatFlash = regexp.MustCompile(`(?i)deepseek.*flash`) + +// chatDefaultModel is the model the page chats with when its picker chose +// none: a DeepSeek flash model, as the page asks for, else the first. +func chatDefaultModel(shown []provider.Entry) string { + for _, e := range shown { + if chatFlash.MatchString(e.ID) { + return e.ID + } + } + if len(shown) > 0 { + return shown[0].ID + } + return "" +} + +// chatModel is the model a request of the page's goes to: the picker's, +// while the caller may still use it, else chatDefaultModel. +func chatModel(r *http.Request) string { + shown := catalogFor(r) + if c, err := r.Cookie(chatModelCookie); err == nil { + if id, err := url.QueryUnescape(c.Value); err == nil && slices.ContainsFunc(shown, func(e provider.Entry) bool { return e.ID == id }) { + return id + } + } + return chatDefaultModel(shown) +} + +// chatError answers the page in the shape it reads an error's words from +// ({"error":{"message"}}). +func chatError(w http.ResponseWriter, status int, msg string) { + writeError(w, provider.Anthropic, status, msg) +} + +// ---- files ------------------------------------------------------------------ + +// The page uploads each attachment once (POST /anthropic/v1/files) and +// names it by id in its messages. magpie keeps them in memory, for the +// caller that uploaded them, until it restarts: an id it no longer has +// becomes a line asking for the file again, never a failed reply. +const ( + chatFileMax = 20 << 20 + chatFilesMax = 200 << 20 + chatFileTextN = 400_000 // a text file's characters a model is given +) + +type chatUpload struct { + owner, name, mime string + kind string // "image", "pdf" or "text" + data []byte + at time.Time +} + +var chatFiles = struct { + sync.Mutex + m map[string]*chatUpload + order []string + size int +}{m: map[string]*chatUpload{}} + +// chatImageTypes are the images every vendor's API takes. +var chatImageTypes = map[string]bool{"image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true} + +// chatFileKind is how a file is given to a model, by its bytes: +// an image, a PDF or text; "" for what no model is given (a Word or +// PowerPoint file, an EPUB, a TIFF). +func chatFileKind(b []byte) (kind, mt string) { + sniffed, _, _ := mime.ParseMediaType(http.DetectContentType(b)) + switch { + case chatImageTypes[sniffed]: + return "image", sniffed + case sniffed == "application/pdf": + return "pdf", sniffed + case utf8.Valid(b) && !bytes.ContainsRune(b, 0): + return "text", "text/plain" + } + return "", "" +} + +// chatFileUpload is the page's POST /anthropic/v1/files. +func (s *Server) chatFileUpload(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, chatFileMax+1<<20) + f, hdr, err := r.FormFile("file") + if err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + chatError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("the file is larger than %d MB", chatFileMax>>20)) + return + } + chatError(w, http.StatusBadRequest, "the upload has no file: send it as the form's \"file\"") + return + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, chatFileMax+1)) + if err != nil { + chatError(w, http.StatusBadRequest, "the file couldn't be read: "+err.Error()) + return + } + if len(data) > chatFileMax { + chatError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("the file is larger than %d MB", chatFileMax>>20)) + return + } + kind, mt := chatFileKind(data) + if kind == "" { + chatError(w, http.StatusUnsupportedMediaType, hdr.Filename+" can't be given to a model as it is: attach images (PNG, JPEG, GIF, WebP), PDFs or text files; save a Word or PowerPoint file as PDF first") + return + } + id := "file_" + randomHex(12) + cf := &chatUpload{owner: chatOwner(r), name: hdr.Filename, mime: mt, kind: kind, data: data, at: time.Now()} + chatFiles.Lock() + chatFiles.m[id] = cf + chatFiles.order = append(chatFiles.order, id) + chatFiles.size += len(data) + for chatFiles.size > chatFilesMax && len(chatFiles.order) > 1 { + old := chatFiles.order[0] + chatFiles.order = chatFiles.order[1:] + if o := chatFiles.m[old]; o != nil { + chatFiles.size -= len(o.data) + delete(chatFiles.m, old) + } + } + chatFiles.Unlock() + writeJSON(w, http.StatusOK, map[string]any{"id": id, "type": "file", "size_bytes": len(data), + "created_at": cf.at.UTC().Format(time.RFC3339), "filename": hdr.Filename, "mime_type": mt}) +} + +// chatFileDelete is the page's DELETE /anthropic/v1/files/{id}. +func (s *Server) chatFileDelete(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + chatFiles.Lock() + if f := chatFiles.m[id]; f != nil && f.owner == chatOwner(r) { + delete(chatFiles.m, id) + chatFiles.order = slices.DeleteFunc(chatFiles.order, func(o string) bool { return o == id }) + chatFiles.size -= len(f.data) + } + chatFiles.Unlock() + writeJSON(w, http.StatusOK, map[string]any{"id": id, "type": "file_deleted"}) +} + +// chatFileOf is the caller's file id, nil when magpie hasn't it. +func chatFileOf(r *http.Request, id string) *chatUpload { + chatFiles.Lock() + defer chatFiles.Unlock() + if f := chatFiles.m[id]; f != nil && f.owner == chatOwner(r) { + return f + } + return nil +} + +// chatOwner is whose a file is: the gateway key that uploaded it, "" for +// this computer's calls. +func chatOwner(r *http.Request) string { + return access.Caller(r.Context()).KeyID +} + +// chatFileBlock is the block a file is given to a model as. +func chatFileBlock(f *chatUpload) map[string]any { + switch f.kind { + case "image": + return map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": f.mime, "data": base64.StdEncoding.EncodeToString(f.data)}} + case "pdf": + return map[string]any{"type": "document", "source": map[string]any{"type": "base64", "media_type": "application/pdf", "data": base64.StdEncoding.EncodeToString(f.data)}, "title": f.name} + } + text := string(f.data) + if r := []rune(text); len(r) > chatFileTextN { + text = string(r[:chatFileTextN]) + fmt.Sprintf("\n[%d more characters not included]", len(r)-chatFileTextN) + } + return map[string]any{"type": "text", "text": "File " + f.name + ":\n\n" + text} +} + +// ---- speech ----------------------------------------------------------------- + +// chatASR is the page's voice input (POST /v1/tools/asr, a form with the +// recording as "file"): the first speech-to-text model a provider that is +// on serves (FirstServing), answering {"text"} as the page reads it. +func (s *Server) chatASR(w http.ResponseWriter, r *http.Request) { + model := FirstServing(catalog.ServesTranscription) + if model == "" { + chatError(w, http.StatusNotImplemented, "voice input needs a speech-to-text model (whisper, gpt-4o-transcribe…): add a provider that serves one in magpie") + return + } + r.Body = http.MaxBytesReader(w, r.Body, 30<<20) + f, hdr, err := r.FormFile("file") + if err != nil { + chatError(w, http.StatusBadRequest, "the recording is missing: send it as the form's \"file\"") + return + } + defer f.Close() + var form bytes.Buffer + mw := multipart.NewWriter(&form) + mw.WriteField("model", model) + mw.WriteField("response_format", "json") + name := hdr.Filename + if name == "" { + name = "recording.wav" + } + part, _ := mw.CreateFormFile("file", name) + if _, err := io.Copy(part, f); err != nil { + chatError(w, http.StatusBadRequest, "the recording couldn't be read: "+err.Error()) + return + } + mw.Close() + s.transcribe("/audio/transcriptions", "transcriptions")(w, chatInner(r, "/v1/audio/transcriptions", mw.FormDataContentType(), form.Bytes())) +} + +// chatVoices are the page's two voices as OpenAI's. +var chatVoices = map[string]string{"stella": "nova", "tide": "onyx"} + +// chatTTS is the page's read-aloud (POST /v1/tools/tts): the first +// text-to-speech model a provider that is on serves, asked for raw PCM +// (24 kHz, 16-bit, mono on OpenAI's API, which is what the page plays). +func (s *Server) chatTTS(w http.ResponseWriter, r *http.Request) { + model := FirstServing(catalog.ServesSpeech) + if model == "" { + chatError(w, http.StatusNotImplemented, "reading aloud needs a text-to-speech model (tts-1, gpt-4o-mini-tts…): add a provider that serves one in magpie") + return + } + var in struct { + Text string `json:"text"` + Voice string `json:"voice_id"` + FilterMarkdown bool `json:"filter_markdown"` + } + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&in); err != nil || strings.TrimSpace(in.Text) == "" { + chatError(w, http.StatusBadRequest, "send {\"text\": …} to read aloud") + return + } + text := in.Text + if in.FilterMarkdown { + text = plainOfMarkdown(text) + } + voice := chatVoices[in.Voice] + if voice == "" { + voice = "nova" + } + b, _ := json.Marshal(map[string]any{"model": model, "input": text, "voice": voice, "response_format": "pcm"}) + s.speak(w, chatInner(r, "/v1/audio/speech", "application/json", b)) +} + +var ( + mdLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`) + mdMarks = regexp.MustCompile("(?m)^\\s{0,3}(#{1,6}\\s+|>\\s?|[-*+]\\s+|\\d+\\.\\s+)|[*_`~]+") + mdFences = regexp.MustCompile("(?s)```[^\n]*\n(.*?)```") +) + +// plainOfMarkdown is markdown as it is read aloud: no marks, a link's +// words without its address. +func plainOfMarkdown(s string) string { + s = mdFences.ReplaceAllString(s, "$1") + s = mdLink.ReplaceAllString(s, "$1") + return strings.TrimSpace(mdMarks.ReplaceAllString(s, "")) +} + +// chatInner is r as a call to the gateway's own route at p, with body: +// the caller and everything lanGuard and the key checks put on it kept. +func chatInner(r *http.Request, p, ctype string, body []byte) *http.Request { + in := r.Clone(r.Context()) + in.URL.Path, in.URL.RawPath = p, "" + in.RequestURI = p + in.Pattern = "POST " + p + in.Header.Set("Content-Type", ctype) + in.Header.Del("Content-Length") + in.Header.Del("Accept-Encoding") + in.Header.Del("Anthropic-Beta") + in.Header.Del("Cookie") + in.Body = io.NopCloser(bytes.NewReader(body)) + in.ContentLength = int64(len(body)) + return in +} diff --git a/internal/gateway/chatpage/chat-demo-v0.1.1.zip b/internal/gateway/chatpage/chat-demo-v0.1.1.zip new file mode 100644 index 000000000..7b9217cdb Binary files /dev/null and b/internal/gateway/chatpage/chat-demo-v0.1.1.zip differ diff --git a/internal/gateway/chatpage/magpie.js b/internal/gateway/chatpage/magpie.js new file mode 100644 index 000000000..32d02e9c7 --- /dev/null +++ b/internal/gateway/chatpage/magpie.js @@ -0,0 +1,144 @@ +// magpie's addition to DeepSeek's chat page: the key on this computer, +// and which of magpie's models answers. The page asks for one model of +// DeepSeek's; magpie answers with the one picked here, which it reads +// from the magpie_chat_model cookie. +(function () { + "use strict"; + var KEY = "chat-demo:api-key"; + var COOKIE = "magpie_chat_model"; + var PICKED = "magpie:chat-model"; + var local = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname); + var store = { + get: function (k) { try { return localStorage.getItem(k); } catch (e) { return null; } }, + set: function (k, v) { try { localStorage.setItem(k, v); } catch (e) {} }, + }; + // on this computer the page needs no key of the user's: magpie takes + // its own agent's + if (local && !store.get(KEY)) store.set(KEY, "magpie-deepseek-chat"); + + function setCookie(id) { + document.cookie = COOKIE + "=" + encodeURIComponent(id) + "; Path=/deepseek-chat; SameSite=Strict; Max-Age=31536000"; + } + var picked = store.get(PICKED); + if (picked) setCookie(picked); + + var css = [ + "#magpie-model{position:fixed;top:12px;right:64px;z-index:2147483000;font:13px/1.2 system-ui,-apple-system,sans-serif;color-scheme:inherit}", + "#magpie-model button{all:unset;box-sizing:border-box;cursor:pointer}", + "#magpie-model .mm-btn{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 10px;border-radius:8px;max-width:260px;color:#3a3a3c;color:light-dark(#3a3a3c,#e5e5ea);background:transparent;transition:background-color .15s ease}", + "#magpie-model .mm-btn span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", + "#magpie-model .mm-btn svg{flex:none;opacity:.6}", + "@media (hover:hover) and (pointer:fine){#magpie-model .mm-btn:hover{background:rgba(127,127,127,.12)}}", + "#magpie-model .mm-btn:active{transform:scale(.97)}", + "#magpie-model .mm-menu{position:absolute;top:36px;right:0;min-width:220px;max-width:min(360px,calc(100vw - 24px));max-height:min(420px,calc(100vh - 72px));overflow:auto;padding:4px;border-radius:10px;background:#fff;background:light-dark(#fff,#2c2c2e);box-shadow:0 0 0 .5px rgba(0,0,0,.12),0 8px 28px rgba(0,0,0,.16);transform-origin:top right;opacity:0;transform:scale(.95);transition:opacity .15s cubic-bezier(.23,1,.32,1),transform .15s cubic-bezier(.23,1,.32,1);pointer-events:none}", + "#magpie-model.open .mm-menu{opacity:1;transform:none;pointer-events:auto;transition-duration:.2s}", + "#magpie-model .mm-item{display:flex;align-items:center;gap:8px;width:100%;padding:7px 10px;border-radius:6px;color:#1c1c1e;color:light-dark(#1c1c1e,#f2f2f7)}", + "#magpie-model .mm-item span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", + "#magpie-model .mm-item:hover,#magpie-model .mm-item:focus-visible{background:rgba(127,127,127,.14)}", + "#magpie-model .mm-item .mm-on{visibility:hidden}", + "#magpie-model .mm-item[aria-checked=true] .mm-on{visibility:visible}", + "@media (max-width:640px){#magpie-model{right:56px}}", + "@media (prefers-reduced-motion:reduce){#magpie-model .mm-menu{transform:none}}", + ].join("\n"); + + var chevron = ''; + var check = ''; + + function el(tag, cls, html) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (html) e.innerHTML = html; + return e; + } + + function mount(list) { + if (!list.data || !list.data.length || document.getElementById("magpie-model")) return; + var current = list.data.some(function (m) { return m.id === picked; }) ? picked : list["default"]; + var style = el("style"); + style.textContent = css; + document.head.appendChild(style); + var box = el("div"); + box.id = "magpie-model"; + var btn = el("button", "mm-btn"); + btn.setAttribute("aria-haspopup", "menu"); + btn.setAttribute("aria-expanded", "false"); + var name = el("span"); + btn.appendChild(name); + btn.insertAdjacentHTML("beforeend", chevron); + var menu = el("div", "mm-menu"); + menu.setAttribute("role", "menu"); + var shown = function (id) { + var m = list.data.filter(function (x) { return x.id === id; })[0]; + return (m && (m.display_name || m.id)) || id; + }; + list.data.forEach(function (m) { + var it = el("button", "mm-item"); + it.setAttribute("role", "menuitemradio"); + it.dataset.id = m.id; + it.title = m.id; + var s = el("span"); + s.textContent = m.display_name || m.id; + it.appendChild(s); + it.insertAdjacentHTML("beforeend", check); + it.addEventListener("click", function () { + current = m.id; + store.set(PICKED, m.id); + setCookie(m.id); + draw(); + toggle(false); + btn.focus(); + }); + menu.appendChild(it); + }); + function draw() { + name.textContent = shown(current); + btn.title = current; + menu.querySelectorAll(".mm-item").forEach(function (it) { + it.setAttribute("aria-checked", String(it.dataset.id === current)); + }); + } + function toggle(open) { + box.classList.toggle("open", open); + btn.setAttribute("aria-expanded", String(open)); + if (open) { + var on = menu.querySelector('[aria-checked="true"]'); + if (on) { on.scrollIntoView({ block: "nearest" }); on.focus(); } + } + } + btn.addEventListener("click", function () { toggle(!box.classList.contains("open")); }); + document.addEventListener("mousedown", function (e) { if (!box.contains(e.target)) toggle(false); }); + box.addEventListener("keydown", function (e) { + if (e.key === "Escape") { toggle(false); btn.focus(); return; } + if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; + var items = Array.prototype.slice.call(menu.querySelectorAll(".mm-item")); + var i = items.indexOf(document.activeElement); + if (i < 0) { toggle(true); e.preventDefault(); return; } + i = (i + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length; + items[i].focus(); + e.preventDefault(); + }); + draw(); + box.appendChild(btn); + box.appendChild(menu); + document.body.appendChild(box); + } + + var tries = 0; + function load() { + var key = store.get(KEY); + if (!key) { + // the page asks for the key; once it is typed the models can be read + if (tries++ < 600) setTimeout(load, 1000); + return; + } + fetch("models", { headers: { Authorization: "Bearer " + key } }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (list) { + if (list) mount(list); + else if (tries++ < 600) setTimeout(load, 3000); + }) + .catch(function () { if (tries++ < 600) setTimeout(load, 3000); }); + } + if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", load); + else load(); +})(); diff --git a/internal/gateway/chatpage_messages.go b/internal/gateway/chatpage_messages.go new file mode 100644 index 000000000..98bbb4a7d --- /dev/null +++ b/internal/gateway/chatpage_messages.go @@ -0,0 +1,748 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" +) + +// The chat page (ChatPagePath) speaks DeepSeek's Anthropic-compatible +// Messages API with two server tools of DeepSeek's: deepseek_web_search +// and deepseek_read_url, whose calls and results it shows in its own +// shapes (its parseEvent.ts). chatMessages answers it with any of magpie's +// models: the search is Anthropic's web_search tool, which magpie runs for +// a model that can't search (searchRounds), and the link reading a tool of +// the request's own, read_url, which is run here with magpie's web_fetch +// (fetchPage) and its result handed back to the model, round after round, +// as one reply to the page. + +const ( + chatRounds = 10 // a reply's rounds of reading links at most + chatReadChars = 40_000 // a page's characters a model is given + chatReadTool = "read_url" + // the page's own system prompt, naming DeepSeek: another model is + // not told it is DeepSeek + chatDemoSystem = "该助手为DeepSeek,由深度求索公司创造。" + // chatSigned is what a read page's text is kept under in the + // result's signature, which the page sends back with its history + chatSigned = "m1." +) + +var chatReadDef = map[string]any{ + "name": chatReadTool, + "description": "Read a web page and return its text. Use it for a link the user gives, or for a page a search found when its snippet isn't enough.", + "input_schema": map[string]any{"type": "object", "properties": map[string]any{ + "url": map[string]any{"type": "string", "description": "The page's http:// or https:// URL"}, + }, "required": []string{"url"}}, +} + +type chatRequest struct { + System json.RawMessage `json:"system"` + Messages []struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` + } `json:"messages"` + Thinking *struct { + Type string `json:"type"` + } `json:"thinking"` + Tools []struct { + Type string `json:"type"` + Name string `json:"name"` + } `json:"tools"` + Title *struct { + Enabled bool `json:"enabled"` + } `json:"title"` +} + +// chatMessages is the page's POST /anthropic/v1/messages. +func (s *Server) chatMessages(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 256<<20)) + if err != nil { + chatError(w, http.StatusRequestEntityTooLarge, "the request is too large") + return + } + var in chatRequest + if err := json.Unmarshal(body, &in); err != nil { + chatError(w, http.StatusBadRequest, "the body isn't the chat page's JSON: "+err.Error()) + return + } + model := chatModel(r) + if model == "" { + chatError(w, http.StatusServiceUnavailable, "magpie has no model to chat with: add a provider in magpie first") + return + } + req, title := chatUpstream(r, &in, model) + t := &chatTurn{s: s, r: r, w: w, req: req, model: model, title: title} + t.run() +} + +// chatUpstream is the Messages request the page's asks for, and the +// title the page asked for (""): its reminder of date and place a +// system line, its files the blocks they are, the pages it read before +// with the question they were read for, its tools Anthropic's search +// and read_url. +func chatUpstream(r *http.Request, in *chatRequest, model string) (map[string]any, string) { + var system []string + var sys string + if json.Unmarshal(in.System, &sys) == nil && sys != "" && strings.TrimSpace(sys) != chatDemoSystem { + system = append(system, sys) + } + var msgs []map[string]any + reminder, title := "", "" + for _, m := range in.Messages { + switch m.Role { + case "latest_reminder": + json.Unmarshal(m.Content, &reminder) + case "user": + content := chatUserContent(r, m.Content) + if title == "" { + title = chatTitle(chatQuestion(m.Content)) + } + msgs = append(msgs, map[string]any{"role": "user", "content": content}) + case "assistant": + content, read := chatAssistantContent(m.Content) + // the pages read for a question go after it, as the + // page's own API puts them + if len(read) > 0 && len(msgs) > 0 && msgs[len(msgs)-1]["role"] == "user" { + prev := msgs[len(msgs)-1]["content"].([]map[string]any) + msgs[len(msgs)-1]["content"] = append(prev, read...) + } + if len(content) > 0 { + msgs = append(msgs, map[string]any{"role": "assistant", "content": content}) + } + } + } + if line := chatReminder(reminder); line != "" { + system = append(system, line) + } + out := map[string]any{"model": model, "messages": msgs, "stream": true} + if len(system) > 0 { + out["system"] = strings.Join(system, "\n\n") + } + if in.Thinking != nil { + switch in.Thinking.Type { + case "enabled": + out["thinking"] = map[string]any{"type": "adaptive"} + case "disabled": + out["thinking"] = map[string]any{"type": "disabled"} + } + } + var tools []any + for _, t := range in.Tools { + switch t.Type { + case "deepseek_web_search": + tools = append(tools, map[string]any{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}) + case "deepseek_read_url": + tools = append(tools, chatReadDef) + } + } + if len(tools) > 0 { + out["tools"] = tools + } + if in.Title == nil || !in.Title.Enabled { + title = "" + } + return out, title +} + +// chatTitle is a conversation's title, from its first question. +func chatTitle(q string) string { + q = strings.TrimSpace(q) + if i := strings.IndexByte(q, '\n'); i >= 0 { + q = strings.TrimSpace(q[:i]) + } + if r := []rune(q); len(r) > 24 { + q = string(r[:24]) + "…" + } + return q +} + +// chatQuestion is a question's own words, without its files. +func chatQuestion(raw json.RawMessage) string { + var s string + if json.Unmarshal(raw, &s) == nil { + return s + } + var blocks []struct { + Type string `json:"type"` + Text string `json:"text"` + } + json.Unmarshal(raw, &blocks) + for _, b := range blocks { + if b.Type == "text" && strings.TrimSpace(b.Text) != "" { + return b.Text + } + } + return "" +} + +// chatReminder is the page's latest_reminder ("date,weekday,place,Web, +// language", the place empty when it has none) as a line of the system +// prompt. +func chatReminder(s string) string { + parts := strings.Split(s, ",") + if len(parts) < 5 { + return "" + } + date, weekday := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]) + lang := strings.TrimSpace(parts[len(parts)-1]) + place := strings.TrimSpace(strings.Join(parts[2:len(parts)-2], ",")) + line := "Today is " + date + if weekday != "" { + line += ", " + weekday + } + line += "." + if place != "" { + line += " The user is in " + place + "." + } + if lang != "" { + line += " The user's language is " + lang + "." + } + return line +} + +// chatUserContent is a question's blocks: its text, and each file the +// page uploaded as the block a model takes it as. +func chatUserContent(r *http.Request, raw json.RawMessage) []map[string]any { + var s string + if json.Unmarshal(raw, &s) == nil { + return []map[string]any{{"type": "text", "text": s}} + } + var blocks []struct { + Type string `json:"type"` + Text string `json:"text"` + Source struct { + Type string `json:"type"` + FileID string `json:"file_id"` + } `json:"source"` + } + json.Unmarshal(raw, &blocks) + out := []map[string]any{} + for _, b := range blocks { + switch b.Type { + case "text": + if b.Text != "" { + out = append(out, map[string]any{"type": "text", "text": b.Text}) + } + case "image", "document": + if f := chatFileOf(r, b.Source.FileID); f != nil { + out = append(out, chatFileBlock(f)) + } else { + out = append(out, map[string]any{"type": "text", "text": "(A file attached here is no longer available.)"}) + } + } + } + if len(out) == 0 { + out = append(out, map[string]any{"type": "text", "text": "…"}) + } + return out +} + +// chatAssistantContent is an answer the page sends back: its text, and +// the thinking of an answer it asks to go on with; the pages it read are +// given back as text, to go after the question they were read for. +func chatAssistantContent(raw json.RawMessage) (content, read []map[string]any) { + var blocks []map[string]any + json.Unmarshal(raw, &blocks) + for _, b := range blocks { + switch b["type"] { + case "text": + if t, _ := b["text"].(string); t != "" { + content = append(content, map[string]any{"type": "text", "text": t}) + } + case "thinking": + t, _ := b["thinking"].(string) + sig, _ := b["signature"].(string) + if strings.TrimSpace(t) != "" && sig != "" { + content = append(content, map[string]any{"type": "thinking", "thinking": t, "signature": sig}) + } + case "web_fetch_tool_result": + if text := chatReadBack(b); text != "" { + read = append(read, map[string]any{"type": "text", "text": text}) + } + } + } + return content, read +} + +// chatReadBack is a page read before, from its result block: where it +// was read and its text, which chatSign kept in the signature. +func chatReadBack(b map[string]any) string { + sig, _ := b["signature"].(string) + enc, ok := strings.CutPrefix(sig, chatSigned) + if !ok { + return "" + } + text, err := base64.StdEncoding.DecodeString(enc) + if err != nil { + return "" + } + content, _ := b["content"].(map[string]any) + u, _ := content["url"].(string) + return "Content of " + u + ":\n\n" + string(text) +} + +func chatSign(text string) string { + return chatSigned + base64.StdEncoding.EncodeToString([]byte(text)) +} + +// ---- the reply -------------------------------------------------------------- + +// chatTurn is one reply to the page: rounds of the model, each read_url +// call it makes run between them, all said as one message. +type chatTurn struct { + s *Server + r *http.Request + w http.ResponseWriter + req map[string]any + model string + title string + started bool // the page was sent message_start + index int // the page's next block index + usage [4]int + failed bool +} + +func (t *chatTurn) event(name string, v any) bool { + b, _ := json.Marshal(v) + if _, err := fmt.Fprintf(t.w, "event: %s\ndata: %s\n\n", name, b); err != nil { + return false + } + if f, ok := t.w.(http.Flusher); ok { + f.Flush() + } + return true +} + +func (t *chatTurn) start() { + if t.started { + return + } + t.started = true + h := t.w.Header() + h.Set("Content-Type", "text/event-stream; charset=utf-8") + h.Set("Cache-Control", "no-cache") + h.Set("X-Accel-Buffering", "no") + t.w.WriteHeader(http.StatusOK) + t.event("message_start", map[string]any{"type": "message_start", "message": map[string]any{ + "id": randomHex(16), "type": "message", "role": "assistant", "model": t.model, "content": []any{}, + "usage": map[string]any{"input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0}, + }}) +} + +// block sends the page one whole block. +func (t *chatTurn) block(b map[string]any) { + t.start() + t.event("content_block_start", map[string]any{"type": "content_block_start", "index": t.index, "content_block": b}) + t.event("content_block_stop", map[string]any{"type": "content_block_stop", "index": t.index}) + t.index++ +} + +func (t *chatTurn) fail(msg string) { + if !t.started { + chatError(t.w, http.StatusBadGateway, msg) + t.failed = true + return + } + t.event("error", map[string]any{"type": "error", "error": map[string]any{"type": "api_error", "message": msg}}) + t.failed = true +} + +func (t *chatTurn) run() { + stop := "end_turn" + for n := 0; ; n++ { + res := t.round() + if t.failed { + return + } + stop = res.stop + if res.stop != "tool_use" || len(res.calls) == 0 || n+1 >= chatRounds { + break + } + results := []map[string]any{} + for _, c := range res.calls { + results = append(results, t.read(c)) + } + msgs := t.req["messages"].([]map[string]any) + t.req["messages"] = append(msgs, + map[string]any{"role": "assistant", "content": res.content}, + map[string]any{"role": "user", "content": results}) + } + switch stop { + case "end_turn", "max_tokens", "refusal": + default: + // tool_use left with rounds spent, stop_sequence, pause_turn + stop = "end_turn" + } + t.start() + delta := map[string]any{"stop_reason": stop, "stop_sequence": nil} + if t.title != "" { + delta["title"] = t.title + } + t.event("message_delta", map[string]any{"type": "message_delta", "delta": delta, "usage": map[string]any{ + "input_tokens": t.usage[0], "cache_creation_input_tokens": t.usage[1], "cache_read_input_tokens": t.usage[2], "output_tokens": t.usage[3]}}) + t.event("message_stop", map[string]any{"type": "message_stop"}) +} + +type chatPageCall struct { + id, name string + input map[string]any +} + +type chatRound struct { + stop string + content []map[string]any // the answer, to send back with the calls' results + calls []chatPageCall +} + +// chatBlock is a block of a round as it arrives. +type chatBlock struct { + start map[string]any + out int // the page's index, -1 for one it is shown whole at its end + text strings.Builder + sig string + args strings.Builder +} + +// round asks the model once, through the gateway's own Messages route, +// and tells the page what it says as it says it. +func (t *chatTurn) round() chatRound { + body, _ := json.Marshal(t.req) + in := chatInner(t.r, "/v1/messages", "application/json", body) + in.Header.Set("Accept", "text/event-stream") + var res chatRound + blocks := map[int]*chatBlock{} + var order []*chatBlock + var errMsg string + tap := &sseTap{h: http.Header{}, on: func(name string, data []byte) bool { + var ev map[string]any + if json.Unmarshal(data, &ev) != nil { + return true + } + idx := -1 + if f, ok := ev["index"].(float64); ok { + idx = int(f) + } + switch name { + case "message_start": + msg, _ := ev["message"].(map[string]any) + t.addUsage(msg["usage"], true) + case "content_block_start": + cb, _ := ev["content_block"].(map[string]any) + b := &chatBlock{start: cb, out: -1} + blocks[idx] = b + order = append(order, b) + switch cb["type"] { + case "text": + b.out = t.index + t.index++ + t.start() + return t.event(name, map[string]any{"type": name, "index": b.out, "content_block": map[string]any{"type": "text", "text": ""}}) + case "thinking": + b.out = t.index + t.index++ + t.start() + return t.event(name, map[string]any{"type": name, "index": b.out, "content_block": map[string]any{"type": "thinking", "thinking": "", "signature": ""}}) + case "web_search_tool_result": + t.block(chatSearchResult(cb)) + } + case "content_block_delta": + b := blocks[idx] + if b == nil { + return true + } + d, _ := ev["delta"].(map[string]any) + switch d["type"] { + case "text_delta": + s, _ := d["text"].(string) + b.text.WriteString(s) + case "thinking_delta": + s, _ := d["thinking"].(string) + b.text.WriteString(s) + case "signature_delta": + s, _ := d["signature"].(string) + b.sig += s + case "input_json_delta": + s, _ := d["partial_json"].(string) + b.args.WriteString(s) + return true + } + if b.out >= 0 { + return t.event(name, map[string]any{"type": name, "index": b.out, "delta": d}) + } + case "content_block_stop": + b := blocks[idx] + if b == nil { + return true + } + if b.out >= 0 { + return t.event(name, map[string]any{"type": name, "index": b.out}) + } + if b.start["type"] == "server_tool_use" && b.start["name"] == "web_search" { + var q struct { + Query string `json:"query"` + } + json.Unmarshal([]byte(b.args.String()), &q) + t.block(map[string]any{"type": "server_tool_use", "id": b.start["id"], "name": "deepseek_web_search", + "kind": "search", "input": map[string]any{"action": "search", "queries": []string{q.Query}}}) + } + case "message_delta": + d, _ := ev["delta"].(map[string]any) + if s, _ := d["stop_reason"].(string); s != "" { + res.stop = s + } + t.addUsage(ev["usage"], false) + case "error": + e, _ := ev["error"].(map[string]any) + errMsg, _ = e["message"].(string) + if errMsg == "" { + errMsg = string(data) + } + case "ping": + if t.started { + return t.event("ping", map[string]any{"type": "ping"}) + } + } + return true + }} + keepsSignIn(t.s.handle(provider.Anthropic))(tap, in) + if tap.status != 0 && tap.status != http.StatusOK || !tap.sse { + msg := tap.body.String() + var e struct { + Error struct { + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal(tap.body.Bytes(), &e) == nil && e.Error.Message != "" { + msg = e.Error.Message + } + if !t.started { + status := tap.status + if status == 0 || status == http.StatusOK { + status = http.StatusBadGateway + } + chatError(t.w, status, msg) + t.failed = true + return res + } + t.fail(msg) + return res + } + if errMsg != "" { + t.fail(errMsg) + return res + } + // the answer as it goes back to the model with the calls' results + for _, b := range order { + switch b.start["type"] { + case "text": + res.content = append(res.content, map[string]any{"type": "text", "text": b.text.String()}) + case "thinking": + res.content = append(res.content, map[string]any{"type": "thinking", "thinking": b.text.String(), "signature": b.sig}) + case "redacted_thinking", "web_search_tool_result": + res.content = append(res.content, b.start) + case "server_tool_use", "tool_use": + input := map[string]any{} + json.Unmarshal([]byte(b.args.String()), &input) + if len(input) == 0 { + if in, ok := b.start["input"].(map[string]any); ok { + input = in + } + } + id, _ := b.start["id"].(string) + name, _ := b.start["name"].(string) + res.content = append(res.content, map[string]any{"type": b.start["type"], "id": id, "name": name, "input": input}) + if b.start["type"] == "tool_use" { + res.calls = append(res.calls, chatPageCall{id: id, name: name, input: input}) + } + } + } + return res +} + +func (t *chatTurn) addUsage(v any, start bool) { + u, _ := v.(map[string]any) + for i, k := range []string{"input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"} { + f, ok := u[k].(float64) + if !ok { + continue + } + if start || i < 3 && f == 0 { + // message_start's count; message_delta's input counts, when + // it gives them, are the same round's again + if start { + t.usage[i] += int(f) + } + continue + } + if i == 3 { + t.usage[i] += int(f) + } + } +} + +// chatSearchResult is a web_search_tool_result as the page shows it. +func chatSearchResult(cb map[string]any) map[string]any { + items := []map[string]any{} + switch c := cb["content"].(type) { + case []any: + for _, it := range c { + m, _ := it.(map[string]any) + if m["type"] != "web_search_result" { + continue + } + u, _ := m["url"].(string) + title, _ := m["title"].(string) + var site any + if pu, err := url.Parse(u); err == nil && pu.Host != "" { + site = strings.TrimPrefix(pu.Hostname(), "www.") + } + age, _ := m["page_age"].(string) + var pageAge any + if age != "" { + pageAge = age + } + items = append(items, map[string]any{"type": "web_search_result", "url": u, "title": title, + "snippet": nil, "site_name": site, "site_icon": nil, "encrypted_content": "", "page_age": pageAge}) + } + case map[string]any: + items = append(items, map[string]any{"type": "web_search_tool_result_error", "error_code": "unavailable"}) + } + return map[string]any{"type": "web_search_tool_result", "tool_use_id": cb["tool_use_id"], "kind": "search", "content": items} +} + +// read runs a read_url call: the page is shown the call and the page it +// read, and the model is given the page's text. +func (t *chatTurn) read(c chatPageCall) map[string]any { + result := func(text string, isErr bool) map[string]any { + return map[string]any{"type": "tool_result", "tool_use_id": c.id, "content": text, "is_error": isErr} + } + if c.name != chatReadTool { + return result("There is no tool named "+c.name+".", true) + } + raw, _ := c.input["url"].(string) + raw = strings.TrimSpace(raw) + t.block(map[string]any{"type": "server_tool_use", "id": c.id, "name": "deepseek_read_url", "kind": "read_link", + "input": map[string]any{"action": "read_link", "url": raw}}) + failed := func(why string) map[string]any { + t.block(map[string]any{"type": "web_fetch_tool_result", "tool_use_id": c.id, "kind": "read_link", + "content": map[string]any{"type": "web_fetch_tool_result_error", "error_code": "url_not_accessible"}}) + return result(why, true) + } + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return failed("read_url reads only http:// and https:// URLs, not " + raw) + } + release, refused := budget.Reserve(access.Caller(t.r.Context()), int64(len(raw)), "", limitClock()) + if refused != nil { + return failed(refused.Error()) + } + defer release() + ctx, cancel := context.WithTimeout(netproxy.With(t.r.Context(), ""), webFetchTimeout) + defer cancel() + title, text, final, err := fetchPage(ctx, u) + if err != nil { + return failed("couldn't read " + u.Redacted() + ": " + err.Error()) + } + if r := []rune(text); len(r) > chatReadChars { + text = string(r[:chatReadChars]) + } + var titled any + if title != "" { + titled = title + } + t.block(map[string]any{"type": "web_fetch_tool_result", "tool_use_id": c.id, "kind": "read_link", + "content": map[string]any{"type": "web_fetch_result", "url": final, "published_at": nil, + "content": map[string]any{"type": "document", "title": titled, + "source": map[string]any{"type": "text", "media_type": "text/plain", "data": ""}}}, + "signature": chatSign(fetchPart(final, title, text, 0, chatReadChars))}) + return result(fetchPart(final, title, text, 0, chatReadChars), false) +} + +// sseTap is the ResponseWriter a round is answered into: a stream's +// events are handed to on as each is written whole, anything else is +// kept to be read after. +type sseTap struct { + h http.Header + status int + sse bool + buf []byte + body bytes.Buffer + on func(name string, data []byte) bool + gone bool +} + +func (t *sseTap) Header() http.Header { return t.h } + +func (t *sseTap) WriteHeader(code int) { + if t.status == 0 { + t.status = code + t.sse = code == http.StatusOK && strings.HasPrefix(t.h.Get("Content-Type"), "text/event-stream") + } +} + +func (t *sseTap) Flush() {} + +func (t *sseTap) Write(p []byte) (int, error) { + t.WriteHeader(http.StatusOK) + if t.gone { + return 0, http.ErrHandlerTimeout + } + if !t.sse { + if t.body.Len() < 1<<20 { + t.body.Write(p) + } + return len(p), nil + } + t.buf = append(t.buf, p...) + for { + t.buf = bytes.ReplaceAll(t.buf, []byte("\r\n"), []byte("\n")) + end := bytes.Index(t.buf, []byte("\n\n")) + if end < 0 { + break + } + frame := t.buf[:end] + t.buf = t.buf[end+2:] + var name string + var data []byte + for line := range bytes.SplitSeq(frame, []byte("\n")) { + if v, ok := bytes.CutPrefix(line, []byte("event:")); ok { + name = string(bytes.TrimSpace(v)) + } else if v, ok := bytes.CutPrefix(line, []byte("data:")); ok { + if len(data) > 0 { + data = append(data, '\n') + } + data = append(data, bytes.TrimPrefix(v, []byte(" "))...) + } + } + if len(data) == 0 { + continue + } + if name == "" { + var ev struct { + Type string `json:"type"` + } + json.Unmarshal(data, &ev) + name = ev.Type + } + if !t.on(name, data) { + t.gone = true + return 0, http.ErrHandlerTimeout + } + } + return len(p), nil +} + +var _ = time.Second diff --git a/internal/gateway/chatpage_test.go b/internal/gateway/chatpage_test.go new file mode 100644 index 000000000..ebda85d06 --- /dev/null +++ b/internal/gateway/chatpage_test.go @@ -0,0 +1,397 @@ +package gateway + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// The page is DeepSeek's release, as published: its zip is the one +// whose sha256 the release has, its one API origin is magpie's own path, +// and magpie.js is loaded before its script. +func TestChatPageIsTheRelease(t *testing.T) { + sum := sha256.Sum256(chatDemoZip) + if hex.EncodeToString(sum[:]) != chatDemoSHA256 { + t.Fatal("the embedded chat-demo zip isn't v0.1.1's") + } + files, err := chatPageFiles() + if err != nil { + t.Fatal(err) + } + main := string(files[chatDemoMain]) + if strings.Contains(main, "api.deepseek.com") || strings.Count(main, chatOrigin) != 1 { + t.Fatal("the page still calls DeepSeek, or magpie's origin isn't in it once") + } + if _, ok := files["LICENSE"]; !ok { + t.Fatal("the release's MIT license isn't served with it") + } + index := string(files["index.html"]) + js, page := strings.Index(index, `src="magpie.js"`), strings.Index(index, `src="`+chatDemoMain+`"`) + if js < 0 || page < 0 || js > page { + t.Fatalf("magpie.js isn't loaded before the page's script: %s", index) + } +} + +// The page's files are the same bytes for everyone, so another computer +// opens them with no key while magpie is shared; every call they make, +// the model list included, needs one. The page can load nothing from +// elsewhere and can't be framed. +func TestChatPageOpensWithoutAKey(t *testing.T) { + h, _, secrets := keyPageGateway(t) + remote := "192.168.1.9:5000" + w := keyPageReq{method: "GET", path: ChatPagePath, from: remote}.do(h) + if w.Code != http.StatusFound || w.Header().Get("Location") != ChatPagePath+"/" { + t.Fatal("bare path", w.Code, w.Header()) + } + for _, p := range []string{"/", "/" + chatDemoMain, "/magpie.js", "/LICENSE"} { + w := keyPageReq{method: "GET", path: ChatPagePath + p, from: remote}.do(h) + if w.Code != 200 { + t.Fatalf("%s: %d %s", p, w.Code, w.Body.String()) + } + csp := w.Header().Get("Content-Security-Policy") + for _, want := range []string{"default-src 'self'", "script-src 'self'", "connect-src 'self'", "frame-ancestors 'none'"} { + if !strings.Contains(csp, want) { + t.Errorf("%s: CSP %q lacks %q", p, csp, want) + } + } + if w.Header().Get("X-Frame-Options") != "DENY" || w.Header().Get("X-Content-Type-Options") != "nosniff" { + t.Errorf("%s: %v", p, w.Header()) + } + } + for _, q := range []keyPageReq{ + {method: "GET", path: ChatPagePath + "/models"}, + {method: "GET", path: ChatPagePath + "/no-such-file"}, + {method: "GET", path: ChatPagePath + "/static/../index.html"}, + {method: "POST", path: ChatPagePath + "/anthropic/v1/messages"}, + {method: "POST", path: ChatPagePath + "/anthropic/v1/files"}, + {method: "DELETE", path: ChatPagePath + "/anthropic/v1/files/file_x"}, + {method: "POST", path: ChatPagePath + "/v1/tools/asr"}, + {method: "POST", path: ChatPagePath + "/v1/tools/tts"}, + {method: "POST", path: ChatPagePath + "/"}, + } { + q.from = remote + if w := q.do(h); w.Code != http.StatusUnauthorized { + t.Errorf("%s %s with no key: %d", q.method, q.path, w.Code) + } + } + // Alice's key may use plan/m1 alone: the picker lists that, and a + // model she may not use, picked before, isn't chatted with + w = keyPageReq{method: "GET", path: ChatPagePath + "/models", from: remote, header: map[string]string{"Authorization": "Bearer " + secrets[0]}}.do(h) + var list struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` + Default string `json:"default"` + } + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &list) != nil || len(list.Data) != 1 || list.Data[0].ID != "plan/m1" || list.Default != "plan/m1" { + t.Fatalf("Alice's models: %d %s", w.Code, w.Body.String()) + } + r := httptest.NewRequest("GET", ChatPagePath+"/models", nil) + r.AddCookie(&http.Cookie{Name: chatModelCookie, Value: "plan%2Fm2"}) + if got := chatModel(r); got != "plan/m1" && got != "plan/m2" { + t.Fatal("the picker's model", got) + } +} + +// A conversation the page sends back is what the model is asked: the +// page's DeepSeek identity isn't, its reminder of the day is a system +// line, a file it attached is the file, one magpie no longer has says +// so, and a page read before goes after the question it was read for, +// its text from the result's signature. +func TestChatPageConversation(t *testing.T) { + fresh(t) + r := httptest.NewRequest("POST", ChatPagePath+"/anthropic/v1/messages", nil) + chatFiles.Lock() + chatFiles.m["file_txt"] = &chatUpload{owner: chatOwner(r), name: "notes.md", mime: "text/plain", kind: "text", data: []byte("# Notes\nhello")} + chatFiles.m["file_bob"] = &chatUpload{owner: "someone else", name: "bob.txt", mime: "text/plain", kind: "text", data: []byte("Bob's")} + chatFiles.Unlock() + t.Cleanup(func() { + chatFiles.Lock() + delete(chatFiles.m, "file_txt") + delete(chatFiles.m, "file_bob") + chatFiles.Unlock() + }) + body := `{"model":"deepseek-flash","system":"` + chatDemoSystem + `", + "thinking":{"type":"enabled"},"title":{"enabled":true}, + "tools":[{"type":"deepseek_web_search","name":"deepseek_web_search"},{"type":"deepseek_read_url","name":"deepseek_read_url"}], + "messages":[ + {"role":"latest_reminder","content":"2026-11-14,Saturday,,Web,zh-CN"}, + {"role":"user","content":[{"type":"text","text":"Read https://go.dev for me\nplease"},{"type":"document","source":{"type":"file","file_id":"file_txt"}}]}, + {"role":"assistant","content":[ + {"type":"thinking","thinking":"hm","signature":""}, + {"type":"server_tool_use","id":"t1","name":"deepseek_read_url","kind":"read_link","input":{"action":"read_link","url":"https://go.dev"}}, + {"type":"web_fetch_tool_result","tool_use_id":"t1","kind":"read_link","content":{"type":"web_fetch_result","url":"https://go.dev/","content":{"type":"document","source":{"type":"text","media_type":"text/plain","data":""},"title":"Go"},"published_at":null},"signature":"` + chatSign("Go is a language.") + `"}, + {"type":"text","text":"Go is a language."}]}, + {"role":"user","content":[{"type":"text","text":"And Bob's?"},{"type":"document","source":{"type":"file","file_id":"file_bob"}}]}]}` + var in chatRequest + if err := json.Unmarshal([]byte(body), &in); err != nil { + t.Fatal(err) + } + out, title := chatUpstream(r, &in, "deep/deepseek-v4.1-flash") + if title != "Read https://go.dev for …" { + t.Fatalf("title %q", title) + } + sys, _ := out["system"].(string) + if strings.Contains(sys, "DeepSeek") || !strings.Contains(sys, "2026-11-14, Saturday") || !strings.Contains(sys, "zh-CN") || strings.Contains(sys, "The user is in") { + t.Fatalf("system %q", sys) + } + got, _ := json.Marshal(out["messages"]) + for _, want := range []string{ + `"text":"File notes.md`, // the attached file + `Content of https://go.dev/:\n\nGo is a language.`, // the page read before + `{"content":[{"text":"Go is a language.","type":"text"}],"role":"assistant"}`, // no unsigned thinking, no tool blocks + `no longer available`, // Bob's file isn't this caller's + } { + if !strings.Contains(string(got), want) { + t.Errorf("messages lack %s:\n%s", want, got) + } + } + if strings.Contains(string(got), "Bob's\"") || strings.Contains(string(got), "deepseek_read_url") { + t.Errorf("messages: %s", got) + } + tools, _ := json.Marshal(out["tools"]) + if !strings.Contains(string(tools), `"web_search_20250305"`) || !strings.Contains(string(tools), `"name":"read_url"`) || strings.Contains(string(tools), "deepseek") { + t.Errorf("tools %s", tools) + } + if out["stream"] != true { + t.Error("not streamed") + } +} + +// A question the page asks is answered by a magpie model that can't +// search: magpie searches for it (shown as DeepSeek's search, with the +// pages found), reads a link it asks for (shown as DeepSeek's link +// reading, the model given the page's text), and the answer comes in +// the same reply, titled, with every round's tokens. +func TestChatPageSearchesAndReadsLinks(t *testing.T) { + fresh(t) + search := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/models": + io.WriteString(w, `{"data":[{"id":"claude-haiku-4-5"}]}`) + case "/v1/messages": + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"s","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[ + {"type":"server_tool_use","id":"srv","name":"web_search","input":{"query":"go"}}, + {"type":"web_search_tool_result","tool_use_id":"srv","content":[ + {"type":"web_search_result","title":"Go downloads","url":"https://www.go.dev/dl/","encrypted_content":"EqoB","page_age":"1 day ago"}]}, + {"type":"text","text":"Go 1.27.1 is out."}], + "stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":5}}`) + default: + http.NotFound(w, r) + } + })) + defer search.Close() + site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + io.WriteString(w, `Release notes

Go 1.27.1 fixes the linker.

`) + })) + defer site.Close() + was := webFetchClient + webFetchClient = site.Client() + defer func() { webFetchClient = was }() + + var mu sync.Mutex + var asked []string + model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + asked = append(asked, string(b)) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + switch { + case strings.Contains(string(b), "fixes the linker"): + io.WriteString(w, sse(`data: {"id":"c","choices":[{"index":0,"delta":{"role":"assistant","content":"The linker is fixed."}}]}`, + `data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":40,"completion_tokens":4}}`, + `data: [DONE]`)) + case strings.Contains(string(b), "Go downloads"): + io.WriteString(w, sse(`data: {"id":"c","choices":[{"index":0,"delta":{"role":"assistant","content":"Reading it, from https://www.go.dev/dl/."}}]}`, + `data: {"id":"c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_2","type":"function","function":{"name":"read_url","arguments":"{\"url\":\"`+site.URL+`/notes\"}"}}]}}]}`, + `data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":30,"completion_tokens":3}}`, + `data: [DONE]`)) + default: + io.WriteString(w, sse(`data: {"id":"c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"web_search","arguments":"{\"query\":\"latest go\"}"}}]}}]}`, + `data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":2}}`, + `data: [DONE]`)) + } + })) + defer model.Close() + hosts := searchHosts[provider.Anthropic] + searchHosts[provider.Anthropic] = append(hosts, provider.HostOf(search.URL)) + defer func() { searchHosts[provider.Anthropic] = hosts }() + for _, p := range []provider.Provider{ + {ID: "srch", Name: "Search", Key: "k", Anthropic: search.URL}, + {ID: "deep", Name: "Deep", Key: "k", Chat: model.URL, Models: []string{"deepseek-v4.1-flash"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + p, _ := provider.Find("srch") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + + body := `{"model":"deepseek-flash","system":"` + chatDemoSystem + `","thinking":{"type":"disabled"},"title":{"enabled":true}, + "tools":[{"type":"deepseek_web_search","name":"deepseek_web_search"},{"type":"deepseek_read_url","name":"deepseek_read_url"}], + "messages":[{"role":"latest_reminder","content":"2026-11-14,Saturday,Beijing,Web,en-US"},{"role":"user","content":"What's new in Go?"}]}` + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", ChatPagePath+"/anthropic/v1/messages", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-api-key", "magpie-deepseek-chat") + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/event-stream") { + t.Fatalf("%d %v %s", rec.Code, rec.Header(), rec.Body.String()) + } + evs := events(rec.Body.String()) + var kinds []string + var text string + var delta map[string]any + var cited []string + indices := map[float64]bool{} + for _, ev := range evs { + switch ev["type"] { + case "content_block_start": + cb := ev["content_block"].(map[string]any) + i := ev["index"].(float64) + if indices[i] { + t.Fatalf("index %v twice: %s", i, rec.Body.String()) + } + indices[i] = true + k := cb["type"].(string) + if n, ok := cb["name"].(string); ok { + k += ":" + n + } + kinds = append(kinds, k) + switch cb["type"] { + case "server_tool_use": + in := cb["input"].(map[string]any) + if cb["name"] == "deepseek_web_search" && (cb["kind"] != "search" || in["action"] != "search" || in["queries"].([]any)[0] != "latest go") { + t.Errorf("search call %v", cb) + } + if cb["name"] == "deepseek_read_url" && (cb["kind"] != "read_link" || in["url"] != site.URL+"/notes") { + t.Errorf("read call %v", cb) + } + case "web_search_tool_result": + items := cb["content"].([]any) + it := items[0].(map[string]any) + if cb["kind"] != "search" || it["url"] != "https://www.go.dev/dl/" || it["site_name"] != "go.dev" || it["page_age"] != "1 day ago" { + t.Errorf("search result %v", cb) + } + case "web_fetch_tool_result": + c := cb["content"].(map[string]any) + doc := c["content"].(map[string]any) + sig, _ := cb["signature"].(string) + kept, _ := base64.StdEncoding.DecodeString(strings.TrimPrefix(sig, chatSigned)) + if cb["kind"] != "read_link" || c["type"] != "web_fetch_result" || doc["title"] != "Release notes" || !strings.Contains(string(kept), "fixes the linker") { + t.Errorf("read result %v", cb) + } + } + case "content_block_delta": + switch d := ev["delta"].(map[string]any); d["type"] { + case "text_delta": + text += d["text"].(string) + case "citations_delta": + c := d["citation"].(map[string]any) + cited = append(cited, c["type"].(string)+" "+c["url"].(string)) + } + case "message_delta": + delta = ev + } + } + want := []string{"server_tool_use:deepseek_web_search", "web_search_tool_result", "text", "server_tool_use:deepseek_read_url", "web_fetch_tool_result", "text"} + if !slices.Equal(kinds, want) { + t.Fatalf("blocks %v, want %v\n%s", kinds, want, rec.Body.String()) + } + // the page shows a line's sources from its citations, as Anthropic's + // search gives them + if !slices.Equal(cited, []string{"web_search_result_location https://www.go.dev/dl/"}) { + t.Errorf("citations %v\n%s", cited, rec.Body.String()) + } + if !strings.Contains(text, "Reading it, from https://www.go.dev/dl/.") || !strings.HasSuffix(text, "The linker is fixed.") { + t.Errorf("text %q", text) + } + d, _ := delta["delta"].(map[string]any) + u, _ := delta["usage"].(map[string]any) + if d["stop_reason"] != "end_turn" || d["title"] != "What's new in Go?" || u["output_tokens"].(float64) < 4+3 { + t.Errorf("message_delta %v", delta) + } + if evs[len(evs)-1]["type"] != "message_stop" { + t.Error("no message_stop") + } + mu.Lock() + defer mu.Unlock() + first := asked[0] + if strings.Contains(first, "DeepSeek") || strings.Contains(first, "深度求索") || !strings.Contains(first, "The user is in Beijing") || !strings.Contains(first, `"read_url"`) { + t.Errorf("the model was asked %s", first) + } +} + +// A file the page uploads is kept for its own caller, as what a model +// can take: an image, a PDF or text; anything else is refused with what +// to do instead, and the page's DELETE drops it. +func TestChatPageFiles(t *testing.T) { + fresh(t) + h := New().Handler() + upload := func(name string, data []byte) (int, map[string]any) { + var b bytes.Buffer + mw := multipart.NewWriter(&b) + mw.WriteField("purpose", "user_data") + fw, _ := mw.CreateFormFile("file", name) + fw.Write(data) + mw.Close() + r := httptest.NewRequest("POST", ChatPagePath+"/anthropic/v1/files", &b) + r.Header.Set("Content-Type", mw.FormDataContentType()) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + var out map[string]any + json.Unmarshal(w.Body.Bytes(), &out) + return w.Code, out + } + png := append([]byte("\x89PNG\r\n\x1a\n"), make([]byte, 32)...) + for _, c := range []struct { + name string + data []byte + mime string + }{ + {"a.png", png, "image/png"}, + {"a.pdf", []byte("%PDF-1.7\n..."), "application/pdf"}, + {"a.md", []byte("# 标题\ntext"), "text/plain"}, + } { + code, out := upload(c.name, c.data) + if code != 200 || out["type"] != "file" || out["mime_type"] != c.mime || out["filename"] != c.name || out["size_bytes"].(float64) != float64(len(c.data)) { + t.Fatalf("%s: %d %v", c.name, code, out) + } + id := out["id"].(string) + r := httptest.NewRequest("POST", "/", nil) + f := chatFileOf(r, id) + if f == nil { + t.Fatalf("%s isn't kept", c.name) + } + blk := chatFileBlock(f) + if c.mime == "image/png" && blk["type"] != "image" || c.mime == "application/pdf" && blk["type"] != "document" || c.mime == "text/plain" && blk["type"] != "text" { + t.Errorf("%s as %v", c.name, blk["type"]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest("DELETE", ChatPagePath+"/anthropic/v1/files/"+id, nil)) + if w.Code/100 != 2 || chatFileOf(r, id) != nil { + t.Errorf("%s not deleted: %d", c.name, w.Code) + } + } + if code, out := upload("a.docx", []byte("PK\x03\x04\x00\x00binary\x00")); code != http.StatusUnsupportedMediaType || !strings.Contains(out["error"].(map[string]any)["message"].(string), "PDF") { + t.Errorf("docx: %d %v", code, out) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 320e37c6e..a1f1866dd 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1087,6 +1087,16 @@ func (s *Server) routes() *routeMux { // another magpie looking for it at a new address (remote_prove.go) mux.HandleFunc("POST "+provider.RemoteProvePath, s.prove) mux.HandleFunc("GET "+KeyPagePath, s.keyPage) + // DeepSeek's chat page (deepseek-ai/chat-demo), served with any of + // magpie's models, its search and link reading magpie's (chatpage.go) + mux.HandleFunc("GET "+ChatPagePath, s.chatPage) + mux.HandleFunc("GET "+ChatPagePath+"/{path...}", s.chatPage) + mux.HandleFunc("GET "+ChatPagePath+"/models", s.chatPageModels) + mux.HandleFunc("POST "+ChatPagePath+"/anthropic/v1/messages", s.chatMessages) + mux.HandleFunc("POST "+ChatPagePath+"/anthropic/v1/files", s.chatFileUpload) + mux.HandleFunc("DELETE "+ChatPagePath+"/anthropic/v1/files/{id}", s.chatFileDelete) + mux.HandleFunc("POST "+ChatPagePath+"/v1/tools/asr", s.chatASR) + mux.HandleFunc("POST "+ChatPagePath+"/v1/tools/tts", s.chatTTS) mux.HandleFunc("GET "+CAPath, s.caFile) mux.HandleFunc("GET "+keyPageData, s.keyInfo) // the join page, where another computer that knows the join password diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 66e607143..a6a29ea71 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -620,7 +620,7 @@ func lanGuard(next http.Handler) http.Handler { // opened before the key it asks for is typed; its data isn't // magpie's CA, too: public, and fetched before the computer // asking trusts magpie's https:// (https.go) - if remote && (keyPageOpen(r) || caFileOpen(r)) { + if remote && (keyPageOpen(r) || caFileOpen(r) || chatPageOpen(r)) { next.ServeHTTP(w, r) return } diff --git a/internal/gateway/oneport.go b/internal/gateway/oneport.go index 24487b27e..796f0a6da 100644 --- a/internal/gateway/oneport.go +++ b/internal/gateway/oneport.go @@ -31,6 +31,8 @@ var clientPrefixes = []string{ // the key page (KeyPagePath): a key's holder opens it at the address // they give their agents KeyPagePath, + // DeepSeek's chat page (ChatPagePath), at the same address + ChatPagePath, // and the join page (JoinPagePath), at the same address JoinPagePath, // and magpie's CA (CAPath), which the other computer fetches from the diff --git a/internal/gateway/readonly.go b/internal/gateway/readonly.go index 47f4126b2..98f9022d0 100644 --- a/internal/gateway/readonly.go +++ b/internal/gateway/readonly.go @@ -42,7 +42,10 @@ var readOnlyRoutes = map[string]bool{ "GET " + routeEventsPath: true, "GET " + OwnMCPPath: true, "GET " + KeyPagePath: true, - "GET " + keyPageData: true, + // the chat page's own files, answered without a key (chatpage.go) + "GET " + ChatPagePath: true, + "GET " + ChatPagePath + "/{path...}": true, + "GET " + keyPageData: true, // the join carries a password, not a key (join.go) "GET " + JoinPagePath: true, "GET " + joinData: true, diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go index aa5880edc..6db73e9ec 100644 --- a/internal/gateway/readonly_test.go +++ b/internal/gateway/readonly_test.go @@ -27,6 +27,13 @@ var readOnlyRefused = []string{ "POST /api/show", "POST /api/chat", "POST /api/generate", // writes, another key's routes, the whole trace, debugging "POST /v1/magpie/usage/requests", "POST " + provider.RemoteRefreshPath, + // the chat page's models, its chat, files and speech + "GET " + ChatPagePath + "/models", + "POST " + ChatPagePath + "/anthropic/v1/messages", + "POST " + ChatPagePath + "/anthropic/v1/files", + "DELETE " + ChatPagePath + "/anthropic/v1/files/{id}", + "POST " + ChatPagePath + "/v1/tools/asr", + "POST " + ChatPagePath + "/v1/tools/tts", // a Codex reset, which can't be undone (#3850) "POST " + provider.RemoteCodexResetPath, // an update another magpie asks for