Files
magpie/internal/plugin/tools.go
T
yetone 091153bf71 idle: the loops following magpie's files wake on its own writes, not a 1-2s poll (#3185)
An idle `magpie serve` (no providers, no requests) woke 12-13 times a
second. A runtime trace showed the wakers were polling loops: the
middleware observer's refresh every 1s, pluginrt.KeepFresh's stat of five
files every 2s, OTel's session watch every 2s and its exporter tick every
5s, all with nothing to do.

Now filememo.Forget, which every write magpie makes of settings,
providers, sign-ins and caller keys already calls, also closes a channel
(filememo.Written). The plugins.json, tools and plugins.yml saves call it
too. The middleware observer, KeepFresh and OTel's session watch wait on
it, and look every filememo.OthersEvery (5s) only for what another
process (the CLI, a second magpie) wrote. Each takes the channel before
it looks, so a write made during a look isn't missed. middleware's
current() also reloads at once when filememo's generation moved, rather
than after its 1s skip. OTel's session watch waits 5s, not 2s, while
sessions aren't exported, and its exporter's timer runs only while a
batch holds something.

Measured: sandbox HOME, MAGPIE_ADDR=127.0.0.1:3481, `magpie serve`,
proc_pid_rusage (idle + interrupt wakeups) over 30s after 40s warm-up,
old (cec54c1d0) and new builds alternated:
  old  13.2 / 13.3 / 12.2 wakeups/s, 0.40 / 0.35 / 0.42 ms CPU/s
  new   7.9 /  8.6 wakeups/s,         0.22 / 0.30 ms CPU/s
What's left is the Go runtime itself, awake.Keep's 5s tick and the 5s
looks for other processes' writes.

Tests: TestKeepFreshFollowsPluginsYml now also runs KeepFresh with a 1h
interval and needs Set to apply at once; TestStrategiesFollowOwnWrite
needs a plugin turned off through plugin.SetOff to stop being served
within 2s, with no refresh by hand; TestWritten. With the Written cases
replaced by a nil channel, both of the first two went red (applied = 1,
want 0; still served 2s after). Run at this head: go test -count=1
-timeout 45m ./internal/filememo ./internal/plugin ./internal/pluginrt
./internal/middleware ./internal/otlp ./internal/settings
./internal/access: all ok. GOOS=linux and GOOS=windows go vet -tags
nogui ./internal/...: clean. gofmt -l internal: clean.

Not run: the full suite and internal/gateway's tests (gateway.go only
changes KeepFresh's interval argument, and it compiles under vet); the
macOS app with its window open (only headless serve was measured).
2026-10-25 23:45:34 +08:00

157 lines
4.3 KiB
Go

package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/steady"
)
// Tool is a tool a plugin gives: OpenCode's tool hook ({tool: {name:
// tool({description, args, execute})}}), which magpie offers every agent
// through its plugin tools MCP server (internal/gateway/tools_mcp.go).
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
// Schema is its arguments as JSON Schema, made in the host from its
// zod shape
Schema json.RawMessage `json:"schema,omitempty"`
}
// PluginTools are one plugin's tools.
type PluginTools struct {
Spec string `json:"spec"`
Tools []Tool `json:"tools"`
}
// Tools are the tools the plugins the host loaded give, in plugins.json's
// order, starting the host if need be.
func Tools(ctx context.Context) ([]PluginTools, error) {
loaded, err := Plugins(ctx)
if err != nil {
return nil, err
}
var out []PluginTools
for _, l := range loaded {
if l.Error == "" && len(l.Tools) > 0 {
out = append(out, PluginTools{Spec: l.Spec, Tools: l.Tools})
}
}
return out, nil
}
// ToolTimeout is how long a tool may run before its call is answered that
// it took too long. Agents give a tool call as little as 60 s (the MCP
// SDK's request timeout), so it ends a little before that.
var ToolTimeout = 55 * time.Second
// RunTool runs the plugin spec's tool name with args (a JSON object) in
// the host: its answer as text. agent is the agent that called it, as the
// tool's context names it.
func RunTool(ctx context.Context, spec, name string, args json.RawMessage, agent string) (string, error) {
if len(args) == 0 || string(args) == "null" {
args = json.RawMessage("{}")
}
var out struct {
Text string `json:"text"`
}
err := callWithTimeout(ctx, "tool", map[string]any{
"spec": spec, "name": name, "args": args, "agent": agent,
"ms": ToolTimeout.Milliseconds(),
}, &out, ToolTimeout+5*time.Second)
if errors.Is(err, context.DeadlineExceeded) {
return "", fmt.Errorf("%s took longer than %s", name, ToolTimeout)
}
return out.Text, err
}
// toolsPath is where the tools the host last loaded are noted, by plugin:
// the Plugin tools plugin's InUse reads it, which mustn't start the host.
func toolsPath() string { return filepath.Join(settings.Dir(), "plugin-tools.json") }
// ToolsPath is the note ToolsOn reads, which the gateway watches.
func ToolsPath() string { return toolsPath() }
var toolsMu sync.Mutex
// noteTools notes which plugins the host loaded give tools, written whole.
func noteTools(loaded []Loaded) {
m := map[string][]string{}
for _, l := range loaded {
if l.Error != "" || len(l.Tools) == 0 {
continue
}
names := make([]string, 0, len(l.Tools))
for _, t := range l.Tools {
names = append(names, t.Name)
}
m[l.Spec] = names
}
b, _ := json.MarshalIndent(m, "", " ")
toolsMu.Lock()
defer toolsMu.Unlock()
old, err := steady.ReadFile(toolsPath())
if err == nil && strings.TrimSpace(string(old)) == strings.TrimSpace(string(b)) {
return
}
if len(m) == 0 && errors.Is(err, fs.ErrNotExist) {
return
}
defer filememo.Forget() // the gateway follows this note (Written)
if err := writeWhole(toolsPath(), append(b, '\n')); err != nil {
log.Printf("plugin tools: noting them: %v", err)
}
}
// ToolsOn counts the plugins on in plugins.json that gave tools when the
// host last loaded them. A note that can't be read or parsed is an error:
// not known.
func ToolsOn() (int, error) {
b, err := steady.ReadFile(toolsPath())
if errors.Is(err, fs.ErrNotExist) {
return 0, nil
}
if err != nil {
return 0, err
}
var m map[string][]string
if err := json.Unmarshal(b, &m); err != nil {
return 0, fmt.Errorf("%s: %w", toolsPath(), err)
}
n := 0
for _, e := range Load().Plugins {
if !e.Off && len(m[e.Spec]) > 0 {
n++
}
}
return n, nil
}
// ToolNames are the tools noted for each plugin, by spec, sorted: what the
// Plugins page shows for a plugin whose host isn't running.
func ToolNames() map[string][]string {
b, err := steady.ReadFile(toolsPath())
if err != nil {
return nil
}
var m map[string][]string
if json.Unmarshal(b, &m) != nil {
return nil
}
for _, v := range m {
sort.Strings(v)
}
return m
}