remote magpie: another computer makes videos with the video models a shared magpie has, as it draws with its image models (#545: 图像生成能否也提供给局域网中其他终端) — drawing from another computer already worked both ways, a plain client with the gateway's key at its /v1/images/generations and a magpie with it as a Remote magpie (since v0.1.555), but a Remote magpie's videos did not: its list never gave them, and /v1/videos turned away any provider but a Grok subscription. A magpie now asks its Remote magpie's list for them too (X-Magpie-Videomakers), the other lists them marked kind:video (a magpie that doesn't ask isn't given them, as it would take grok-imagine-video for an image model), and they are kept apart from the models to chat or draw with (catalog.Model.Films). A video with one is started at the other's /v1/videos, its id there carried, base64, in this magpie's video id, and asked after and fetched at its /v1/videos/{id} and /content. TestRemoteMagpieVideos fails without the change (no video models listed); TestLANDraws covers images from another computer both ways through lanGuard with a caller key. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui of gateway, provider, catalog and imagemcp pass.

This commit is contained in:
yetone
2026-10-02 17:32:08 +08:00
parent 6586c556db
commit 47741ee31f
7 changed files with 349 additions and 19 deletions
+4
View File
@@ -55,6 +55,10 @@ type Model struct {
// a relay's flux): kept with the list for Settings → Images, never
// offered to agents as a model to talk to.
Draws bool `json:",omitempty"`
// Films is set on a model another magpie lists as one it makes videos
// with (a Remote magpie's Grok Imagine Video): kept with the list for
// its videos API, never offered as a model to talk to or draw with.
Films bool `json:",omitempty"`
// Free is set on a model a subscription serves at no cost to its
// allowance: WorkBuddy's "credits": "x0.00".
Free bool `json:",omitempty"`
+24 -6
View File
@@ -70,11 +70,27 @@ func LiveDrawers(provider string) []Model {
return out
}
// Chat is ms without the models that draw.
// LiveVideomakers are the models in the provider's fetched list that make
// videos, in the list's order.
func LiveVideomakers(provider string) []Model {
f, err := readLive(provider)
if err != nil {
return nil
}
var out []Model
for _, m := range f.Models {
if m.Films {
out = append(out, m)
}
}
return out
}
// Chat is ms without the models that draw or make videos.
func Chat(ms []Model) []Model {
out := make([]Model, 0, len(ms))
for _, m := range ms {
if !m.Draws {
if !m.Draws && !m.Films {
out = append(out, m)
}
}
@@ -265,8 +281,9 @@ func fetchOne(ctx context.Context, url, key string, anthropic bool, headers map[
}
// a model that draws is kept, marked, for Settings → Images; any
// other that isn't for text (embeddings, speech) is left out
drawer := DrawsID(id) && !strings.Contains(strings.ToLower(id), "deep-research") || r.Kind == "image"
if !drawer && !textModel(mdModel{ID: id}) {
films := r.Kind == "video"
drawer := !films && (DrawsID(id) && !strings.Contains(strings.ToLower(id), "deep-research") || r.Kind == "image")
if !drawer && !films && !textModel(mdModel{ID: id}) {
continue
}
name := r.DisplayName
@@ -284,7 +301,7 @@ func fetchOne(ctx context.Context, url, key string, anthropic bool, headers map[
if len(apis) == 0 {
apis = targetAPIs(r.TypeTarget)
}
m := Model{ID: id, Name: name, ImageInput: input, APIs: apis, Draws: drawer}
m := Model{ID: id, Name: name, ImageInput: input, APIs: apis, Draws: drawer, Films: films}
if n, ok := r.ContextLength.(float64); ok && n > 0 {
m.Context = int(n)
}
@@ -350,7 +367,8 @@ type liveModel struct {
Output any `json:"max_output_tokens"`
Levels any `json:"supported_reasoning_levels"`
// another magpie's name for the model with its provider there after
// it, and "image" on one it draws with
// it, and "image" on one it draws with, "video" on one it makes videos
// with
Label string `json:"magpie_label"`
Kind string `json:"kind"`
// the protocol family PipeLLM routes the model by: openai, anthropic
+21
View File
@@ -525,6 +525,24 @@ func drawerObjects() []map[string]any {
return out
}
// videomakerObjects are the video models magpie makes videos with, as
// another magpie asks for them (provider.VideomakersHeader): "kind": "video".
func videomakerObjects() []map[string]any {
var out []map[string]any
for _, p := range provider.All() {
if !p.On() || p.Decides() {
continue
}
for _, m := range Videomakers(p) {
name := cmp.Or(m.Name, m.ID)
out = append(out, map[string]any{"id": p.ID + "/" + m.ID, "object": "model", "type": "model", "kind": "video", "created": 0,
"owned_by": p.ID, "display_name": name, "magpie_label": name + " · " + p.Name,
"modalities": map[string]any{"input": []string{"text", "image"}, "output": []string{"video"}}})
}
}
return out
}
// catalogFor is the catalog as the agent asking is shown it.
func catalogFor(r *http.Request) []provider.Entry {
shown, _ := provider.CatalogFor(agentOf(r))
@@ -551,6 +569,9 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(provider.DrawersHeader) != "" {
data = append(data, drawerObjects()...)
}
if r.Header.Get(provider.VideomakersHeader) != "" {
data = append(data, videomakerObjects()...)
}
out := map[string]any{"object": "list", "data": data, "has_more": false}
if len(data) > 0 {
out["first_id"], out["last_id"] = data[0]["id"], data[len(data)-1]["id"]
+145
View File
@@ -0,0 +1,145 @@
package gateway
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Another computer on the network draws with the magpie shared there
// (#545): a plain client with the gateway's key, at its images API, and a
// magpie that has it as a Remote magpie, whose image models it lists and
// draws with there. Neither gets an image only this computer can open.
func TestLANDraws(t *testing.T) {
_, e := easeled(t)
_, secrets := newCaller(t, "Laptop") // shares the gateway
h := lanGuard(New().Handler())
host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.RemoteAddr = "192.168.1.9:5000" // another computer
h.ServeHTTP(w, r)
}))
t.Cleanup(host.Close)
ask := func(path, key, body string) (int, imagesAnswer, string) {
req, _ := http.NewRequest("POST", host.URL+path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
var a imagesAnswer
var raw json.RawMessage
json.NewDecoder(res.Body).Decode(&raw)
json.Unmarshal(raw, &a)
return res.StatusCode, a, string(raw)
}
want := base64.StdEncoding.EncodeToString(pngBytes)
// a plain client: no key, turned away; with it, the image's bytes, by
// the model named or the one the Settings draw with
if code, _, body := ask("/v1/images/generations", "", `{"prompt":"a magpie"}`); code != 401 {
t.Errorf("no key: %d %s", code, body)
}
for _, body := range []string{`{"model":"art/gpt-image-1","prompt":"a magpie"}`, `{"prompt":"a magpie"}`} {
code, a, raw := ask("/v1/images/generations", secrets[0], body)
if code != 200 || len(a.Data) != 1 || a.Data[0].B64 != want || strings.Contains(raw, "127.0.0.1") || strings.Contains(raw, "localhost") {
t.Errorf("%s: %d %s", body, code, raw)
}
}
if code, a, raw := ask("/v1/images/edits", secrets[0], `{"model":"art/gpt-image-1","prompt":"a hat","image":"data:image/png;base64,`+want+`"}`); code != 200 || len(a.Data) != 1 {
t.Errorf("edit: %d %s", code, raw)
}
// a magpie with it as a Remote magpie, signed with the key
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Key: secrets[0], Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(host.URL, "http://")})
if err != nil {
t.Fatal(err)
}
office, _ := provider.Find(id)
if _, err := office.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
var draws []string
for _, m := range Drawers(*office) {
draws = append(draws, m.ID)
}
if !slices.Contains(draws, "art/gpt-image-1") {
t.Fatalf("the shared magpie's image models aren't listed here: %v", draws)
}
before := len(e.got("/v1/images/generations"))
code, body := post(t, "/v1/images/generations", `{"model":"office/art/gpt-image-1","prompt":"a magpie"}`)
var a imagesAnswer
json.Unmarshal([]byte(body), &a)
if code != 200 || len(a.Data) != 1 || a.Data[0].B64 != want || a.Model != "office/art/gpt-image-1" {
t.Errorf("through the remote magpie: %d %s", code, body)
}
if n := len(e.got("/v1/images/generations")); n != before+1 {
t.Errorf("the vendor was asked %d times", n-before)
}
}
// A magpie with another as its Remote magpie makes videos with the video
// models shared there (#545): they are listed as such, not as image models,
// and the video is started, asked after and fetched at the other magpie's
// videos API, under an id of this magpie's.
func TestRemoteMagpieVideos(t *testing.T) {
grokSignedIn(t)
g := newGrokMedia(t)
_, secrets := newCaller(t, "Laptop")
h := lanGuard(New().Handler())
host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.RemoteAddr = "192.168.1.9:5000"
h.ServeHTTP(w, r)
}))
t.Cleanup(host.Close)
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Key: secrets[0], Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(host.URL, "http://")})
if err != nil {
t.Fatal(err)
}
office, _ := provider.Find(id)
if _, err := office.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
var films, draws []string
for _, m := range Videomakers(*office) {
films = append(films, m.ID)
}
for _, m := range Drawers(*office) {
draws = append(draws, m.ID)
}
if !slices.Contains(films, "grok/grok-imagine-video") {
t.Fatalf("the shared magpie's video models aren't listed here: %v", films)
}
if slices.ContainsFunc(draws, func(id string) bool { return strings.Contains(id, "video") }) || !slices.Contains(draws, "grok/grok-imagine-image") {
t.Errorf("image models here: %v", draws)
}
s := New()
code, obj, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"office/grok/grok-imagine-video","prompt":"a magpie takes off","seconds":6,"size":"1280x720"}`)
vid, _ := obj["id"].(string)
if code != 200 || !strings.HasPrefix(vid, "video_office.") || obj["model"] != "office/grok/grok-imagine-video" {
t.Fatalf("start: %d %s", code, raw)
}
if b := g.body("/v1/videos/generations", 0); !strings.Contains(b, `"duration":6`) || !strings.Contains(b, `"resolution":"720p"`) {
t.Errorf("Grok was asked %s", b)
}
if code, obj, raw, _ := request(t, s, "GET", "/v1/videos/"+vid, "", ""); code != 200 || obj["id"] != vid || obj["status"] != "queued" {
t.Errorf("status: %d %s", code, raw)
}
if code, _, raw, _ := request(t, s, "GET", "/v1/videos/"+vid+"/content", "", ""); code != 409 {
t.Errorf("content before it is made: %d %s", code, raw)
}
if code, _, raw, hdr := request(t, s, "GET", "/v1/videos/"+vid+"/content", "", ""); code != 200 || string(raw) != "fake-mp4-bytes" || hdr.Get("Content-Type") != "video/mp4" {
t.Errorf("content: %d %s %v", code, raw, hdr)
}
}
+144 -12
View File
@@ -1,8 +1,10 @@
package gateway
import (
"cmp"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
@@ -35,6 +37,10 @@ import (
// backend Grok Build talks to: <cli-chat-proxy.grok.com/v1>/videos/generations
// starts one and answers with its request_id, and /videos/{request_id} is
// answered 202 while it is made and 200 with the video's URL when it is.
//
// Another magpie's videos (a Remote magpie's, #545) are asked of it, at its
// own videos API: its id for one goes, encoded, in the id given here, and
// what it answers comes back with this magpie's id and name for the model.
// grokVideoModels are the video models a Grok subscription makes videos with.
var grokVideoModels = []catalog.Model{
@@ -48,8 +54,16 @@ var grokVideoAspects = []string{"1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3
// maxVideoBytes is the most of a video the gateway passes on.
const maxVideoBytes = 512 << 20
// Videomakers are the models a provider can make videos with.
// Videomakers are the models a provider can make videos with: a Grok
// subscription's, and those another magpie listed as its own.
func Videomakers(p provider.Provider) []catalog.Model {
if p.IsRemoteMagpie() {
out := catalog.LiveVideomakers(p.ID)
for i := range out {
out[i].Provider = p.ID
}
return out
}
if !drawsGrok(p) {
return nil
}
@@ -379,7 +393,7 @@ func videoMaker(id string) (p provider.Provider, vendorID string, started time.T
return p, "", started, fmt.Errorf("%q isn't the id of a video magpie is making", id)
}
found, ferr := provider.Find(pid)
if ferr != nil || !drawsGrok(*found) {
if ferr != nil || !drawsGrok(*found) && !found.IsRemoteMagpie() {
return p, "", started, fmt.Errorf("no provider %q makes videos here", pid)
}
if signer(*found) != by {
@@ -388,6 +402,62 @@ func videoMaker(id string) (p provider.Provider, vendorID string, started time.T
return *found, vendorID, started, nil
}
// remoteVideoID is the id of a video another magpie (p) is making, by its
// id there: that has dots in it, so it goes in base64.
func remoteVideoID(p provider.Provider, theirs string, t time.Time) string {
return videoID(p, base64.RawURLEncoding.EncodeToString([]byte(theirs)), t)
}
// theirVideoID is the other magpie's id of a video, from remoteVideoID's.
func theirVideoID(vendorID string) string {
b, _ := base64.RawURLEncoding.DecodeString(vendorID)
return string(b)
}
// remoteVideoBody is f as another magpie's videos API takes it: OpenAI's,
// the images as data URLs.
func remoteVideoBody(model string, f filming) []byte {
req := map[string]any{"model": model, "prompt": f.Prompt}
if f.Seconds != "" {
req["seconds"] = f.Seconds
}
if f.Size != "" {
req["size"] = f.Size
}
if f.Start != nil {
req["input_reference"] = f.Start.dataURL()
}
var refs []string
for _, pic := range f.References {
refs = append(refs, pic.dataURL())
}
if len(refs) > 0 {
req["reference_images"] = refs
}
b, _ := json.Marshal(req)
return b
}
// asOurs is another magpie's video object with this magpie's id for it and
// name for its model.
func asOurs(b []byte, p provider.Provider, id string) (map[string]any, error) {
var obj map[string]any
if err := json.Unmarshal(b, &obj); err != nil || obj == nil {
return nil, fmt.Errorf("%s's answer isn't a video's: %v", p.Name, err)
}
obj["id"] = id
if m, _ := obj["model"].(string); m != "" {
obj["model"] = p.ID + "/" + m
}
return obj, nil
}
// remoteVideoURL is where another magpie answers for a video, with suffix
// ("" or "/content").
func remoteVideoURL(p provider.Provider, vendorID, suffix string) string {
return strings.TrimRight(p.Base(provider.Chat), "/") + "/videos/" + url.PathEscape(theirVideoID(vendorID)) + suffix
}
// videoStatus asks the vendor how a video is going.
func (s *Server) videoStatus(ctx context.Context, p provider.Provider, vendorID string) (videoState, int, error) {
var st videoState
@@ -438,26 +508,32 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
return
}
call.Provider, call.To = p.ID, provider.Chat
remote := p.IsRemoteMagpie()
// any grok-imagine-video*, not only those listed: the vendor's newer ones work before magpie names them
if len(Videomakers(p)) == 0 || !strings.HasPrefix(model, "grok-imagine-video") {
if !remote && (len(Videomakers(p)) == 0 || !strings.HasPrefix(model, "grok-imagine-video")) {
fail(400, fmt.Sprintf("%s/%s can't make videos: magpie makes videos with a Grok subscription's grok-imagine-video", p.ID, model))
return
}
body, err := grokVideoBody(model, f)
if err != nil {
// another magpie is asked at its videos API, which says itself what
// it can't make
at, field := strings.TrimRight(p.Base(provider.Responses), "/")+"/videos/generations", "request_id"
var body []byte
if remote {
at, field, body = strings.TrimRight(p.Base(provider.Chat), "/")+"/videos", "id", remoteVideoBody(model, f)
} else if body, err = grokVideoBody(model, f); err != nil {
fail(400, err.Error())
return
}
ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
defer cancel()
b, code, err := s.send(ctx, p, strings.TrimRight(p.Base(provider.Responses), "/")+"/videos/generations", "application/json", body, true)
b, code, err := s.send(ctx, p, at, "application/json", body, true)
call.Millis, call.Status = time.Since(start).Milliseconds(), code
var started struct {
ID string `json:"request_id"`
}
var started map[string]any
theirs := ""
if err == nil {
if json.Unmarshal(b, &started) != nil || started.ID == "" {
code, err = 502, fmt.Errorf("%s started no video: its answer had no request_id", p.Name)
json.Unmarshal(b, &started)
if theirs, _ = started[field].(string); theirs == "" {
code, err = 502, fmt.Errorf("%s started no video: its answer had no %s", p.Name, field)
call.Status = code
}
}
@@ -470,7 +546,12 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
return
}
s.record(call)
writeJSON(w, 200, videoObject(videoID(p, started.ID, start), p.ID+"/"+model, start, videoState{}, f))
if remote {
obj, _ := asOurs(b, p, remoteVideoID(p, theirs, start))
writeJSON(w, 200, obj)
return
}
writeJSON(w, 200, videoObject(videoID(p, theirs, start), p.ID+"/"+model, start, videoState{}, f))
}
// videosGet answers how a video is going.
@@ -483,6 +564,20 @@ func (s *Server) videosGet(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
defer cancel()
if p.IsRemoteMagpie() {
b, code, err := s.sendAs(ctx, p, http.MethodGet, remoteVideoURL(p, vendorID, ""), "", nil, true)
if err != nil {
writeError(w, provider.Chat, code, err.Error())
return
}
obj, err := asOurs(b, p, id)
if err != nil {
writeError(w, provider.Chat, 502, err.Error())
return
}
writeJSON(w, 200, obj)
return
}
st, code, err := s.videoStatus(ctx, p, vendorID)
if err != nil {
writeError(w, provider.Chat, code, err.Error())
@@ -505,6 +600,10 @@ func (s *Server) videosContent(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
defer cancel()
if p.IsRemoteMagpie() {
s.remoteVideoContent(ctx, w, p, vendorID)
return
}
st, code, err := s.videoStatus(ctx, p, vendorID)
if err != nil {
writeError(w, provider.Chat, code, err.Error())
@@ -545,3 +644,36 @@ func (s *Server) videosContent(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
io.Copy(w, io.LimitReader(res.Body, maxVideoBytes))
}
// remoteVideoContent passes on the bytes of a video another magpie made, or
// what it says of one it hasn't.
func (s *Server) remoteVideoContent(ctx context.Context, w http.ResponseWriter, p provider.Provider, vendorID string) {
ctx = p.Via(ctx)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, remoteVideoURL(p, vendorID, "/content"), nil)
if err != nil {
writeError(w, provider.Chat, 502, err.Error())
return
}
passOnCaller(ctx, req)
if err := p.Sign(ctx, req, provider.Chat, nil); err != nil {
writeError(w, provider.Chat, 502, err.Error())
return
}
res, err := p.Do(s.client, req)
if err != nil {
writeError(w, provider.Chat, 502, fmt.Sprintf("the video couldn't be fetched: %v", err))
return
}
defer res.Body.Close()
if res.StatusCode != 200 {
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
writeError(w, provider.Chat, res.StatusCode, p.Name+": "+vendorMessage(b))
return
}
w.Header().Set("Content-Type", cmp.Or(res.Header.Get("Content-Type"), "video/mp4"))
if res.ContentLength > 0 {
w.Header().Set("Content-Length", strconv.FormatInt(res.ContentLength, 10))
}
w.WriteHeader(200)
io.Copy(w, io.LimitReader(res.Body, maxVideoBytes))
}
+1
View File
@@ -435,6 +435,7 @@ func (p Provider) fixV1(base, at string) string {
func (p Provider) fetchPerKey(ctx context.Context, keys []KeyAccount) ([]catalog.Model, error) {
old, _, _ := catalog.Live(p.ID)
old = append(old, catalog.LiveDrawers(p.ID)...)
old = append(old, catalog.LiveVideomakers(p.ID)...)
var out []catalog.Model
at := map[string]int{}
add := func(m catalog.Model, id string) {
+10 -1
View File
@@ -25,9 +25,17 @@ import (
// there after it ("Claude Sonnet 5 · RelayA"), as its own agents see it:
// two of its providers' models of one name are told apart here too.
// Its video models come the same way (VideomakersHeader), marked "kind":
// "video", and go on to its videos API (#545).
// DrawersHeader asks a magpie's model list for its image models as well.
const DrawersHeader = "X-Magpie-Drawers"
// VideomakersHeader asks a magpie's model list for its video models as
// well: a magpie that doesn't send it would take grok-imagine-video, whose
// id says "imagine", for an image model.
const VideomakersHeader = "X-Magpie-Videomakers"
// RemoteMagpiePreset is the preset's id.
const RemoteMagpiePreset = "remote-magpie"
@@ -64,7 +72,7 @@ func (p *Provider) remoteMagpieEndpoints() {
}
// listHeaders are the headers p's model list is asked with: a remote
// magpie is asked for its image models too.
// magpie is asked for its image and video models too.
func (p Provider) listHeaders() map[string]string {
if !p.IsRemoteMagpie() {
return p.Headers
@@ -74,5 +82,6 @@ func (p Provider) listHeaders() map[string]string {
h = map[string]string{}
}
h[DrawersHeader] = "1"
h[VideomakersHeader] = "1"
return h
}