Files
magpie/internal/usage/probes.go
T
yetone 1bbaded622 usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as
magpie-image's generate_image, generate_video and generation_result, in
Routing > Requests.

Each tools/call to magpie's own MCP servers (image, vision, web search,
tools and the Library hub) is now a row of the request log. The row has
Source and Kind "mcp", the tool as its model, the server as its host,
how long the call took, and its error if it failed. The provider and
model it shows are those of the model requests the call made, collected
through the request's context in appendUsage. generation_result names
the model of the job it answers. The stdio Magpie Image server reports
each call it answered to the gateway as "magpie/toolCalled". That report
carries the tool, ms, model and error, never the prompt.

The arguments are never stored at all, so there is nothing to mask. The
rows go down the probe lane: they are listed, but no total, host list,
budget or key limit counts them. The model requests a call made are rows
of their own.

In the GUI the row reuses the Requests list. It gets a muted "MCP" badge
with a tooltip, the server beside the provider, and a Succeeded/Failed
status. The Purpose filter gains "MCP tool" in every language. There is
no new page, no <select> and no left border.

The core scripts went over their budget with the new purpose.
genpurposes now writes purposes.js as compact JSON, which makes the core
448 bytes smaller than main in all, and coreScriptBudget is lowered to
the new total, 1,538,975. No room is added.

Run on mote, at the rebased head:
- gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux
  and windows: ok.
- go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp,
  ./internal/usageapi and ./internal/gui ok. internal/budget has no test
  files. ./internal/gateway (805s): every test ok except five Antigravity
  and Codex/Grok tests. They fail the same on a clean origin/main
  3bebc3839 and are filed as #4362.
