gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway, which had no /api/usage counterpart, and asked for subagents' parent ids. - GET /v1/magpie/usage (the /api/usage summary, ?period=) and GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same filters, offset/limit) on the gateway. The builders moved out of gui into internal/usageapi so both serve the same JSON; gui keeps aliases and sets usageapi.Clients for agent names (gateway can't import agent). Guard as /v1/magpie/quotas: this machine, or another with an enabled gateway key, behind the same Host check. A key held to a budget, models or accounts is refused the summary (403) and gets the ledger filtered to its own CallerKey, with callerKeys/agents/providers/accounts cut to its own rows (usageapi.OwnPage): those facets are drawn from every call in the period. `path` is left out for another machine. - usage.Record gains subagent and parent_agent; session stays the parent conversation. Gateway rows take them from x-claude-code-agent-id and x-claude-code-parent-agent-id; session-file rows from the file name (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both packed into the request page's text columns (now 29, msg at 29). Codex sub-threads: only kind, as before; no spawned thread on disk to take a parent shape from. Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a local fake Anthropic endpoint that made it spawn a subagent from a subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96 and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one the agent id only, Session-Id the parent's throughout; the nested meta.json had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red with OwnPage, the CallerKey pin, or the header read removed (each tried). gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; set -o pipefail; go test ./... green.
This commit is contained in:
+5
-2
@@ -66,8 +66,11 @@ line.
|
||||
and `GET /v1/magpie/route?session=<id>` says which model a routing group
|
||||
picked for the turn and the fallbacks it tried, before the first token
|
||||
(long-poll with `after=<seq>&wait=<s>`). `GET /v1/magpie/quotas` lists the
|
||||
user's subscription allowances. Both answer only this machine, or another
|
||||
with a gateway key. [Connecting anything else](reference.md#connecting-anything-else)
|
||||
user's subscription allowances, and `GET /v1/magpie/usage` and
|
||||
`/v1/magpie/usage/requests` the Usage page's numbers and its requests
|
||||
(with `session`, and `subagent`/`parent_agent` for a Claude Code
|
||||
subagent's call). They answer only this machine, or another with a gateway
|
||||
key; a key held to a budget, models or accounts sees its own calls alone. [Connecting anything else](reference.md#connecting-anything-else)
|
||||
has the details.
|
||||
|
||||
**Keep the user's providers.** Add magpie as one more provider (named
|
||||
|
||||
@@ -1369,6 +1369,28 @@ subscription account, plan and key that answered a request through the
|
||||
gateway in the last 30 days, and `last: true` on the latest. It is kept
|
||||
in `served.json` beside `providers.json`, so a restart keeps it.
|
||||
|
||||
An app of your own can read the Usage page's numbers too.
|
||||
`GET /v1/magpie/usage?period=<today|week|month|all>` is the page's summary,
|
||||
the same JSON as the window's `/api/usage` (`path` is left out for another
|
||||
machine). `GET /v1/magpie/usage/requests` is its requests a page at a time
|
||||
(`offset`, `limit` up to 500), with the same filters as the Requests log:
|
||||
`period`, `day`, `agent`, `provider`, `model`, `account`, `callerKey`,
|
||||
`purpose`, `failed`, `q`, `via`, `computer`. What was said in a call is not
|
||||
in either. Like `/v1/magpie/quotas`, they answer this machine, and another
|
||||
only with a gateway key. A key held to a budget, to some models or to some
|
||||
accounts is told its own calls alone: `/v1/magpie/usage` refuses it with a
|
||||
403, and `/v1/magpie/usage/requests` keeps only its rows and filter lists.
|
||||
|
||||
A row's `session` is the conversation it belongs to. A Claude Code
|
||||
subagent's call keeps its parent conversation there and adds `subagent`,
|
||||
its agent id (the `agentId` of its lines and its
|
||||
`<session>/subagents/agent-<id>.jsonl` file), and `parent_agent`: the
|
||||
subagent that started it (Claude Code's `x-claude-code-parent-agent-id`, or
|
||||
the `parentAgentId` of the subagent's `.meta.json`); none when the main
|
||||
conversation did.
|
||||
Records written before these fields came have neither. Codex's sub-agents are told
|
||||
apart by `kind` only.
|
||||
|
||||
`magpie quota wait <provider|account>` blocks until that subscription (any
|
||||
of its accounts magpie has on) or that one account has allowance again — no
|
||||
window that stops it used up — then exits 0, so a long task stopped by its
|
||||
|
||||
@@ -136,3 +136,34 @@ and `TestGatewayConversationClientRequestPrefixedSession` for the two rules abov
|
||||
`TestGatewayRestoreRefusesForeignItems`; browser
|
||||
`gateway-conversations.test.cjs`, `sessions-talk.test.cjs`,
|
||||
`sessions-gateway-delete.test.cjs`, and locale checks.
|
||||
|
||||
## Usage over the gateway, and subagents
|
||||
|
||||
`GET /v1/magpie/usage` and `GET /v1/magpie/usage/requests`
|
||||
([`internal/gateway/usage_api.go`](../../internal/gateway/usage_api.go)) serve
|
||||
the Usage page's summary and request ledger from the same builders as the
|
||||
window's `/api/usage` and `/api/usage/requests`
|
||||
([`internal/usageapi`](../../internal/usageapi/usageapi.go)), read-only and
|
||||
without conversation text. They follow `/v1/magpie/quotas`' guard: this
|
||||
machine, or another with an enabled gateway key, behind the same Host check.
|
||||
A key that is held (`heldKey`: a budget, models or accounts) is refused the
|
||||
summary and gets the ledger filtered to its own `CallerKey`, with its filter
|
||||
lists cut to its own rows (`usageapi.OwnPage`): the ledger's facets are drawn
|
||||
from every call in the period, so without the cut they would name other keys.
|
||||
`TestUsageOverGateway` covers both, and a red when either cut is removed.
|
||||
|
||||
A usage record's `Session` stays the conversation. A Claude Code subagent's
|
||||
record adds `Subagent` and `ParentAgent`. Through the gateway they come from
|
||||
the `x-claude-code-agent-id` and `x-claude-code-parent-agent-id` headers
|
||||
Claude Code sends for a subagent's requests (`subagentOf`, read in
|
||||
`appendUsage`); the main thread sends neither. A row read from the agent's own
|
||||
files gets `Subagent` from the file's name, `<session>/subagents/agent-<id>.jsonl`
|
||||
or `<session>/subagents/workflows/<run>/agent-<id>.jsonl`
|
||||
(`sessions.SubagentOf`), so no cache version changes, and `ParentAgent` from
|
||||
the `parentAgentId` of the `agent-<id>.meta.json` beside it, which Claude Code
|
||||
writes for a subagent a subagent started (`sessions.SubagentParent`, read once
|
||||
a file; a meta file not read is unknown and read again). A gateway row matched
|
||||
to a file row keeps the gateway's own. Both were checked against Claude Code
|
||||
2.1.296 spawning a subagent from a subagent.
|
||||
Codex sub-agents are told apart by `Kind` (`x-openai-subagent`) only: no
|
||||
spawned Codex thread was found on disk to take a parent's shape from.
|
||||
|
||||
@@ -495,6 +495,8 @@ 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/usage", s.usageSummary)
|
||||
mux.HandleFunc("GET /v1/magpie/usage/requests", s.usageRequests)
|
||||
mux.HandleFunc("GET /v1/magpie/quotas/history", s.quotasHistory)
|
||||
mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards)
|
||||
mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh)
|
||||
@@ -556,7 +558,7 @@ func responsesOverHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
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/embeddings", "/v1/rerank", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/route"}})
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route"}})
|
||||
}
|
||||
|
||||
// quotas is what is left of every subscription, plan and key magpie has,
|
||||
@@ -4901,6 +4903,20 @@ func sessionOf(in http.Header) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// subagentOf is the subagent a request is of, and the subagent that
|
||||
// spawned that one, as Claude Code names them to a gateway
|
||||
// (x-claude-code-agent-id, x-claude-code-parent-agent-id; neither is sent
|
||||
// for the conversation's own turns). Its session header stays the
|
||||
// conversation's, so the call is told apart within it, not from it.
|
||||
func subagentOf(in http.Header) (agent, parent string) {
|
||||
agent = strings.TrimSpace(in.Get("x-claude-code-agent-id"))
|
||||
if agent == "" {
|
||||
return "", ""
|
||||
}
|
||||
parent = strings.TrimSpace(in.Get("x-claude-code-parent-agent-id"))
|
||||
return agent[:min(len(agent), 128)], parent[:min(len(parent), 128)]
|
||||
}
|
||||
|
||||
// nativeSessionOf keeps the client session even when magpie's header overrides it.
|
||||
func nativeSessionOf(in http.Header) string {
|
||||
for _, h := range sessionHeaders {
|
||||
|
||||
@@ -376,6 +376,9 @@ func appendUsage(r *http.Request, rec usage.Record) {
|
||||
if rec.Session == "" {
|
||||
rec.Session = sessionOf(r.Header)
|
||||
}
|
||||
if rec.Subagent == "" {
|
||||
rec.Subagent, rec.ParentAgent = subagentOf(r.Header)
|
||||
}
|
||||
who := access.Caller(r.Context())
|
||||
rec.CallerKeyID, rec.CallerKeyName = who.KeyID, who.KeyName
|
||||
rec.Local = local(r)
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usageapi"
|
||||
)
|
||||
|
||||
// The usage log, as the Usage page reads it (HoGee_xxl on X: an app of
|
||||
// their own reading magpie's usage over its gateway, as they can't over
|
||||
// the GUI's /api/usage): GET /v1/magpie/usage is the page's summary of a
|
||||
// ?period=, the same JSON as /api/usage, and GET /v1/magpie/usage/requests
|
||||
// its requests a page at a time, with /api/usage/requests' filters. Both
|
||||
// are read-only, and what was said in a call is not told here.
|
||||
//
|
||||
// They name accounts, keys and sessions, so, as /v1/magpie/quotas, they
|
||||
// answer this machine, and another only with an enabled gateway key while
|
||||
// magpie is shared. A key held to a budget, to some models or to some
|
||||
// accounts is someone else's to use: it is told its own calls alone, from
|
||||
// /v1/magpie/usage/requests, and not the summary of everyone's.
|
||||
|
||||
const usageRefused = "magpie's usage is 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>)"
|
||||
|
||||
// heldKey: the request's gateway key is held to a budget, models or
|
||||
// accounts, and so sees only its own usage.
|
||||
func heldKey(who access.Identity) bool {
|
||||
return who.KeyID != "" && (who.Limit.Limited() || len(who.Models) > 0 || len(who.Accounts) > 0)
|
||||
}
|
||||
|
||||
func (s *Server) usageSummary(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, usageRefused)
|
||||
return
|
||||
}
|
||||
if heldKey(access.Caller(r.Context())) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "this gateway key is held to a budget, models or accounts, so it is told its own calls alone: GET /v1/magpie/usage/requests")
|
||||
return
|
||||
}
|
||||
out := usageapi.State(usageapi.PeriodOf(r.URL.Query().Get("period")))
|
||||
if !local(r) {
|
||||
out.Path = "" // where the log is on this machine
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
func (s *Server) usageRequests(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, usageRefused)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
offset, _ := strconv.Atoi(q.Get("offset"))
|
||||
limit, _ := strconv.Atoi(q.Get("limit"))
|
||||
f := usageapi.FilterOf(q)
|
||||
who := access.Caller(r.Context())
|
||||
if !heldKey(who) {
|
||||
writeJSON(w, 200, usageapi.LedgerPage(usageapi.PeriodOf(q.Get("period")), f, offset, limit))
|
||||
return
|
||||
}
|
||||
f.CallerKey = who.KeyID
|
||||
writeJSON(w, 200, usageapi.OwnPage(usageapi.LedgerPage(usageapi.PeriodOf(q.Get("period")), f, offset, limit), who.KeyID))
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usageapi"
|
||||
)
|
||||
|
||||
// The Usage page's numbers are read over the gateway too (HoGee_xxl on
|
||||
// X): /v1/magpie/usage and /v1/magpie/usage/requests answer this machine,
|
||||
// another one only with a gateway key, and a key held to a budget only
|
||||
// with its own calls. A Claude Code subagent's call says which subagent
|
||||
// made it and which one started that.
|
||||
func TestUsageOverGateway(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":5}}`)
|
||||
}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, secrets := newCaller(t, "Laptop", "Held")
|
||||
if _, err := access.Update("limit-key", access.Change{Key: keys[1].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := lanGuard(New().Handler())
|
||||
do := func(method, path, from string, body io.Reader, hdr ...string) (int, string) {
|
||||
r := httptest.NewRequest(method, path, body)
|
||||
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)
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
// the main conversation, then a subagent of it that another started, as
|
||||
// Claude Code 2.1.296 sends a nested one (captured headers)
|
||||
if c, b := do("POST", "/v1/chat/completions", "127.0.0.1:5000", strings.NewReader(chatReq), "Authorization", "Bearer "+secrets[0], "X-Claude-Code-Session-Id", "conv-1"); c != 200 {
|
||||
t.Fatal(c, b)
|
||||
}
|
||||
if c, b := do("POST", "/v1/chat/completions", "127.0.0.1:5000", strings.NewReader(chatReq), "Authorization", "Bearer "+secrets[0], "X-Claude-Code-Session-Id", "conv-1",
|
||||
"X-Claude-Code-Agent-Id", "a143287ac46b82a96", "X-Claude-Code-Parent-Agent-Id", "a99ca20c03d1813d8"); c != 200 {
|
||||
t.Fatal(c, b)
|
||||
}
|
||||
if c, b := do("POST", "/v1/chat/completions", "127.0.0.1:5000", strings.NewReader(chatReq), "Authorization", "Bearer "+secrets[1]); c != 200 {
|
||||
t.Fatal(c, b)
|
||||
}
|
||||
|
||||
var sum usageapi.Usage
|
||||
c, b := do("GET", "/v1/magpie/usage?period=all", "127.0.0.1:5000", nil)
|
||||
if c != 200 || json.Unmarshal([]byte(b), &sum) != nil || sum.Calls != 3 || len(sum.CallerKeys) != 2 || sum.Path == "" {
|
||||
t.Fatal("loopback summary:", c, b)
|
||||
}
|
||||
var page usageapi.Ledger
|
||||
c, b = do("GET", "/v1/magpie/usage/requests?period=all", "127.0.0.1:5000", nil)
|
||||
if c != 200 || json.Unmarshal([]byte(b), &page) != nil || page.Total != 3 {
|
||||
t.Fatal("loopback requests:", c, b)
|
||||
}
|
||||
subs := 0
|
||||
for _, r := range page.Rows {
|
||||
if r.Subagent != "" {
|
||||
subs++
|
||||
if r.Subagent != "a143287ac46b82a96" || r.ParentAgent != "a99ca20c03d1813d8" || r.Session != "conv-1" {
|
||||
t.Fatalf("the subagent's row: %+v", r.Row)
|
||||
}
|
||||
} else if r.ParentAgent != "" {
|
||||
t.Fatalf("a parent with no subagent: %+v", r.Row)
|
||||
}
|
||||
}
|
||||
if subs != 1 {
|
||||
t.Fatal("subagent rows:", subs, b)
|
||||
}
|
||||
|
||||
if c, _ := do("GET", "/v1/magpie/usage", "192.168.1.9:5000", nil); c != http.StatusUnauthorized {
|
||||
t.Fatal("another machine with no key got", c)
|
||||
}
|
||||
sum = usageapi.Usage{}
|
||||
c, b = do("GET", "/v1/magpie/usage?period=all", "192.168.1.9:5000", nil, "Authorization", "Bearer "+secrets[0])
|
||||
if c != 200 || json.Unmarshal([]byte(b), &sum) != nil || sum.Calls != 3 || sum.Path != "" {
|
||||
t.Fatal("another machine with a key:", c, b)
|
||||
}
|
||||
|
||||
// the held key: no summary of everyone, and its own calls alone
|
||||
for _, from := range []string{"127.0.0.1:5000", "192.168.1.9:5000"} {
|
||||
if c, b := do("GET", "/v1/magpie/usage?period=all", from, nil, "x-api-key", secrets[1]); c != http.StatusForbidden || !strings.Contains(b, "/v1/magpie/usage/requests") {
|
||||
t.Fatal("held key's summary from", from, c, b)
|
||||
}
|
||||
page = usageapi.Ledger{}
|
||||
c, b := do("GET", "/v1/magpie/usage/requests?period=all&callerKey="+keys[0].ID, from, nil, "x-api-key", secrets[1])
|
||||
if c != 200 || json.Unmarshal([]byte(b), &page) != nil || page.Total != 1 || len(page.Rows) != 1 || page.Rows[0].CallerKeyID != keys[1].ID {
|
||||
t.Fatal("held key's requests from", from, c, b)
|
||||
}
|
||||
if len(page.CallerKeys) != 1 || strings.Contains(b, "Laptop") || strings.Contains(b, keys[0].ID) || strings.Contains(b, "conv-1") {
|
||||
t.Fatal("held key told of another key's calls:", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-304
@@ -7,114 +7,44 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
"github.com/yetone/magpie/internal/usageapi"
|
||||
)
|
||||
|
||||
// usageGroup is a usage.Group with what the UI needs to draw it.
|
||||
type usageGroup struct {
|
||||
usage.Group
|
||||
Name string `json:"name"`
|
||||
Sub string `json:"sub,omitempty"` // models: the provider's name
|
||||
Icon string `json:"icon,omitempty"` // a real logo, or "generic" for an unknown client
|
||||
}
|
||||
// The Usage page's JSON is built in usageapi, which the gateway's
|
||||
// /v1/magpie/usage answers from too.
|
||||
type (
|
||||
usageGroup = usageapi.Group
|
||||
usageJSON = usageapi.Usage
|
||||
ledgerRow = usageapi.Row
|
||||
ledgerJSON = usageapi.Ledger
|
||||
)
|
||||
|
||||
type usageJSON struct {
|
||||
usage.Summary
|
||||
Agents []usageGroup `json:"agents"`
|
||||
Models []usageGroup `json:"models"`
|
||||
Accounts []usageGroup `json:"accounts"`
|
||||
CallerKeys []usageGroup `json:"callerKeys"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
var (
|
||||
usageState = usageapi.State
|
||||
ledgerPage = usageapi.LedgerPage
|
||||
periodOf = usageapi.PeriodOf
|
||||
ledgerFilter = usageapi.FilterOf
|
||||
)
|
||||
|
||||
func usageState(p usage.Period) usageJSON {
|
||||
s := usage.Summarize(p)
|
||||
out := usageJSON{Summary: s, Agents: []usageGroup{}, Models: []usageGroup{}, Accounts: []usageGroup{}, Path: tilde(usage.Path())}
|
||||
agents := map[string]*agent.Agent{}
|
||||
for _, a := range agent.Clients() {
|
||||
agents[a.ID] = a
|
||||
}
|
||||
for _, g := range s.Agents {
|
||||
ug := usageGroup{Group: g, Name: g.ID, Icon: "generic"}
|
||||
if a := agents[g.ID]; a != nil {
|
||||
ug.Name, ug.Icon = a.Name, a.Icon
|
||||
func init() {
|
||||
usageapi.Clients = func() []usageapi.Client {
|
||||
var out []usageapi.Client
|
||||
for _, a := range agent.Clients() {
|
||||
out = append(out, usageapi.Client{ID: a.ID, Name: a.Name, Icon: a.Icon})
|
||||
}
|
||||
out.Agents = append(out.Agents, ug)
|
||||
return out
|
||||
}
|
||||
providers := map[string]provider.Provider{}
|
||||
for _, p := range provider.All() {
|
||||
providers[p.ID] = p
|
||||
}
|
||||
for _, g := range s.Models {
|
||||
ug := usageGroup{Group: g, Name: g.Model, Sub: g.Provider, Icon: "generic"}
|
||||
if p, ok := providers[g.Provider]; ok {
|
||||
ug.Sub = p.Name
|
||||
if p.Icon != "" {
|
||||
ug.Icon = p.Icon
|
||||
}
|
||||
}
|
||||
if g.Host != "" {
|
||||
ug.Sub += " · " + g.Host
|
||||
}
|
||||
out.Models = append(out.Models, ug)
|
||||
}
|
||||
// each subscription account's share, by the account that answered
|
||||
// (#557); Name "" is the calls whose record names none, the page
|
||||
// saying "account not recorded"
|
||||
for _, g := range s.Accounts {
|
||||
ug := usageGroup{Group: g, Name: g.Account, Sub: g.Provider, Icon: "generic"}
|
||||
if p, ok := providers[g.Provider]; ok {
|
||||
ug.Sub = p.Name
|
||||
if p.Icon != "" {
|
||||
ug.Icon = p.Icon
|
||||
}
|
||||
}
|
||||
out.Accounts = append(out.Accounts, ug)
|
||||
}
|
||||
out.CallerKeys = callerUsageGroups(s)
|
||||
return out
|
||||
}
|
||||
|
||||
func callerUsageGroups(s usage.Summary) []usageGroup {
|
||||
keys := []usageGroup{}
|
||||
current, _ := access.List()
|
||||
names := map[string]string{}
|
||||
for _, k := range current {
|
||||
names[k.ID] = k.Name
|
||||
}
|
||||
for _, g := range s.CallerKeys {
|
||||
n := names[g.CallerKeyID]
|
||||
if n == "" {
|
||||
n = g.CallerKeyName
|
||||
}
|
||||
if n == "" {
|
||||
n = g.CallerKeyID
|
||||
}
|
||||
keys = append(keys, usageGroup{Group: g, Name: n, Icon: "generic"})
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// periodOf is the period a ?period= names: a preset, or days picked as
|
||||
// "2026-10-01..2026-10-07" (#1492); 30 days for anything else.
|
||||
func periodOf(s string) usage.Period {
|
||||
if p := usage.Period(s); p.Known() {
|
||||
return p
|
||||
}
|
||||
return usage.Month
|
||||
}
|
||||
|
||||
// csvStamp names the selected day, or, when no day is selected, the period
|
||||
@@ -129,219 +59,6 @@ func csvStamp(p usage.Period, day string, now time.Time) string {
|
||||
return "magpie-requests-" + string(p) + "-" + now.Format(time.DateOnly)
|
||||
}
|
||||
|
||||
func ledgerFilter(q url.Values) usage.Filter {
|
||||
id, _ := strconv.ParseInt(q.Get("route"), 10, 64)
|
||||
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: q.Get("model"), Agent: q.Get("agent"), Provider: q.Get("provider"), Purpose: q.Get("purpose"), Account: q.Get("account"), CallerKey: q.Get("callerKey"), Failed: q.Get("failed") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
|
||||
}
|
||||
|
||||
// viaOf is the source a request's ?via= names, "" for both.
|
||||
func viaOf(s string) string {
|
||||
switch s {
|
||||
case usage.SourceGateway, usage.SourceSession:
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ledgerRow is a usage.Row with the names the page shows it by.
|
||||
type ledgerRow struct {
|
||||
usage.Row
|
||||
CallerKeyLabel string `json:"callerKeyLabel,omitempty"`
|
||||
AgentName string `json:"agentName"`
|
||||
Icon string `json:"icon"` // the agent's
|
||||
ProviderName string `json:"providerName"`
|
||||
Access string `json:"access,omitempty"` // known account/route type, independent of model maker
|
||||
PricingModel string `json:"pricing_model,omitempty"`
|
||||
// ComputerName is the other computer a call was made on, shared through sync (#542)
|
||||
ComputerName string `json:"computerName,omitempty"`
|
||||
}
|
||||
|
||||
type ledgerJSON struct {
|
||||
CallerKeys []usageGroup `json:"callerKeys"`
|
||||
Period usage.Period `json:"period"`
|
||||
Rows []ledgerRow `json:"rows"`
|
||||
Offset int `json:"offset"`
|
||||
Total int `json:"total"` // the rows the filter keeps, on every page
|
||||
// Series: the period by hour, day or week (Bucket), before the day filter
|
||||
Bucket string `json:"bucket"`
|
||||
Series []usage.SeriesPoint `json:"series"`
|
||||
// By: the rows told apart by provider, agent, model and model at each
|
||||
// provider ("modelAt", named "model · provider"), the most tokens
|
||||
// first. The one by a dimension the filter has picked is of the rows
|
||||
// without that pick, so the others are still there to switch to.
|
||||
By map[string][]ledgerShare `json:"by"`
|
||||
ChartBy map[string][]ledgerShare `json:"chartBy,omitempty"`
|
||||
Day string `json:"day,omitempty"`
|
||||
usage.Totals
|
||||
// Through and Direct: the rows the gateway served, and the rows read
|
||||
// from the agents' own session files, which it never saw. Totals is
|
||||
// the two together, so the page can show all three (#the usage report).
|
||||
Through usage.Totals `json:"through"`
|
||||
Direct usage.Totals `json:"direct"`
|
||||
// Agents, Providers and Purposes: those with calls in the period, for the filters
|
||||
Agents []ledgerAgent `json:"agents"`
|
||||
Providers []ledgerAgent `json:"providers"`
|
||||
Purposes []string `json:"purposes"`
|
||||
// Accounts: the subscription accounts that answered calls in the
|
||||
// period, for the Account filter (#557)
|
||||
Accounts []ledgerAccount `json:"accounts"`
|
||||
// Computers: this one ("this", no name) and the others whose usage
|
||||
// sync brought (#542), for the filter; none while there are none
|
||||
Computers []ledgerShare `json:"computers,omitempty"`
|
||||
}
|
||||
|
||||
// ledgerShare is a usage.Share with the name and logo the page shows it by.
|
||||
type ledgerShare struct {
|
||||
usage.Share
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon,omitempty"`
|
||||
}
|
||||
|
||||
// ledgerAccount is a subscription account the Account filter offers: its
|
||||
// name, and the providers it answered for, by name.
|
||||
type ledgerAccount struct {
|
||||
ID string `json:"id"`
|
||||
Providers []string `json:"providers"`
|
||||
}
|
||||
|
||||
type ledgerAgent struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon"`
|
||||
}
|
||||
|
||||
// ledgerPage is one page of the ledger: limit rows (100 when none is
|
||||
// given, 500 at most) from offset.
|
||||
func ledgerPage(p usage.Period, f usage.Filter, offset, limit int) ledgerJSON {
|
||||
l := usage.QueryPage(p, f, offset, limit)
|
||||
offset = max(0, min(offset, l.Total))
|
||||
page := l.Rows
|
||||
agents := map[string]*agent.Agent{}
|
||||
for _, a := range agent.Clients() {
|
||||
agents[a.ID] = a
|
||||
}
|
||||
// A session file without route evidence is a local source, not a supplier.
|
||||
names := map[string]string{usage.UnknownProvider: "Local session"}
|
||||
icons := map[string]string{}
|
||||
access := map[string]string{}
|
||||
for _, pr := range provider.All() {
|
||||
names[pr.ID], icons[pr.ID] = pr.Name, pr.Icon
|
||||
if pr.Account != nil {
|
||||
access[pr.ID] = "subscription"
|
||||
} else if pr.Key != "" {
|
||||
access[pr.ID] = "api"
|
||||
}
|
||||
}
|
||||
who := func(id string) ledgerAgent {
|
||||
if a := agents[id]; a != nil {
|
||||
return ledgerAgent{ID: id, Name: a.Name, Icon: a.Icon}
|
||||
}
|
||||
return ledgerAgent{ID: id, Name: id, Icon: "generic"}
|
||||
}
|
||||
which := func(id string) ledgerAgent {
|
||||
a := ledgerAgent{ID: id, Name: names[id], Icon: icons[id]}
|
||||
if a.Name == "" {
|
||||
a.Name = id
|
||||
}
|
||||
if a.Icon == "" {
|
||||
a.Icon = "generic"
|
||||
}
|
||||
return a
|
||||
}
|
||||
out := ledgerJSON{Period: p, Rows: make([]ledgerRow, 0, len(page)), Offset: offset, Total: l.Total, Totals: l.Sum, Agents: []ledgerAgent{}, Providers: []ledgerAgent{}, Accounts: []ledgerAccount{}}
|
||||
out.Through, out.Direct = l.Through, l.Direct
|
||||
out.Bucket, out.Series = l.Bucket, l.Series
|
||||
out.Purposes = l.Purposes
|
||||
out.Day = f.Day
|
||||
out.CallerKeys = callerUsageGroups(usage.Summary{CallerKeys: l.CallerKeys})
|
||||
callerLabels := map[string]string{}
|
||||
for _, g := range out.CallerKeys {
|
||||
callerLabels[g.CallerKeyID] = g.Name
|
||||
}
|
||||
for _, r := range page {
|
||||
a := who(r.Agent)
|
||||
lr := ledgerRow{Row: r, AgentName: a.Name, Icon: a.Icon, ProviderName: names[r.Provider]}
|
||||
if r.Source != "log" {
|
||||
lr.Access = access[r.Provider]
|
||||
}
|
||||
if r.Priced {
|
||||
if model := provider.PricedNameFor(r.Provider, r.Model); model != r.Model {
|
||||
lr.PricingModel = model
|
||||
}
|
||||
}
|
||||
if lr.ProviderName == "" {
|
||||
lr.ProviderName = r.Provider
|
||||
}
|
||||
lr.CallerKeyLabel = callerLabels[r.CallerKeyID]
|
||||
if r.Computer != "" {
|
||||
lr.ComputerName = l.Names[r.Computer]
|
||||
if lr.ComputerName == "" {
|
||||
lr.ComputerName = r.Computer
|
||||
}
|
||||
}
|
||||
out.Rows = append(out.Rows, lr)
|
||||
}
|
||||
for _, id := range l.Agents {
|
||||
out.Agents = append(out.Agents, who(id))
|
||||
}
|
||||
for _, id := range l.Providers {
|
||||
out.Providers = append(out.Providers, which(id))
|
||||
}
|
||||
// one choice per account, most used first, with the providers it
|
||||
// answered for: the same email may be a Codex and a Claude account
|
||||
at := map[string]int{}
|
||||
for _, g := range l.Accounts {
|
||||
name := which(g.Provider).Name
|
||||
if i, ok := at[g.Account]; ok {
|
||||
if a := &out.Accounts[i]; !slices.Contains(a.Providers, name) {
|
||||
a.Providers = append(a.Providers, name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
at[g.Account] = len(out.Accounts)
|
||||
out.Accounts = append(out.Accounts, ledgerAccount{ID: g.Account, Providers: []string{name}})
|
||||
}
|
||||
// what each is of: the rows of the filter, or, for the dimension the
|
||||
// filter has picked, of the rows without that pick
|
||||
sharesJSON := func(by map[string][]usage.Share) map[string][]ledgerShare {
|
||||
out := map[string][]ledgerShare{}
|
||||
for _, d := range usage.Dimensions {
|
||||
shares := []ledgerShare{}
|
||||
for _, s := range by[d] {
|
||||
ls := ledgerShare{Share: s, Name: s.ID}
|
||||
switch d {
|
||||
case "provider":
|
||||
a := which(s.ID)
|
||||
ls.Name, ls.Icon = a.Name, a.Icon
|
||||
case "agent":
|
||||
a := who(s.ID)
|
||||
ls.Name, ls.Icon = a.Name, a.Icon
|
||||
case "modelAt":
|
||||
// the model, and the provider it went to
|
||||
prov, model, _ := strings.Cut(s.ID, "/")
|
||||
a := which(prov)
|
||||
ls.Name, ls.Icon = model+" · "+a.Name, a.Icon
|
||||
}
|
||||
shares = append(shares, ls)
|
||||
}
|
||||
out[d] = shares
|
||||
}
|
||||
return out
|
||||
}
|
||||
out.By = sharesJSON(l.By)
|
||||
if l.ChartBy != nil {
|
||||
out.ChartBy = sharesJSON(l.ChartBy)
|
||||
}
|
||||
for _, s := range l.Computers {
|
||||
ls := ledgerShare{Share: s, Name: l.Names[s.ID]}
|
||||
if s.ID != usage.ThisComputer && ls.Name == "" {
|
||||
ls.Name = s.ID
|
||||
}
|
||||
out.Computers = append(out.Computers, ls)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// contentJSON is what was said in a request, or why it can't be told.
|
||||
type contentJSON struct {
|
||||
Found bool `json:"found"`
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/desktopdir"
|
||||
@@ -319,6 +320,56 @@ func sessionOfPath(p string) string {
|
||||
return strings.TrimSuffix(filepath.Base(p), ".jsonl")
|
||||
}
|
||||
|
||||
// SubagentOf is the subagent a Claude Code file is the conversation of, by
|
||||
// its name: <agent> of <id>/subagents/agent-<agent>.jsonl or a workflow's
|
||||
// <id>/subagents/workflows/<run>/agent-<agent>.jsonl — the agentId its
|
||||
// lines carry, and the x-claude-code-agent-id Claude Code sends the
|
||||
// gateway for it. "" for a session's own file, and any other agent's.
|
||||
func SubagentOf(p string) string {
|
||||
d := filepath.Dir(p)
|
||||
if filepath.Base(d) != "subagents" && (filepath.Base(filepath.Dir(d)) != "workflows" || filepath.Base(filepath.Dir(filepath.Dir(d))) != "subagents") {
|
||||
return ""
|
||||
}
|
||||
name := strings.TrimSuffix(filepath.Base(p), ".jsonl")
|
||||
if name == filepath.Base(p) || !strings.HasPrefix(name, "agent-") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(name, "agent-")
|
||||
}
|
||||
|
||||
// SubagentParent is the subagent that started the one whose Claude Code
|
||||
// file p is: the parentAgentId of its agent-<agent>.meta.json beside it,
|
||||
// which Claude Code writes for a subagent a subagent started (spawnDepth
|
||||
// 2 and on), the x-claude-code-parent-agent-id it sends the gateway. ""
|
||||
// for one the conversation itself started, and for a file that is no
|
||||
// subagent's. A meta file once read is kept; one not read is read again.
|
||||
func SubagentParent(p string) string {
|
||||
if SubagentOf(p) == "" {
|
||||
return ""
|
||||
}
|
||||
meta := strings.TrimSuffix(p, ".jsonl") + ".meta.json"
|
||||
if v, ok := subagentParents.Load(meta); ok {
|
||||
return v.(string)
|
||||
}
|
||||
b, err := os.ReadFile(meta)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var m struct {
|
||||
ParentAgentID string `json:"parentAgentId"`
|
||||
}
|
||||
if json.Unmarshal(b, &m) != nil {
|
||||
return ""
|
||||
}
|
||||
parent := m.ParentAgentID[:min(len(m.ParentAgentID), 128)]
|
||||
subagentParents.Store(meta, parent)
|
||||
return parent
|
||||
}
|
||||
|
||||
// subagentParents: SubagentParent's meta files read, by path. Claude Code
|
||||
// writes one as it starts the subagent and never changes it.
|
||||
var subagentParents sync.Map
|
||||
|
||||
// str is s kept once per file, as the calls of a file repeat a few.
|
||||
func (st *callFile) str(s string) string {
|
||||
if s == "" {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A Claude Code subagent's conversation is a file of its own beside the
|
||||
// session's, named by the agentId its lines carry; a workflow's agents
|
||||
// sit a folder deeper. The shapes are those under ~/.claude/projects.
|
||||
func TestSubagentOf(t *testing.T) {
|
||||
proj := filepath.FromSlash("/h/.claude/projects/-Users-me-app")
|
||||
for p, want := range map[string]string{
|
||||
"2bd9379e-9a4a-4cb6-ba42-e6b2fb6dc5a5/subagents/agent-a76fc11ece25eafc9.jsonl": "a76fc11ece25eafc9",
|
||||
"4c056ab3-f2e6-4918-b774-da5c713ce1e3/subagents/workflows/wf_e241ae3e-9ce/agent-aa06d649dca14e7f9.jsonl": "aa06d649dca14e7f9",
|
||||
"2bd9379e-9a4a-4cb6-ba42-e6b2fb6dc5a5.jsonl": "",
|
||||
"2bd9379e-9a4a-4cb6-ba42-e6b2fb6dc5a5/subagents/agent-a76fc11ece25eafc9.meta.json": "",
|
||||
"2bd9379e-9a4a-4cb6-ba42-e6b2fb6dc5a5/subagents/notes.jsonl": "",
|
||||
"2bd9379e-9a4a-4cb6-ba42-e6b2fb6dc5a5/workflows/wf_1/agent-a1.jsonl": "",
|
||||
"agent-a1.jsonl": "",
|
||||
} {
|
||||
if got := SubagentOf(filepath.Join(proj, filepath.FromSlash(p))); got != want {
|
||||
t.Errorf("%s: %q, want %q", p, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A subagent another started says which one in its meta file; the bytes
|
||||
// are Claude Code 2.1.296's for a subagent spawned by a subagent, and for
|
||||
// the one the conversation spawned.
|
||||
func TestSubagentParent(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "3ac5fc87-6335-4971-9609-0fbdc17742ce", "subagents")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write := func(name, s string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
nested := write("agent-a143287ac46b82a96.jsonl", "{}\n")
|
||||
write("agent-a143287ac46b82a96.meta.json", `{"agentType":"general-purpose","description":"check","toolUseId":"toolu_01","parentAgentId":"a99ca20c03d1813d8","spawnDepth":2,"requestShape":"background","requestNonInteractive":true}`)
|
||||
first := write("agent-a99ca20c03d1813d8.jsonl", "{}\n")
|
||||
write("agent-a99ca20c03d1813d8.meta.json", `{"agentType":"general-purpose","description":"check","toolUseId":"toolu_01","spawnDepth":1,"requestShape":"background","requestNonInteractive":true}`)
|
||||
if got := SubagentParent(nested); got != "a99ca20c03d1813d8" {
|
||||
t.Fatalf("nested: %q", got)
|
||||
}
|
||||
if got := SubagentParent(first); got != "" {
|
||||
t.Fatalf("started by the conversation: %q", got)
|
||||
}
|
||||
// no meta file yet is not known, so it is read again once there is one
|
||||
late := write("agent-a5.jsonl", "{}\n")
|
||||
if got := SubagentParent(late); got != "" {
|
||||
t.Fatalf("no meta: %q", got)
|
||||
}
|
||||
write("agent-a5.meta.json", `{"parentAgentId":"a99ca20c03d1813d8","spawnDepth":2}`)
|
||||
if got := SubagentParent(late); got != "a99ca20c03d1813d8" {
|
||||
t.Fatalf("meta written later: %q", got)
|
||||
}
|
||||
if got := SubagentParent(filepath.Join(filepath.Dir(dir), "x.jsonl")); got != "" {
|
||||
t.Fatalf("a session's own file: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -292,7 +292,7 @@ const UnknownProvider = "session-unknown"
|
||||
func logRecord(c sessions.Call) Record {
|
||||
r := Record{Time: c.Time, Agent: c.Agent, Provider: UnknownProvider, Model: c.Model, Served: c.Model, Requested: c.Requested,
|
||||
Input: c.Input, Output: c.Output, CacheRead: c.CacheRead, CacheWrite: c.CacheWrite, CacheWrite1h: c.CacheWrite1h, Reasoning: c.Reasoning, Effort: c.Effort,
|
||||
Millis: c.Millis, TTFT: c.TTFT, Session: c.Session, RequestID: c.RequestID, Error: c.ErrorText, ErrType: c.Error}
|
||||
Millis: c.Millis, TTFT: c.TTFT, Session: c.Session, RequestID: c.RequestID, Error: c.ErrorText, ErrType: c.Error, Subagent: sessions.SubagentOf(c.File), ParentAgent: sessions.SubagentParent(c.File)}
|
||||
if c.Agent == "codex" || c.Agent == "opencode" {
|
||||
r.Requested, r.Served = c.Model, ""
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ type RequestPage struct {
|
||||
|
||||
type packedRow struct {
|
||||
Time time.Time
|
||||
Text [28]uint32
|
||||
Text [30]uint32
|
||||
Tokens [6]int64
|
||||
Millis, TTFT, FirstText, Order int64
|
||||
Sent, Flow int64
|
||||
@@ -84,10 +84,10 @@ type rowChunk struct {
|
||||
}
|
||||
|
||||
// rowMsg is the Text of a row's Claude message id, after rowText's
|
||||
const rowMsg = 27
|
||||
const rowMsg = 29
|
||||
|
||||
func rowText(r *Row) [27]*string {
|
||||
return [27]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream}
|
||||
func rowText(r *Row) [29]*string {
|
||||
return [29]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent}
|
||||
}
|
||||
func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
||||
if c.dict == nil {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// A call read from a Claude Code subagent's own file names that subagent
|
||||
// and, from its meta file, the subagent that started it,
|
||||
// and the subagent and the one that started it are kept when the rows are
|
||||
// packed away and read back.
|
||||
func TestRowKeepsSubagent(t *testing.T) {
|
||||
f := filepath.FromSlash("/h/.claude/projects/-p/2bd9379e-9a4a-4cb6-ba42-e6b2fb6dc5a5/subagents/agent-a76fc11ece25eafc9.jsonl")
|
||||
if r := logRecord(sessions.Call{File: f, Agent: "claude", Model: "m"}); r.Subagent != "a76fc11ece25eafc9" || r.ParentAgent != "" {
|
||||
t.Fatalf("from the subagent's file: %+v", r)
|
||||
}
|
||||
if r := logRecord(sessions.Call{File: filepath.FromSlash("/h/.claude/projects/-p/2bd9379e.jsonl"), Agent: "claude", Model: "m"}); r.Subagent != "" {
|
||||
t.Fatalf("from the session's own file: %q", r.Subagent)
|
||||
}
|
||||
sub := filepath.Join(t.TempDir(), "3ac5fc87", "subagents")
|
||||
os.MkdirAll(sub, 0o755)
|
||||
os.WriteFile(filepath.Join(sub, "agent-a143287ac46b82a96.meta.json"), []byte(`{"agentType":"general-purpose","parentAgentId":"a99ca20c03d1813d8","spawnDepth":2}`), 0o644)
|
||||
if r := logRecord(sessions.Call{File: filepath.Join(sub, "agent-a143287ac46b82a96.jsonl"), Agent: "claude", Model: "m"}); r.Subagent != "a143287ac46b82a96" || r.ParentAgent != "a99ca20c03d1813d8" {
|
||||
t.Fatalf("a subagent a subagent started: %+v", r)
|
||||
}
|
||||
c := &rowChunk{}
|
||||
c.add(Row{Record: Record{Time: time.Now(), Agent: "claude", Session: "conv-1", Subagent: "a1", ParentAgent: "a0"}}, "msg", 1, false)
|
||||
for _, chunk := range []*rowChunk{c, c.pack().unpack()} {
|
||||
if r := chunk.row(0); r.Subagent != "a1" || r.ParentAgent != "a0" || r.Session != "conv-1" || chunk.Strings[chunk.Rows[0].Text[rowMsg]] != "msg" {
|
||||
t.Fatalf("read back: %+v", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,14 @@ type Record struct {
|
||||
Session string `json:"session,omitempty"`
|
||||
// NativeSession retains the client header when X-Magpie-Session overrides it.
|
||||
NativeSession string `json:"native_session,omitempty"`
|
||||
// Subagent is the subagent that made the call, as its agent names it
|
||||
// (Claude Code's x-claude-code-agent-id, the agentId of its
|
||||
// subagents/agent-<id>.jsonl): Session stays the conversation it was
|
||||
// spawned in, so its calls are counted there too. ParentAgent is the
|
||||
// subagent that spawned it in turn (x-claude-code-parent-agent-id), ""
|
||||
// when the conversation itself did or the agent doesn't say.
|
||||
Subagent string `json:"subagent,omitempty"`
|
||||
ParentAgent string `json:"parent_agent,omitempty"`
|
||||
// Rejected is a request refused locally before an upstream was contacted.
|
||||
Rejected bool `json:"rejected,omitempty"`
|
||||
// Kind is what the agent made the call for when it isn't a turn of
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
// Package usageapi builds what magpie tells of its usage log: the Usage
|
||||
// page's summary and its requests, a page at a time. The GUI's /api/usage
|
||||
// and the gateway's /v1/magpie/usage answer the same JSON from here, so an
|
||||
// app reading one reads the other.
|
||||
package usageapi
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// Client is an agent as the usage JSON names it.
|
||||
type Client struct{ ID, Name, Icon string }
|
||||
|
||||
// Clients are the agents magpie knows, for their names and logos: set by
|
||||
// the GUI (internal/agent imports the gateway, which imports this). Unset,
|
||||
// an agent is named by its id.
|
||||
var Clients func() []Client
|
||||
|
||||
func clients() map[string]*Named {
|
||||
out := map[string]*Named{}
|
||||
if Clients == nil {
|
||||
return out
|
||||
}
|
||||
for _, c := range Clients() {
|
||||
out[c.ID] = &Named{ID: c.ID, Name: c.Name, Icon: c.Icon}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Tilde is p with the home folder written ~.
|
||||
func Tilde(p string) string {
|
||||
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home) {
|
||||
return "~" + p[len(home):]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Group is a usage.Group with what the UI needs to draw it.
|
||||
type Group struct {
|
||||
usage.Group
|
||||
Name string `json:"name"`
|
||||
Sub string `json:"sub,omitempty"` // models: the provider's name
|
||||
Icon string `json:"icon,omitempty"` // a real logo, or "generic" for an unknown client
|
||||
}
|
||||
|
||||
type Usage struct {
|
||||
usage.Summary
|
||||
Agents []Group `json:"agents"`
|
||||
Models []Group `json:"models"`
|
||||
Accounts []Group `json:"accounts"`
|
||||
CallerKeys []Group `json:"callerKeys"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
// State is the Usage page's summary of a period: what /api/usage and the
|
||||
// gateway's GET /v1/magpie/usage answer.
|
||||
func State(p usage.Period) Usage {
|
||||
s := usage.Summarize(p)
|
||||
out := Usage{Summary: s, Agents: []Group{}, Models: []Group{}, Accounts: []Group{}, Path: Tilde(usage.Path())}
|
||||
agents := clients()
|
||||
for _, g := range s.Agents {
|
||||
ug := Group{Group: g, Name: g.ID, Icon: "generic"}
|
||||
if a := agents[g.ID]; a != nil {
|
||||
ug.Name, ug.Icon = a.Name, a.Icon
|
||||
}
|
||||
out.Agents = append(out.Agents, ug)
|
||||
}
|
||||
providers := map[string]provider.Provider{}
|
||||
for _, p := range provider.All() {
|
||||
providers[p.ID] = p
|
||||
}
|
||||
for _, g := range s.Models {
|
||||
ug := Group{Group: g, Name: g.Model, Sub: g.Provider, Icon: "generic"}
|
||||
if p, ok := providers[g.Provider]; ok {
|
||||
ug.Sub = p.Name
|
||||
if p.Icon != "" {
|
||||
ug.Icon = p.Icon
|
||||
}
|
||||
}
|
||||
if g.Host != "" {
|
||||
ug.Sub += " · " + g.Host
|
||||
}
|
||||
out.Models = append(out.Models, ug)
|
||||
}
|
||||
// each subscription account's share, by the account that answered
|
||||
// (#557); Name "" is the calls whose record names none, the page
|
||||
// saying "account not recorded"
|
||||
for _, g := range s.Accounts {
|
||||
ug := Group{Group: g, Name: g.Account, Sub: g.Provider, Icon: "generic"}
|
||||
if p, ok := providers[g.Provider]; ok {
|
||||
ug.Sub = p.Name
|
||||
if p.Icon != "" {
|
||||
ug.Icon = p.Icon
|
||||
}
|
||||
}
|
||||
out.Accounts = append(out.Accounts, ug)
|
||||
}
|
||||
out.CallerKeys = callerGroups(s)
|
||||
return out
|
||||
}
|
||||
|
||||
func callerGroups(s usage.Summary) []Group {
|
||||
keys := []Group{}
|
||||
current, _ := access.List()
|
||||
names := map[string]string{}
|
||||
for _, k := range current {
|
||||
names[k.ID] = k.Name
|
||||
}
|
||||
for _, g := range s.CallerKeys {
|
||||
n := names[g.CallerKeyID]
|
||||
if n == "" {
|
||||
n = g.CallerKeyName
|
||||
}
|
||||
if n == "" {
|
||||
n = g.CallerKeyID
|
||||
}
|
||||
keys = append(keys, Group{Group: g, Name: n, Icon: "generic"})
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// PeriodOf is the period a ?period= names: a preset, or days picked as
|
||||
// "2026-10-01..2026-10-07" (#1492); 30 days for anything else.
|
||||
func PeriodOf(s string) usage.Period {
|
||||
if p := usage.Period(s); p.Known() {
|
||||
return p
|
||||
}
|
||||
return usage.Month
|
||||
}
|
||||
|
||||
func FilterOf(q url.Values) usage.Filter {
|
||||
id, _ := strconv.ParseInt(q.Get("route"), 10, 64)
|
||||
return usage.Filter{Day: q.Get("day"), RouteID: id, Model: q.Get("model"), Agent: q.Get("agent"), Provider: q.Get("provider"), Purpose: q.Get("purpose"), Account: q.Get("account"), CallerKey: q.Get("callerKey"), Failed: q.Get("failed") == "1", Query: q.Get("q"), Computer: q.Get("computer"), Through: viaOf(q.Get("via"))}
|
||||
}
|
||||
|
||||
// viaOf is the source a request's ?via= names, "" for both.
|
||||
func viaOf(s string) string {
|
||||
switch s {
|
||||
case usage.SourceGateway, usage.SourceSession:
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Row is a usage.Row with the names the page shows it by.
|
||||
type Row struct {
|
||||
usage.Row
|
||||
CallerKeyLabel string `json:"callerKeyLabel,omitempty"`
|
||||
AgentName string `json:"agentName"`
|
||||
Icon string `json:"icon"` // the agent's
|
||||
ProviderName string `json:"providerName"`
|
||||
Access string `json:"access,omitempty"` // known account/route type, independent of model maker
|
||||
PricingModel string `json:"pricing_model,omitempty"`
|
||||
// ComputerName is the other computer a call was made on, shared through sync (#542)
|
||||
ComputerName string `json:"computerName,omitempty"`
|
||||
}
|
||||
|
||||
type Ledger struct {
|
||||
CallerKeys []Group `json:"callerKeys"`
|
||||
Period usage.Period `json:"period"`
|
||||
Rows []Row `json:"rows"`
|
||||
Offset int `json:"offset"`
|
||||
Total int `json:"total"` // the rows the filter keeps, on every page
|
||||
// Series: the period by hour, day or week (Bucket), before the day filter
|
||||
Bucket string `json:"bucket"`
|
||||
Series []usage.SeriesPoint `json:"series"`
|
||||
// By: the rows told apart by provider, agent, model and model at each
|
||||
// provider ("modelAt", named "model · provider"), the most tokens
|
||||
// first. The one by a dimension the filter has picked is of the rows
|
||||
// without that pick, so the others are still there to switch to.
|
||||
By map[string][]Share `json:"by"`
|
||||
ChartBy map[string][]Share `json:"chartBy,omitempty"`
|
||||
Day string `json:"day,omitempty"`
|
||||
usage.Totals
|
||||
// Through and Direct: the rows the gateway served, and the rows read
|
||||
// from the agents' own session files, which it never saw. Totals is
|
||||
// the two together, so the page can show all three (#the usage report).
|
||||
Through usage.Totals `json:"through"`
|
||||
Direct usage.Totals `json:"direct"`
|
||||
// Agents, Providers and Purposes: those with calls in the period, for the filters
|
||||
Agents []Named `json:"agents"`
|
||||
Providers []Named `json:"providers"`
|
||||
Purposes []string `json:"purposes"`
|
||||
// Accounts: the subscription accounts that answered calls in the
|
||||
// period, for the Account filter (#557)
|
||||
Accounts []Account `json:"accounts"`
|
||||
// Computers: this one ("this", no name) and the others whose usage
|
||||
// sync brought (#542), for the filter; none while there are none
|
||||
Computers []Share `json:"computers,omitempty"`
|
||||
}
|
||||
|
||||
// Share is a usage.Share with the name and logo the page shows it by.
|
||||
type Share struct {
|
||||
usage.Share
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon,omitempty"`
|
||||
}
|
||||
|
||||
// Account is a subscription account the Account filter offers: its
|
||||
// name, and the providers it answered for, by name.
|
||||
type Account struct {
|
||||
ID string `json:"id"`
|
||||
Providers []string `json:"providers"`
|
||||
}
|
||||
|
||||
type Named struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon"`
|
||||
}
|
||||
|
||||
// LedgerPage is one page of the ledger: limit rows (100 when none is
|
||||
// given, 500 at most) from offset.
|
||||
func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger {
|
||||
l := usage.QueryPage(p, f, offset, limit)
|
||||
offset = max(0, min(offset, l.Total))
|
||||
page := l.Rows
|
||||
agents := clients()
|
||||
// A session file without route evidence is a local source, not a supplier.
|
||||
names := map[string]string{usage.UnknownProvider: "Local session"}
|
||||
icons := map[string]string{}
|
||||
access := map[string]string{}
|
||||
for _, pr := range provider.All() {
|
||||
names[pr.ID], icons[pr.ID] = pr.Name, pr.Icon
|
||||
if pr.Account != nil {
|
||||
access[pr.ID] = "subscription"
|
||||
} else if pr.Key != "" {
|
||||
access[pr.ID] = "api"
|
||||
}
|
||||
}
|
||||
who := func(id string) Named {
|
||||
if a := agents[id]; a != nil {
|
||||
return Named{ID: id, Name: a.Name, Icon: a.Icon}
|
||||
}
|
||||
return Named{ID: id, Name: id, Icon: "generic"}
|
||||
}
|
||||
which := func(id string) Named {
|
||||
a := Named{ID: id, Name: names[id], Icon: icons[id]}
|
||||
if a.Name == "" {
|
||||
a.Name = id
|
||||
}
|
||||
if a.Icon == "" {
|
||||
a.Icon = "generic"
|
||||
}
|
||||
return a
|
||||
}
|
||||
out := Ledger{Period: p, Rows: make([]Row, 0, len(page)), Offset: offset, Total: l.Total, Totals: l.Sum, Agents: []Named{}, Providers: []Named{}, Accounts: []Account{}}
|
||||
out.Through, out.Direct = l.Through, l.Direct
|
||||
out.Bucket, out.Series = l.Bucket, l.Series
|
||||
out.Purposes = l.Purposes
|
||||
out.Day = f.Day
|
||||
out.CallerKeys = callerGroups(usage.Summary{CallerKeys: l.CallerKeys})
|
||||
callerLabels := map[string]string{}
|
||||
for _, g := range out.CallerKeys {
|
||||
callerLabels[g.CallerKeyID] = g.Name
|
||||
}
|
||||
for _, r := range page {
|
||||
a := who(r.Agent)
|
||||
lr := Row{Row: r, AgentName: a.Name, Icon: a.Icon, ProviderName: names[r.Provider]}
|
||||
if r.Source != "log" {
|
||||
lr.Access = access[r.Provider]
|
||||
}
|
||||
if r.Priced {
|
||||
if model := provider.PricedNameFor(r.Provider, r.Model); model != r.Model {
|
||||
lr.PricingModel = model
|
||||
}
|
||||
}
|
||||
if lr.ProviderName == "" {
|
||||
lr.ProviderName = r.Provider
|
||||
}
|
||||
lr.CallerKeyLabel = callerLabels[r.CallerKeyID]
|
||||
if r.Computer != "" {
|
||||
lr.ComputerName = l.Names[r.Computer]
|
||||
if lr.ComputerName == "" {
|
||||
lr.ComputerName = r.Computer
|
||||
}
|
||||
}
|
||||
out.Rows = append(out.Rows, lr)
|
||||
}
|
||||
for _, id := range l.Agents {
|
||||
out.Agents = append(out.Agents, who(id))
|
||||
}
|
||||
for _, id := range l.Providers {
|
||||
out.Providers = append(out.Providers, which(id))
|
||||
}
|
||||
// one choice per account, most used first, with the providers it
|
||||
// answered for: the same email may be a Codex and a Claude account
|
||||
at := map[string]int{}
|
||||
for _, g := range l.Accounts {
|
||||
name := which(g.Provider).Name
|
||||
if i, ok := at[g.Account]; ok {
|
||||
if a := &out.Accounts[i]; !slices.Contains(a.Providers, name) {
|
||||
a.Providers = append(a.Providers, name)
|
||||
}
|
||||
continue
|
||||
}
|
||||
at[g.Account] = len(out.Accounts)
|
||||
out.Accounts = append(out.Accounts, Account{ID: g.Account, Providers: []string{name}})
|
||||
}
|
||||
// what each is of: the rows of the filter, or, for the dimension the
|
||||
// filter has picked, of the rows without that pick
|
||||
sharesJSON := func(by map[string][]usage.Share) map[string][]Share {
|
||||
out := map[string][]Share{}
|
||||
for _, d := range usage.Dimensions {
|
||||
shares := []Share{}
|
||||
for _, s := range by[d] {
|
||||
ls := Share{Share: s, Name: s.ID}
|
||||
switch d {
|
||||
case "provider":
|
||||
a := which(s.ID)
|
||||
ls.Name, ls.Icon = a.Name, a.Icon
|
||||
case "agent":
|
||||
a := who(s.ID)
|
||||
ls.Name, ls.Icon = a.Name, a.Icon
|
||||
case "modelAt":
|
||||
// the model, and the provider it went to
|
||||
prov, model, _ := strings.Cut(s.ID, "/")
|
||||
a := which(prov)
|
||||
ls.Name, ls.Icon = model+" · "+a.Name, a.Icon
|
||||
}
|
||||
shares = append(shares, ls)
|
||||
}
|
||||
out[d] = shares
|
||||
}
|
||||
return out
|
||||
}
|
||||
out.By = sharesJSON(l.By)
|
||||
if l.ChartBy != nil {
|
||||
out.ChartBy = sharesJSON(l.ChartBy)
|
||||
}
|
||||
for _, s := range l.Computers {
|
||||
ls := Share{Share: s, Name: l.Names[s.ID]}
|
||||
if s.ID != usage.ThisComputer && ls.Name == "" {
|
||||
ls.Name = s.ID
|
||||
}
|
||||
out.Computers = append(out.Computers, ls)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OwnPage is l, a page filtered to the gateway key key's own calls, with
|
||||
// its filter lists cut to what those calls had: they are drawn from every
|
||||
// call in the period, and so would name the other keys, and the agents,
|
||||
// providers and accounts only someone else's calls reached.
|
||||
func OwnPage(l Ledger, key string) Ledger {
|
||||
l.CallerKeys = slices.DeleteFunc(l.CallerKeys, func(g Group) bool { return g.CallerKeyID != key })
|
||||
had := func(d string) map[string]bool {
|
||||
m := map[string]bool{}
|
||||
for _, s := range l.By[d] {
|
||||
m[s.ID] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
agents, providers := had("agent"), had("provider")
|
||||
l.Agents = slices.DeleteFunc(l.Agents, func(a Named) bool { return !agents[a.ID] })
|
||||
l.Providers = slices.DeleteFunc(l.Providers, func(a Named) bool { return !providers[a.ID] })
|
||||
accounts := map[string]bool{}
|
||||
for _, r := range l.Rows {
|
||||
accounts[r.Account()] = true
|
||||
}
|
||||
l.Accounts = slices.DeleteFunc(l.Accounts, func(a Account) bool { return !accounts[a.ID] })
|
||||
return l
|
||||
}
|
||||
@@ -116,7 +116,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"</
|
||||
<p><code>GET /v1/models</code> lists what the user has turned on: <code>id</code> (<code>provider/model</code>, or a routing group’s name, sent as it is), <code>display_name</code>, <code>owned_by</code> (the provider), <code>reasoning</code> and <code>supported_reasoning_levels</code> (<code>[{"effort":"low"},…]</code>), <code>context_window</code> and <code>max_output_tokens</code> when known, and <code>modalities</code> when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (<code>reasoning_effort</code>, <code>reasoning.effort</code>, Anthropic’s <code>thinking</code> or <code>output_config.effort</code>). <code>?format=text</code> gives the ids one a line.</p>
|
||||
|
||||
<h3>Optional</h3>
|
||||
<p>Send <code>X-Magpie-Session: <id></code> with a conversation’s requests and <code>GET /v1/magpie/route?session=<id></code> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with <code>after=<seq>&wait=<s></code>). <code>GET /v1/magpie/quotas</code> lists the user’s subscription allowances. Both answer only this machine, or another with a gateway key. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">reference</a> has the details.</p>
|
||||
<p>Send <code>X-Magpie-Session: <id></code> with a conversation’s requests and <code>GET /v1/magpie/route?session=<id></code> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with <code>after=<seq>&wait=<s></code>). <code>GET /v1/magpie/quotas</code> lists the user’s subscription allowances, and <code>GET /v1/magpie/usage</code> and <code>/v1/magpie/usage/requests</code> the Usage page’s numbers and its requests (with <code>session</code>, and <code>subagent</code>/<code>parent_agent</code> for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls alone. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">reference</a> has the details.</p>
|
||||
|
||||
<div class="callout"><b>Keep the user’s providers.</b> Add magpie as one more provider (named Magpie) beside the ones the user set up in your app, rather than replacing them, so turning magpie off is picking another provider.</div>
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"</
|
||||
<p><code>GET /v1/models</code> 列出用户打开的模型:<code>id</code>(<code>provider/model</code>,或路由组的名字,原样发送即可)、<code>display_name</code>、<code>owned_by</code>(供应商)、<code>reasoning</code> 与 <code>supported_reasoning_levels</code>(<code>[{"effort":"low"},…]</code>),已知时还有 <code>context_window</code>、<code>max_output_tokens</code>,以及 magpie 知道是否支持图片时的 <code>modalities</code>。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(<code>reasoning_effort</code>、<code>reasoning.effort</code>、Anthropic 的 <code>thinking</code> 或 <code>output_config.effort</code>)。<code>?format=text</code> 每行一个 id。</p>
|
||||
|
||||
<h3>可选</h3>
|
||||
<p>在同一会话的请求里带上 <code>X-Magpie-Session: <id></code>,<code>GET /v1/magpie/route?session=<id></code> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 <code>after=<seq>&wait=<s></code> 长轮询)。<code>GET /v1/magpie/quotas</code> 列出用户各订阅的额度。两者只回答本机,或带网关密钥的其他机器。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">参考文档</a>。</p>
|
||||
<p>在同一会话的请求里带上 <code>X-Magpie-Session: <id></code>,<code>GET /v1/magpie/route?session=<id></code> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 <code>after=<seq>&wait=<s></code> 长轮询)。<code>GET /v1/magpie/quotas</code> 列出用户各订阅的额度,<code>GET /v1/magpie/usage</code> 和 <code>/v1/magpie/usage/requests</code> 给出用量页的统计和逐条请求(带 <code>session</code>;Claude Code 子代理的调用还有 <code>subagent</code>/<code>parent_agent</code>)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">参考文档</a>。</p>
|
||||
|
||||
<div class="callout"><b>保留用户自己的供应商。</b>把 magpie 作为又一个供应商(名为 Magpie)加在用户已有的供应商旁边,而不是替换它们,这样关掉 magpie 就只是换选另一个供应商。</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user