Files
magpie/groups_rules_cli.go
T
yetone 3fe2ff9958 rules: a routing group's rule can be for the agent compacting its conversation, so a cheaper, faster model writes the summary while the conversation stays on its own (X, MR.Guo: 希望 Magpie 能像 OpenCode 一样支持单独指定 context compression model:当 Agent 需要做上下文压缩时…指定一个更便宜、更快的小模型专门负责总结和压缩历史上下文) — a compaction went to whatever model the conversation was on, the priciest in the group as often as not, and a long session paid for each summary at that price. A rule's new condition, compact (provider.Rule.Compact, "compacting"; magpie group rule add <group> use=<model> compact, compact=yes|no; the GUI editor's 压缩上下文时 / compacting toggle; the TUI hint), matches a request that is an agent compacting, told from the agent's own prompt (internal/gateway/compacting.go, read from each one's release): the system prompt of Claude Code 2.1's /compact and auto-compact, OpenCode's compaction agent, Pi, Gemini CLI's state_snapshot and Qwen Code, or the last user message of Claude Code's, Codex's (and magpie's own for a Codex compaction_trigger) and Kimi Code's; a prompt only quoted earlier in a conversation doesn't count. Only in a group with such a rule is a request looked at this way, so nothing else changes. A compaction is decided on its own, never held by the turn's rule, its classifier never asked; it isn't remembered for the turn, and neither the conversation's affinity nor the turn's size is taken from its answer, so the requests after it go on on the model the turn was on and its cache (without that, the next request of a Claude Code turn followed the summary to the cheap model). A member whose context is less than the compaction is passed over for the next rule that matches, or the group's order (RuleHit.Small). The trace tells it ("The agent is compacting the conversation, so rule 1 sends the summary to …", the models passed over named), and the editor notes a compact rule's model taking less than another member. Docs: start#rules (en, zh). Tested: internal/gateway/compacting_test.go — each agent's prompt taken, a plain and a quoted one not; in a group with rules compact→a/small and tokens≥2000→b/big, a long Claude Code turn on b, its /compact to a (Compact, N=1), the turn's next request back on b held, Codex's compaction to a too; a 70k-token compaction skipping a (64k) for rule 2 with Small [a/small]; a group with no compact rule routing a compaction as before; ParseRule/Line/Conditions/Matches for compact. TestRuleCompact failed with the affinity kept from the summary. internal/gui/tests/routing-compact.test.cjs, Chromium and WebKit, en and zh: the compaction in the trace, the rule's words, the toggle on and off with nothing moved, the room note, a compacting-only rule saved as compact:true and not refused. routing-kind/served/signin/steady, click-scroll and old-webkit pass. go vet, go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass. Not tried against real agents' compactions through the gateway (the prompts are matched as read from their releases) nor in the real Wails window.
2026-09-30 10:24:18 +08:00

179 lines
6.8 KiB
Go

package main
import (
"fmt"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// A group's rules from the terminal: magpie group rule add|rm|mv …, as the
// Routing view's Rules section makes them.
const ruleUsage = `usage:
magpie group rule <group> the group's rules
magpie group rule add <group> use=<model> [tokens=<n>] [images] [effort=on|low|medium|high|xhigh|max] [agents=a,b…]
[intent="<what the message asks for>"] [compact] [classifier=<model>] [at=<n>]
a rule: a turn that matches it goes to <model>, one of the group's
(or group/<id>, a group in it), first; a model in the group at an
effort of its own is named with it (use=glm/glm-5.3-flash:high)
magpie group rule rm <group> <n> remove rule n
magpie group rule mv <group> <n> <to> move rule n to place <to>
magpie group rule classifier <group> <model>
the model that tells which intent a message is, or
group/<id>: another group, its models tried in turn
Rules are looked at top first when you send a message (a new turn); the first that
matches puts its model first, and the group's others stay behind it if it fails.
The agent's tool results within the turn stay with the model the turn began on.
Every condition given must hold:
tokens the request is at least this long (200000, 200k, 1m): estimated from its size, or
what the vendor counted the conversation's last request as, whichever is more
images it carries an image, now or earlier in the conversation
effort the agent asked for reasoning: on (any), or at least this level
agents it comes from one of these agents (claude, codex, opencode, … as magpie usage names them)
intent the user's message is of this kind, in your words ("writing or fixing tests", "a quick
question"): as the turn begins, the group's classifier — any model magpie has, best a small
fast one without reasoning, or another group of them to fail over — is asked which of the intents that may match the message is,
once; if it fails or can't say, no intent matches. Its call shows in the usage as magpie's own
compact the agent is compacting the conversation (Claude Code's /compact or auto-compact, Codex's,
OpenCode's, Pi's, Gemini CLI's, Qwen Code's, Kimi's): a cheaper, faster model can write the
summary. The request is as long as the conversation, so a model known to take less is passed
over; it is not the turn's model, and the requests after it go on as before
e.g. magpie group rule add opus-anywhere use=openrouter/google/gemini-3-pro tokens=200k
magpie group rule add opus-anywhere use=a/vision-model images
magpie group rule add fast use=codex/gpt-5.6-sol:xhigh effort=high
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash intent="a quick question" classifier=groq/llama-3.1-8b-instant`
// parseTokens reads 200000, 200k, 1.5m.
func parseTokens(v string) (int, error) { return provider.ParseTokens(v) }
// parseRule makes a rule of k=v words (provider.ParseRule), an unknown
// word answered with the usage.
func parseRule(g provider.Group, words []string) (provider.Rule, int, string, error) {
r, at, classifier, err := provider.ParseRule(g, words)
if err != nil && strings.HasPrefix(err.Error(), provider.UnknownRuleWord) {
err = fmt.Errorf("%w\n\n%s", err, ruleUsage)
}
return r, at, classifier, err
}
// groupMember is the group's member a typed model names.
func groupMember(g provider.Group, in string) (string, error) { return provider.GroupMember(g, in) }
// ruleCmd: magpie group rule …
func ruleCmd(args []string) error {
if len(args) == 0 || slices.Contains([]string{"help", "-h", "--help"}, args[0]) {
fmt.Println(ruleUsage)
return nil
}
verb, rest := args[0], args[1:]
if len(rest) == 0 {
// magpie group rule <group>: the group, its rules with it
if g, err := findGroup(verb); err == nil {
if len(g.Rules) == 0 {
fmt.Println(muted.Render(" " + g.ID + " has no rules · magpie group rule add " + g.ID + " use=<model> …"))
return nil
}
return showGroup(g)
}
return fmt.Errorf("%s", ruleUsage)
}
g, err := findGroup(rest[0])
if err != nil {
return err
}
if g.Hidden {
return fmt.Errorf("%s was removed: magpie group restore %s brings it back first", g.ID, g.ID)
}
place := func(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil || n < 1 || n > len(g.Rules) {
if len(g.Rules) == 0 {
return 0, fmt.Errorf("%s has no rules", g.ID)
}
return 0, fmt.Errorf("rule %s: %s has rules 1 to %d", s, g.ID, len(g.Rules))
}
return n - 1, nil
}
switch verb {
case "add", "new":
r, at, classifier, err := parseRule(g, rest[1:])
if err != nil {
return err
}
if classifier != "" {
g.Classifier = classifier
}
if at == 0 || at > len(g.Rules) {
g.Rules = append(g.Rules, r)
} else {
g.Rules = slices.Insert(g.Rules, at-1, r)
}
case "rm", "remove", "delete":
if len(rest) != 2 {
return fmt.Errorf("magpie group rule rm <group> <n>")
}
i, err := place(rest[1])
if err != nil {
return err
}
g.Rules = slices.Delete(g.Rules, i, i+1)
case "mv", "move":
if len(rest) != 3 {
return fmt.Errorf("magpie group rule mv <group> <n> <to>")
}
i, err := place(rest[1])
if err != nil {
return err
}
j, err := place(rest[2])
if err != nil {
return err
}
r := g.Rules[i]
g.Rules = slices.Insert(slices.Delete(g.Rules, i, i+1), j, r)
case "classifier", "classify":
if len(rest) != 2 {
return fmt.Errorf("magpie group rule classifier <group> <model>")
}
if !slices.ContainsFunc(g.Rules, func(r provider.Rule) bool { return r.Intent != "" }) {
return fmt.Errorf("%s has no rule with an intent to classify for", g.ID)
}
g.Classifier = rest[1]
default:
return fmt.Errorf("magpie group rule has no %q\n\n%s", verb, ruleUsage)
}
if err := provider.SaveGroup(g); err != nil {
return err
}
g, err = findGroup(g.ID)
if err != nil {
return err
}
fmt.Println(green.Render("✓"), "saved", bold.Render(g.Name))
return showGroup(g)
}
// ruleLine is a rule as magpie group shows it.
func ruleLine(r provider.Rule) string {
return strings.Join(r.Conditions(), " · ") + muted.Render(" → ") + r.Use
}
// pruneRules drops the rules for models no longer in the group, saying so.
func pruneRules(g *provider.Group) {
var keep []provider.Rule
for i, r := range g.Rules {
if slices.Contains(g.Members, r.Use) {
keep = append(keep, r)
} else {
fmt.Println(amber.Render("!"), fmt.Sprintf("rule %d is removed with %s", i+1, r.Use))
}
}
g.Rules = keep
}