gateway: GET /v1/magpie/route tells a session's route as it happens (#405: a status bar wants the routed model and effort before the first token) — routing decides a group's member, and its decision model the effort, before the vendor is asked, but an agent's UI only learned it from the reply. A route now remembers the session its request named (X-Magpie-Session, or the agent's own session header; kept out of the trace's JSON and history), and GET /v1/magpie/route?session=<id> answers that session's latest route: the model asked, the group, the rule matched (with the effort picked), the member being tried and the effort it was sent at, every try with why a fallen-over one failed, then done/status/served. after=<seq>&wait=<s> (up to 60) waits for it to change. Only the named session is told; like /v1/magpie/quotas it answers this machine, and another only with the shared gateway's key. TestSessionRoute fails without the change (404). go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestUserPath and two Claude account tests flaked under load and pass alone).
This commit is contained in:
@@ -481,6 +481,23 @@ subscription with several: only it is tried, and an unknown account, one
|
||||
whose plan lacks the model, or one resting is an error rather than another
|
||||
account's reply. The header is not sent on to the vendor.
|
||||
|
||||
A status bar can show where a turn went before its first token arrives:
|
||||
send `X-Magpie-Session: <id>` with the requests (an agent's own session
|
||||
header, such as Pi's or Claude Code's, works too) and read
|
||||
`GET /v1/magpie/route?session=<id>`. It answers the session's latest
|
||||
request as routing has it so far — `asked` (the model the agent named),
|
||||
`group`, `rule` (the group's rule that matched, and `rule.pick`, the
|
||||
effort its decision model picked), `model` and `effort` (the member being
|
||||
tried now, as `provider/model`, and the reasoning it was sent at), and
|
||||
`tries`, one per member tried, each failed one a fallback with its `fail`
|
||||
— then `done`, `status` and `served` once the reply is over; `route` is
|
||||
`null` before the session has one. The route appears once routing has
|
||||
decided, before the vendor is asked. `after=<seq>&wait=<seconds>` (up to 60)
|
||||
holds the answer until the route changes past the `seq` of the last one,
|
||||
so a UI can follow a turn with one request at a time. Only the session
|
||||
named is told; like `/v1/magpie/quotas`, it answers this machine, and
|
||||
another only with the key of a gateway shared on the local network.
|
||||
|
||||
The *Gateway* tab in the app has this as copy buttons and ready-made
|
||||
snippets (shell, curl, Python, Node) for each API, the list of model ids,
|
||||
and the recent calls; `MAGPIE_DEBUG=1` logs every call to the terminal.
|
||||
|
||||
@@ -238,7 +238,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri
|
||||
}
|
||||
model := modelOf(body)
|
||||
seat := Weighed{ID: "codex", Provider: "openai", Name: "OpenAI", Icon: "openai", Who: who, Kind: "account", Agent: "codex", Model: model}
|
||||
tr = s.trace.begin(Route{Time: start, Agent: agentOf(r), Kind: callKind(r.Header), Model: model, Provider: "openai",
|
||||
tr = s.trace.begin(Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Kind: callKind(r.Header), Model: model, Provider: "openai",
|
||||
Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}})
|
||||
end = func(status int, msg string, tokens, out int) {
|
||||
ms := time.Since(start).Milliseconds()
|
||||
|
||||
@@ -365,6 +365,7 @@ func (s *Server) Handler() http.Handler {
|
||||
writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version})
|
||||
})
|
||||
mux.HandleFunc("GET /v1/magpie/quotas", s.quotas)
|
||||
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
|
||||
mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat))
|
||||
mux.HandleFunc("POST /chat/completions", s.handle(provider.Chat))
|
||||
mux.HandleFunc("POST /v1/responses", s.handle(provider.Responses))
|
||||
@@ -395,7 +396,7 @@ func (s *Server) Handler() http.Handler {
|
||||
|
||||
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), "window": Window,
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/magpie/quotas"}})
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/magpie/quotas", "/v1/magpie/route"}})
|
||||
}
|
||||
|
||||
// quotas is what is left of every subscription, plan and key magpie has,
|
||||
@@ -1044,7 +1045,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if len(cands) == 1 {
|
||||
shown = nil // nobody else to stay away from
|
||||
}
|
||||
tr := s.trace.begin(Route{Pinned: pin, Time: start, Agent: call.Agent, Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, Affinity: shown, Order: pl.order, Left: pl.left})
|
||||
tr := s.trace.begin(Route{Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, Affinity: shown, Order: pl.order, Left: pl.left})
|
||||
var skipped []string
|
||||
sent := "" // the reasoning the last try's model was asked for
|
||||
where := "" // the last try's provider.Where, for the usage
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package gateway
|
||||
|
||||
// GET /v1/magpie/route: where a session's turn went, for an agent's UI to
|
||||
// show while the reply is still on its way (#405). Routing decides the
|
||||
// member, and a group's decision model the effort, before the vendor is
|
||||
// asked; each fallback is in the trace as it happens. This tells one
|
||||
// session's latest route from the trace, nothing the trace doesn't hold.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// routeWaitMax caps how long one ask waits for the route to change.
|
||||
const routeWaitMax = 60 * time.Second
|
||||
|
||||
// SessionRoute is a session's latest request as routing has it so far.
|
||||
type SessionRoute struct {
|
||||
ID int64 `json:"id"`
|
||||
Time time.Time `json:"time"`
|
||||
Kind string `json:"kind,omitempty"` // a side call's: a title, a subagent…
|
||||
Asked string `json:"asked"` // the model as the agent asked
|
||||
AskedEffort string `json:"asked_effort,omitempty"` // the reasoning it asked for
|
||||
Group string `json:"group,omitempty"` // the routing group's id, when it asked one
|
||||
Rule *RuleHit `json:"rule,omitempty"` // the group's rules, as the Routing page has them
|
||||
Nested []NestedRule `json:"nested,omitempty"`
|
||||
// Model and Effort: the try under way, or the last, as provider/model
|
||||
// and the reasoning it was sent at
|
||||
Model string `json:"model,omitempty"`
|
||||
Effort string `json:"effort,omitempty"`
|
||||
Served string `json:"served,omitempty"` // the model the reply says answered
|
||||
Tries []RouteTry `json:"tries"`
|
||||
Done bool `json:"done"`
|
||||
Status int `json:"status,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Millis int64 `json:"ms,omitempty"`
|
||||
TTFT int64 `json:"ttft_ms,omitempty"`
|
||||
}
|
||||
|
||||
// RouteTry is one member trying the request: each failed one was fallen
|
||||
// over from.
|
||||
type RouteTry struct {
|
||||
Model string `json:"model"` // provider/model
|
||||
Effort string `json:"effort,omitempty"`
|
||||
Done bool `json:"done"`
|
||||
Status int `json:"status,omitempty"`
|
||||
Fail string `json:"fail,omitempty"` // why it failed, as the trace tells it
|
||||
Millis int64 `json:"ms,omitempty"`
|
||||
}
|
||||
|
||||
func sessionRouteOf(r Route) SessionRoute {
|
||||
out := SessionRoute{ID: r.ID, Time: r.Time, Kind: r.Kind, Asked: r.Model, AskedEffort: r.Effort, Rule: r.Rule, Nested: r.Nested,
|
||||
Served: r.Served, Tries: []RouteTry{}, Done: r.Done, Status: r.Status, Error: r.Error, Millis: r.Millis, TTFT: r.TTFT}
|
||||
if r.Group != nil {
|
||||
out.Group = r.Group.ID
|
||||
}
|
||||
// a try names its seat, whose provider is in the order weighed
|
||||
providerOf := func(id string) string {
|
||||
for _, ws := range [][]Weighed{r.Order, r.Left} {
|
||||
for _, w := range ws {
|
||||
if w.ID == id {
|
||||
return w.Provider
|
||||
}
|
||||
}
|
||||
}
|
||||
return r.Provider
|
||||
}
|
||||
for _, t := range r.Tries {
|
||||
model := t.Model
|
||||
if p := providerOf(t.ID); p != "" && model != "" {
|
||||
model = p + "/" + model
|
||||
}
|
||||
out.Tries = append(out.Tries, RouteTry{Model: model, Effort: t.Effort, Done: t.Done, Status: t.Status, Fail: t.Fail, Millis: t.Millis})
|
||||
}
|
||||
if n := len(out.Tries); n > 0 {
|
||||
out.Model, out.Effort = out.Tries[n-1].Model, out.Tries[n-1].Effort
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sessionRoute answers GET /v1/magpie/route?session=<id>, or with the
|
||||
// session in X-Magpie-Session (or the agent's own session header): the
|
||||
// session's latest route, null before it has one. With after=<seq> and
|
||||
// wait=<seconds> it waits, up to a minute, for the route to change past
|
||||
// seq. Like the quotas, it answers this machine, and another only with the
|
||||
// shared gateway's key.
|
||||
func (s *Server) sessionRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's routes are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
session := strings.TrimSpace(q.Get("session"))
|
||||
if len(session) > 128 {
|
||||
session = session[:128] // as sessionOf keeps it
|
||||
}
|
||||
if session == "" {
|
||||
session = sessionOf(r.Header)
|
||||
}
|
||||
if session == "" {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, "name the session: ?session=<id> or the "+SessionHeader+" header")
|
||||
return
|
||||
}
|
||||
after, _ := strconv.ParseInt(q.Get("after"), 10, 64)
|
||||
secs, _ := strconv.ParseFloat(q.Get("wait"), 64)
|
||||
wait := min(time.Duration(secs*float64(time.Second)), routeWaitMax)
|
||||
seq, route := s.trace.sessionLatest(r.Context(), session, after, wait)
|
||||
out := map[string]any{"session": session, "seq": seq, "route": nil}
|
||||
if route != nil {
|
||||
out["route"] = sessionRouteOf(*route)
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// sessionLatest is a copy of session's latest route, and its seq; with
|
||||
// wait, it waits up to that long for it to change past after.
|
||||
func (t *trace) sessionLatest(ctx context.Context, session string, after int64, wait time.Duration) (int64, *Route) {
|
||||
deadline := time.NewTimer(max(wait, 0))
|
||||
defer deadline.Stop()
|
||||
for {
|
||||
t.mu.Lock()
|
||||
var seq int64
|
||||
var found *Route
|
||||
for i := len(t.routes) - 1; i >= 0; i-- {
|
||||
if r := t.routes[i]; r.Session == session {
|
||||
c := *r
|
||||
c.Order = append([]Weighed(nil), r.Order...)
|
||||
c.Left = append([]Weighed(nil), r.Left...)
|
||||
c.Tries = append([]Try{}, r.Tries...)
|
||||
seq, found = r.Seq, &c
|
||||
break
|
||||
}
|
||||
}
|
||||
// after past the trace's count: the gateway started over since
|
||||
if wait <= 0 || seq > after || t.seq < after {
|
||||
t.mu.Unlock()
|
||||
return seq, found
|
||||
}
|
||||
if t.wake == nil {
|
||||
t.wake = make(chan struct{})
|
||||
}
|
||||
wake := t.wake
|
||||
t.mu.Unlock()
|
||||
select {
|
||||
case <-wake:
|
||||
case <-deadline.C:
|
||||
return seq, found
|
||||
case <-ctx.Done():
|
||||
return seq, found
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// GET /v1/magpie/route tells an agent's UI where its session's turn went
|
||||
// while it is under way (#405): the member routing put first, the effort it
|
||||
// was sent at, and each fallback as it happens — before the reply's first
|
||||
// token, not after. Only the session asked for is told, and only to this
|
||||
// machine or one with the shared gateway's key.
|
||||
func TestSessionRoute(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
limited := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, `{"error":{"message":"rate limited"}}`)
|
||||
}))
|
||||
t.Cleanup(limited.Close)
|
||||
asked, release := make(chan struct{}, 1), make(chan struct{})
|
||||
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked <- struct{}{}
|
||||
<-release
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"ok","model":"m","choices":[{"message":{"role":"assistant","content":"hi"}}]}`)
|
||||
}))
|
||||
t.Cleanup(slow.Close)
|
||||
var once sync.Once
|
||||
let := func() { once.Do(func() { close(release) }) }
|
||||
t.Cleanup(let) // before slow.Close, cleanups running last first
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "ra", Name: "RA", Key: "k", Models: []string{"m"}, Chat: limited.URL + "/v1"},
|
||||
{ID: "rb", Name: "RB", Key: "k", Models: []string{"m"}, Chat: slow.URL + "/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{Name: "R", Members: []string{"ra/m", "rb/m"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
h := lanGuard(s.Handler())
|
||||
get := func(from, target string, hdr ...string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest("GET", target, nil)
|
||||
r.RemoteAddr = from
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
var out map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &out)
|
||||
return w.Code, out
|
||||
}
|
||||
const here = "127.0.0.1:5000"
|
||||
|
||||
done := make(chan int, 1)
|
||||
go func() {
|
||||
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"group/r","reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`))
|
||||
r.RemoteAddr = here
|
||||
r.Header.Set(SessionHeader, "pi-1")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
done <- w.Code
|
||||
}()
|
||||
select {
|
||||
case <-asked:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the second member was never asked")
|
||||
}
|
||||
|
||||
// under way: the first member failed over to the second, which has
|
||||
// not answered yet
|
||||
code, out := get(here, "/v1/magpie/route", SessionHeader, "pi-1")
|
||||
if code != 200 || out["session"] != "pi-1" {
|
||||
t.Fatalf("in flight: %d %v", code, out)
|
||||
}
|
||||
rt, _ := out["route"].(map[string]any)
|
||||
if rt == nil || rt["done"] != false || rt["asked"] != "group/r" || rt["group"] != "r" || rt["model"] != "rb/m" || rt["effort"] != "high" {
|
||||
t.Fatalf("in flight route: %v", out)
|
||||
}
|
||||
tries, _ := rt["tries"].([]any)
|
||||
if len(tries) != 2 {
|
||||
t.Fatalf("tries: %v", rt["tries"])
|
||||
}
|
||||
first, second := tries[0].(map[string]any), tries[1].(map[string]any)
|
||||
if first["model"] != "ra/m" || first["status"] != float64(429) || first["fail"] == nil || second["model"] != "rb/m" || second["done"] != false {
|
||||
t.Fatalf("tries: %v", tries)
|
||||
}
|
||||
seq := int64(out["seq"].(float64))
|
||||
|
||||
// a long poll hears the turn end
|
||||
polled := make(chan map[string]any, 1)
|
||||
go func() {
|
||||
_, o := get(here, "/v1/magpie/route?session=pi-1&wait=5&after="+strconv.FormatInt(seq, 10))
|
||||
polled <- o
|
||||
}()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
let()
|
||||
if c := <-done; c != 200 {
|
||||
t.Fatal("the turn got", c)
|
||||
}
|
||||
o := <-polled
|
||||
if rt, _ := o["route"].(map[string]any); rt == nil || rt["done"] != true || rt["status"] != float64(200) || rt["model"] != "rb/m" {
|
||||
t.Fatalf("polled: %v", o)
|
||||
}
|
||||
|
||||
// another session hears nothing of this one
|
||||
if code, out := get(here, "/v1/magpie/route?session=other"); code != 200 || out["route"] != nil {
|
||||
t.Fatalf("other session: %d %v", code, out)
|
||||
}
|
||||
if code, _ := get(here, "/v1/magpie/route"); code != http.StatusBadRequest {
|
||||
t.Fatal("no session got", code)
|
||||
}
|
||||
// another machine needs the shared gateway's key, as the quotas do
|
||||
key, none := "sk-magpie-k", ""
|
||||
t.Cleanup(func() { lanKey.Store(&none) })
|
||||
lanKey.Store(&key)
|
||||
if code, _ := get("192.168.1.9:5000", "/v1/magpie/route?session=pi-1"); code != http.StatusUnauthorized {
|
||||
t.Fatal("no key got", code)
|
||||
}
|
||||
if code, out := get("192.168.1.9:5000", "/v1/magpie/route?session=pi-1", "Authorization", "Bearer "+key); code != 200 || out["route"] == nil {
|
||||
t.Fatalf("with the key: %d %v", code, out)
|
||||
}
|
||||
lanKey.Store(&none)
|
||||
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3425")
|
||||
if code, _ := get("192.168.1.9:5000", "/v1/magpie/route?session=pi-1"); code != http.StatusForbidden {
|
||||
t.Fatal("MAGPIE_ADDR, not shared, got", code)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ type Route struct {
|
||||
ID int64 `json:"id"`
|
||||
Time time.Time `json:"time"`
|
||||
Agent string `json:"agent"`
|
||||
Session string `json:"-"` // the session it named (sessionOf), for GET /v1/magpie/route alone
|
||||
Kind string `json:"kind,omitempty"` // what the call is for, as Call's
|
||||
For *CallFor `json:"for,omitempty"` // the request it was made for, as Call's
|
||||
Model string `json:"model"` // as the agent asked
|
||||
|
||||
Reference in New Issue
Block a user