- GUI, the usage-ledger*, routing-request*, purpose*, i18n* and
  gui-zh/ja/de files (25). On mote, Chromium: 32 of 32 ok; WebKit
  could not launch (10 other sessions' suites on mote). On Linux
  (wsl-run), both engines: 335 of 355 ok. The 20 reds are
  routing-request-model, usage-ledger, -ttft, -chart and
  -open-settled, which fail the same at the parent 1534474c8 (#4120).
  usage-ledger-mcp, purpose-filter and i18n-keys are ok in both.
  The whole GUI suite runs after the push, and each red it finds gets
  an issue.
- At the pushed head, rebased on 0804f2d97: ./internal/gui (the
  budget and purpose asset tests among them), ./internal/usage,
  ./internal/imagemcp and ./internal/usageapi ok, and ./internal/gateway
  -run "MCP|Purpose|Probe" ok.
- usage-ledger-mcp.test.cjs covers 5 languages, widths 1180 and 420,
  light and dark, with no sideways scroll.

Broken by hand. Each break went red:
- sawHost's MCP skip removed: TestMCPCallRowsListedNotCounted (the hosts
  list had magpie-image).
- Row/Record.IsProbe's MCP case removed: the same test (3 calls counted),
  and TestMCPCallCountsInNoKeyLimit (Calls: 1).
- The callMCPTool hook removed: TestMCPToolCallIsARequestRow and its
  siblings (no rows).
- The appendUsage hook removed: the row had no provider or model.
- imagemcp's report removed: TestToolCallsAreReported.
- The gateway's magpie/toolCalled case removed:
  TestMCPCalledFromStdioIsARow.
budget's in-memory counts() now skips these rows too. Breaking only that
stays green, because budget.Of reads the file through usage.Visit, which
already skips probes, and limits count tokens and cost.

Not tried:
- no real agent calling a real vendor's drawing;
- no test run on Windows or Linux;
- the page not checked in the real app or in WebKitGTK.
A generate call that answers while its drawing still runs has no model on
its row. The generation_result row that follows names it.
2026-10-30 15:00:16 +08:00

176 lines
6.5 KiB
Go

package usage
import (
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/probelog"
"github.com/yetone/magpie/internal/provider"
)
// SourceProbe is Record.Source for a request magpie sent a provider on its
// own, outside any agent's turn (probelog): the editor's Test, Detect
// APIs, a model list's refresh. Its Kind says which (probelog.KindTest,
// KindDetect, KindList). Such a row is listed on the request log, told
// apart there, and counted nowhere: no total, cost, chart, group, budget,
// window hold or observer reads it. The log's index keeps it apart from
// the calls (logSnapshot.probes) so a reader of those never meets it.
const SourceProbe = "probe"
// SourceMCP is Record.Source for an agent's call to a tool of one of
// magpie's own MCP servers: the gateway's (image, vision, web search,
// plugin tools, the MCP hub) and the Magpie Image server an agent runs
// (ferock on Discord). Its Kind is KindMCP, Requested the tool's name as
// it was called, Host the server's, Provider and Model what the tool used
// when it used a model, Millis how long the call took and Error what a
// failed one said. Its arguments are never kept. It rides the probes'
// lane: listed on the request log, told apart there, counted nowhere, as
// the model requests the tool made are rows of their own that are.
const SourceMCP = "mcp"
// KindMCP is an MCP tool call's Kind, the purpose the request log picks
// them by.
const KindMCP = "mcp"
// IsProbe is a request magpie sent on its own (SourceProbe), or an MCP
// tool call (SourceMCP): a row listed and counted nowhere.
func (r Record) IsProbe() bool { return r.Source == SourceProbe || r.Source == SourceMCP }
// IsProbe is a row of such a request. A packed row keeps the row's Source,
// not its record's, so the request log asks the row.
func (r Row) IsProbe() bool {
return r.Source == SourceProbe || r.Source == SourceMCP || r.Record.IsProbe()
}
// probeRow is a probe's record and where its line ends in the log, as a
// gateway row's Order is.
type probeRow struct {
Record
off int64
}
func init() {
probelog.Sink = func(p probelog.Row) {
r := Record{Time: p.Time, Agent: "magpie", Provider: p.Provider, ProviderAccount: p.Account,
Host: p.Host, Model: p.Model, Requested: p.Model, Status: p.Status, Millis: p.Millis,
Error: clipProbeError(p.Error), Endpoint: p.Endpoint, Kind: p.Kind, Source: SourceProbe}
if quietProbe(r) {
return
}
Append(r)
}
}
// quietProbe is a request of magpie's own the request log leaves out: a
// model list that was answered. magpie asks for one by itself, at start-up,
// behind the panel and the Providers page, and on a schedule (a Remote
// magpie's every 10 minutes, RemoteMagpieEvery), so the Requests page
// filled with rows of 0 tokens that no agent sent (ferock on Discord). One
// that failed is listed, as is every Test and Detect APIs: a list that
// couldn't be fetched is why models are missing, and the row says why.
// Rows written before this are left out the same way as the log is read
// (logSnapshot.probes); the lines stay in the file, counted nowhere.
func quietProbe(r Record) bool {
return r.Kind == probelog.KindList && r.Status >= 200 && r.Status < 400 && r.Error == ""
}
// clipProbeError keeps an error's first 500 bytes, as a vendor's answer can
// be a whole page.
func clipProbeError(s string) string {
const most = 500
if len(s) <= most {
return s
}
cut := most
for cut > 0 && s[cut]&0xC0 == 0x80 { // not inside a character
cut--
}
return s[:cut] + "…"
}
// probeChunk is the probes made since since as one chunk of the request
// log's rows, each in the order its line has in the log as a gateway
// row's is; nil for none.
// A provider renamed since is listed by the id it has now (Renames): the
// Requests page's provider list named a renamed one twice (cybercaius).
// One asked while a provider was being added, under its host, is listed
// by the id of the provider on that host (Renames.ProbeOf), and once no
// provider is on it, a deleted one's, by the id the log's calls to that
// host were made under (hosts, logSnapshot.hosts): cybercaius on Discord,
// a deleted provider's tests were listed under its host beside its id.
// A host no provider was on goes by its site (provider.SiteOf) the same
// way: CyberCaius again, Leee's model list asked at leee.baby before it
// was saved on another host of that site.
func probeChunk(probes []probeRow, since time.Time, renames provider.Renames, hosts map[string]string) *rowChunk {
var c *rowChunk
sites := sync.OnceValue(func() map[string]string { return sitesOf(hosts) })
for _, p := range probes {
if !since.IsZero() && p.Time.Before(since) {
continue
}
if c == nil {
c = &rowChunk{}
}
r := p.Record
if r.Source == SourceMCP {
// a tool call names the provider its gateway call went to, by id
if r.Provider != "" {
r.Provider = renames.Of(r.Provider, r.Time)
}
c.add(Row{Record: r, Source: SourceMCP}, "", p.off, false)
continue
}
r.Provider = probeProvider(r, renames, hosts, sites)
c.add(Row{Record: r, Source: SourceProbe}, "", p.off, false)
}
if c == nil {
return nil
}
c.dict, c.shapeIDs = nil, nil
return c
}
// sitesOf is hosts by site (provider.SiteOf): the provider the log's
// calls to that site went to, "" for a site two providers' calls went to.
func sitesOf(hosts map[string]string) map[string]string {
out := map[string]string{}
for h, id := range hosts {
site := provider.SiteOf(h)
if site == "" {
continue
}
if to, ok := out[site]; ok && to != id {
id = ""
}
out[site] = id
}
return out
}
// probeProvider is the provider a probe row is listed under: its id as it
// is now, and for one recorded under its host before the provider had an
// id, the provider saved on that host, or, with none on it now, the one
// the log's calls to that host went to; with neither, the same by the
// host's site. A host or site two providers were on, or none, stays the
// host.
func probeProvider(r Record, renames provider.Renames, hosts map[string]string, sites func() map[string]string) string {
id := renames.ProbeOf(r.Provider, r.Time)
if id != r.Provider || !strings.EqualFold(r.Provider, r.Host) || renames.OnHost(r.Host) {
return id
}
if to := hosts[strings.ToLower(r.Host)]; to != "" {
return renames.Of(to, r.Time)
}
if to, on := renames.OnSite(r.Host); on {
if to != "" {
return to
}
} else if site := provider.SiteOf(r.Host); site != "" {
if to := sites()[site]; to != "" {
return renames.Of(to, r.Time)
}
}
return strings.ToLower(id) // one host, however it was typed
}