Files
magpie/internal/provider/ruleparse.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

188 lines
5.7 KiB
Go

package provider
// A rule as it is typed: use=<model> tokens=200k images effort=high
// agents=a,b intent="…" compact — by magpie group rule and the TUI's routing page.
import (
"fmt"
"strconv"
"strings"
)
// ParseTokens reads 200000, 200k, 1.5m.
func ParseTokens(v string) (int, error) {
s := strings.ToLower(strings.TrimSpace(strings.ReplaceAll(v, "_", "")))
mul := 1.0
switch {
case strings.HasSuffix(s, "k"):
mul, s = 1e3, strings.TrimSuffix(s, "k")
case strings.HasSuffix(s, "m"):
mul, s = 1e6, strings.TrimSuffix(s, "m")
}
f, err := strconv.ParseFloat(s, 64)
if err != nil || f < 0 {
return 0, fmt.Errorf("tokens %q is not a length (200000, 200k, 1m)", v)
}
return int(f * mul), nil
}
// UnknownRuleWord starts the error for a word ParseRule doesn't know.
const UnknownRuleWord = "unknown "
// ParseRule makes a rule of k=v words; the model is resolved among the
// group's members. classifier is the group's classifier when one was
// given, at the place asked for (from 1) when one was.
func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err error) {
for _, w := range words {
k, v, hasV := strings.Cut(w, "=")
k = strings.ToLower(strings.TrimSpace(k))
switch k {
case "use", "model", "to":
id, err := GroupMember(g, v)
if err != nil {
return r, 0, "", err
}
r.Use = id
case "tokens", "context", "longer":
n, err := ParseTokens(v)
if err != nil {
return r, 0, "", err
}
r.Tokens = n
case "images", "image":
switch strings.ToLower(v) {
case "", "yes", "true", "on", "1":
r.Images = true
case "no", "false", "off", "0":
r.Images = false
default:
return r, 0, "", fmt.Errorf("images takes no value (or yes/no), not %q", v)
}
case "compact", "compacting", "compaction":
switch strings.ToLower(v) {
case "", "yes", "true", "on", "1":
r.Compact = true
case "no", "false", "off", "0":
r.Compact = false
default:
return r, 0, "", fmt.Errorf("compact takes no value (or yes/no), not %q", v)
}
case "effort", "reasoning", "thinking":
if !hasV {
v = "on"
}
r.Effort = strings.ToLower(strings.TrimSpace(v))
case "agents", "agent":
r.Agents = strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == ' ' })
case "intent", "asks", "about":
r.Intent = strings.TrimSpace(v)
if r.Intent == "" {
return r, 0, "", fmt.Errorf(`intent says what the message asks for: intent="writing or fixing tests"`)
}
case "classifier", "classify", "by":
if classifier = strings.TrimSpace(v); classifier == "" {
return r, 0, "", fmt.Errorf("classifier=<model>: the model that tells which intent a message is")
}
case "at":
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return r, 0, "", fmt.Errorf("at is a place from 1, not %q", v)
}
at = n
default:
return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, tokens, images, effort, agents, intent, compact, classifier, at)", w)
}
}
if r.Use == "" {
return r, 0, "", fmt.Errorf("use=<model> is missing: one of %s", strings.Join(g.Members, ", "))
}
if r.Intent != "" && classifier == "" && g.Classifier == "" {
return r, 0, "", fmt.Errorf("a rule with an intent needs the group's classifier, the model that tells which intent a message is: add classifier=<model>, best a small fast one")
}
return r, at, classifier, nil
}
// GroupMember is the group's member a typed model names: its id, its
// model id without the provider, or the model's last name — each with the
// effort fixed on the member ("m:high") or, when only one member is of
// that model, without it.
func GroupMember(g Group, in string) (string, error) {
in = strings.TrimPrefix(strings.TrimSpace(in), "magpie/")
plain := func(m string) string { model, _ := MemberEffort(m); return model }
for _, match := range []func(string) bool{
func(m string) bool { return m == in },
func(m string) bool { return strings.EqualFold(m, in) },
func(m string) bool { _, bare, _ := strings.Cut(m, "/"); return strings.EqualFold(bare, in) },
func(m string) bool { return strings.EqualFold(m[strings.LastIndex(m, "/")+1:], in) },
func(m string) bool { return strings.EqualFold(plain(m), in) },
func(m string) bool { _, bare, _ := strings.Cut(plain(m), "/"); return strings.EqualFold(bare, in) },
} {
var hits []string
for _, m := range g.Members {
if match(m) {
hits = append(hits, m)
}
}
switch len(hits) {
case 0:
continue
case 1:
return hits[0], nil
default:
return "", fmt.Errorf("%s is %s: name one", in, strings.Join(hits, " and "))
}
}
return "", fmt.Errorf("%s is not in %s (its models: %s)", in, g.ID, strings.Join(g.Members, ", "))
}
// RuleWords splits a typed line into its words, a "quoted" part in one:
// intent="a quick question".
func RuleWords(line string) []string {
var out []string
var w strings.Builder
quoted, some := false, false
for _, c := range line {
switch {
case c == '"':
quoted, some = !quoted, true
case !quoted && (c == ' ' || c == '\t'):
if some {
out = append(out, w.String())
}
w.Reset()
some = false
default:
w.WriteRune(c)
some = true
}
}
if some {
out = append(out, w.String())
}
return out
}
// Line is the rule as ParseRule reads it back.
func (r Rule) Line() string {
out := []string{"use=" + r.Use}
if r.Tokens > 0 {
out = append(out, fmt.Sprintf("tokens=%d", r.Tokens))
}
if r.Images {
out = append(out, "images")
}
if r.Effort != "" {
out = append(out, "effort="+r.Effort)
}
if len(r.Agents) > 0 {
out = append(out, "agents="+strings.Join(r.Agents, ","))
}
if r.Intent != "" {
out = append(out, `intent="`+strings.ReplaceAll(r.Intent, `"`, "")+`"`)
}
if r.Compact {
out = append(out, "compact")
}
return strings.Join(out, " ")
}