routing: a rule can match the system prompt or the last user message, by words or a regex, with no model asked (SucroseMoE on X)
SucroseMoE asked for routing on plain string and regex matches instead
of an intent model: `system[0] matches /^你是对话标题命名/` → model A,
`user[-1] matches /^正在上下文压缩/` → model B, so any harness's title
and compaction calls can be routed without a classifier.
Two new rule condition fields, beside message/effort/subagent/agent:
- system: any block of the system prompt as the agent sent it (Anthropic
system blocks, Chat system/developer messages, Responses instructions
and system/developer items, Gemini systemInstruction). Any block, not
only the first, because Claude Code's first block is its billing
header.
- last: any text of the request's last user message as sent, reminders
the agent adds included, so an anchored ^ still meets a compaction ask.
Ops for both: contains, doesn't contain, starts with, matches (regex,
case-insensitive; a value written /…/ has its slashes dropped). The
gateway reads system and last only when a rule asks (RulesRead), and
decodes raw system JSON lazily then. Like every rule, the decision is
made as a turn starts and its tool rounds keep it.
GUI: Routing → group → Rules, "+" on a rule row offers "System prompt text"
and "Last user message" pills (no modal), with tooltips, placeholders
and the bad-regex mark; zh, zh-TW, ja, de. CLI: `--when "system matches
^You are"`, with aliases system[0], user[-1], last-user. TUI hint, docs
(gateway-routing.md, site start pages) say the same.
Ran, on mote (macOS) until its sshd began refusing connections: gofmt
-l internal/ clean, go vet of provider/gateway/cli/tui, the rule tests;
the routing GUI files (routing-rule*, routing-rules-line,
routing-pause*, group-*, i18n-*, routing-compact, routing-intent-*,
routing-smart-intent) in chromium and webkit: 751 of 781, the 30 reds
being "System prompt" taken by a core word (now "System prompt text"),
routing-rules-line's + menu count (now with system and last), and
routing-intent-entry, red on main since 01a260af4 (#5392, next commit).
Then on the Linux box (wsl-run, magpie-desktop): go vet -tags nogui and
GOOS=windows go vet of the same packages; go test -tags nogui of
internal/provider, gateway, cli, tui, gui; node --check of the routing
plugin; routing-rule-ops, routing-rules-line, routing-intent-entry,
i18n-keys, i18n-en-no-cjk, routing-rule-example in chromium and webkit,
the new test 16 of 16 over four repeats.
Broken by hand: holdsIn's system/last cases returning false turns
TestCondHolds and 8 of TestRuleSystemAndLastText's cases red; dropping
the Anthropic system wiring turns its two Anthropic cases (one the real
Claude Code system fixture) red.
Not tried: a real harness's title or compaction request end to end
through a live gateway; the fixtures are Claude Code's, Codex's and pi's
recorded system prompts.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -82,6 +82,11 @@ const ruleUsage = `usage:
|
||||
message contains, does not contain, starts with, matches (a regular expression):
|
||||
the user's own words as the turn begins, upper or lower case alike
|
||||
when="message contains run the tests"
|
||||
system contains, does not contain, starts with, matches: any block of the system
|
||||
prompt as the agent sent it (a title or compaction call's own prompt)
|
||||
when="system matches ^You are a title"
|
||||
last the same, over any text of the last user message as sent
|
||||
when="last starts with Summarize"
|
||||
|
||||
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
|
||||
|
||||
@@ -156,6 +156,9 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
|
||||
}
|
||||
r := &Request{Model: a.Model, System: stringOrText(a.System), MaxTokens: a.MaxTokens,
|
||||
Temp: a.Temperature, TopP: a.TopP, Stop: a.StopSequences, Stream: a.Stream, Fast: a.Speed == "fast"}
|
||||
if len(a.System) > 0 {
|
||||
r.systemRaw = []json.RawMessage{a.System}
|
||||
}
|
||||
if !facts {
|
||||
r.askedTTL = askedCacheTTL(&a)
|
||||
}
|
||||
|
||||
@@ -112,6 +112,7 @@ func readChat(body []byte, facts bool) (*Request, error) {
|
||||
switch m.Role {
|
||||
case "system", "developer":
|
||||
sys = append(sys, stringOrText(m.Content))
|
||||
r.systemRaw = append(r.systemRaw, m.Content)
|
||||
case "user":
|
||||
r.Messages = append(r.Messages, Message{Role: "user", Parts: chatParts(m.Content)})
|
||||
case "assistant":
|
||||
|
||||
@@ -266,6 +266,9 @@ func parseGemini(body []byte) (*Request, error) {
|
||||
}
|
||||
r := &Request{Model: g.Model, Stream: g.Stream}
|
||||
r.System = geminiText(g.SystemInstruction)
|
||||
if r.System != "" {
|
||||
r.systemParts = []string{r.System}
|
||||
}
|
||||
if gc := g.GenerationConfig; gc != nil {
|
||||
r.MaxTokens, r.Temp, r.TopP, r.Stop = gc.MaxOutputTokens, gc.Temperature, gc.TopP, gc.StopSequences
|
||||
if tc := gc.ThinkingConfig; tc != nil {
|
||||
|
||||
@@ -261,6 +261,15 @@ type Request struct {
|
||||
// it, for a rule's subagent condition. Other agents don't say.
|
||||
subagent bool
|
||||
|
||||
// systemParts: each block of the system prompt as the client sent it
|
||||
// (Anthropic's system blocks, a system or developer message, Responses'
|
||||
// instructions), before magpie adds to or joins them, for a rule's
|
||||
// system condition (SucroseMoE on X). systemRaw holds the ones still
|
||||
// as JSON (a string or text blocks), read only when a rule asks
|
||||
// (systemTexts): a Claude Code system prompt is tens of KB.
|
||||
systemParts []string
|
||||
systemRaw []json.RawMessage
|
||||
|
||||
Model string
|
||||
System string
|
||||
Messages []Message
|
||||
@@ -849,6 +858,52 @@ func text(parts []Part) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// systemTexts is each block of the system prompt as the client sent it
|
||||
// (systemParts, systemRaw).
|
||||
func (r *Request) systemTexts() []string {
|
||||
out := slices.Clone(r.systemParts)
|
||||
for _, raw := range r.systemRaw {
|
||||
var s string
|
||||
if decodeJSON(raw, &s) == nil {
|
||||
if s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
continue
|
||||
}
|
||||
var blocks []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if decodeJSON(raw, &blocks) == nil {
|
||||
for _, b := range blocks {
|
||||
if b.Text != "" && (b.Type == "text" || b.Type == "input_text") {
|
||||
out = append(out, b.Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// lastUserTexts is each text of the request's last user message as the
|
||||
// client sent it, the agent's reminders and all; none when that message
|
||||
// holds only tool results.
|
||||
func lastUserTexts(r *Request) []string {
|
||||
for i := len(r.Messages) - 1; i >= 0; i-- {
|
||||
if r.Messages[i].Role != "user" {
|
||||
continue
|
||||
}
|
||||
var out []string
|
||||
for _, p := range r.Messages[i].Parts {
|
||||
if p.Kind == Text && p.Text != "" {
|
||||
out = append(out, p.Text)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringOrText reads a JSON value that is either a string or an array of
|
||||
// {type:"text", text} blocks (Anthropic's system, tool results…).
|
||||
func stringOrText(raw json.RawMessage) string {
|
||||
|
||||
@@ -346,6 +346,9 @@ func readResponsesFor(body []byte, facts, keepInstructions bool) (*Request, erro
|
||||
TopP: q.TopP, Stream: q.Stream, Parallel: q.ParallelToolCalls, Fast: q.ServiceTier == "priority" || q.ServiceTier == "ultrafast", Ultrafast: q.ServiceTier == "ultrafast", Tier: q.ServiceTier, CacheKey: q.PromptCacheKey, Include: q.Include,
|
||||
ClientMetadata: sentRaw(q.ClientMetadata), AccessPrograms: q.AccessPrograms}
|
||||
r.Text, r.Format = textFormat(sentRaw(q.Text))
|
||||
if q.Instructions != "" {
|
||||
r.systemParts = []string{q.Instructions}
|
||||
}
|
||||
// a Responses client's turns go to Claude with hour-long cache marks,
|
||||
// unless it asked for its prompt to be kept in memory only
|
||||
r.hourMarks = q.PromptCacheRetention != "in_memory"
|
||||
@@ -388,6 +391,13 @@ func readResponsesFor(body []byte, facts, keepInstructions bool) (*Request, erro
|
||||
if !facts || role != "assistant" {
|
||||
parts = responsesParts(it.Content)
|
||||
}
|
||||
if it.Role == "system" || it.Role == "developer" {
|
||||
for _, p := range parts {
|
||||
if p.Kind == Text && p.Text != "" {
|
||||
r.systemParts = append(r.systemParts, p.Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
if keepInstructions && (it.Role == "system" || it.Role == "developer") {
|
||||
r.Messages = append(r.Messages, Message{Role: it.Role, Parts: parts})
|
||||
continue
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -114,3 +115,59 @@ func TestRuleMessageIsTheUsers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A rule's system and last conditions (SucroseMoE on X) read the
|
||||
// request's texts as the agent sent them, with no model asked: each block
|
||||
// of its system prompt, in every protocol, and each text of its last user
|
||||
// message. A harness's title or compaction call is told apart by its
|
||||
// prompt alone.
|
||||
func TestRuleSystemAndLastText(t *testing.T) {
|
||||
asGroup := func(body []byte) string {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(body, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m["model"], m["stream"] = "group/r", false
|
||||
delete(m, "thinking")
|
||||
delete(m, "reasoning")
|
||||
b, _ := json.Marshal(m)
|
||||
return string(b)
|
||||
}
|
||||
title := `{"model":"group/r","messages":[{"role":"system","content":"你是对话标题命名助手,用不超过十个字概括对话。"},{"role":"user","content":"帮我写一个排序函数"}]}`
|
||||
titleAnthropic := `{"model":"group/r","max_tokens":64,"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.296"},{"type":"text","text":"你是对话标题命名助手,用不超过十个字概括对话。"}],"messages":[{"role":"user","content":"帮我写一个排序函数"}]}`
|
||||
titleResponses := `{"model":"group/r","instructions":"你是对话标题命名助手。","input":[{"role":"user","content":"帮我写一个排序函数"}]}`
|
||||
titleDeveloper := `{"model":"group/r","input":[{"role":"developer","content":[{"type":"input_text","text":"你是对话标题命名助手。"}]},{"role":"user","content":"帮我写一个排序函数"}]}`
|
||||
said := `{"model":"group/r","messages":[{"role":"system","content":"You are a coding agent."},{"role":"user","content":"你是对话标题命名助手吗?"}]}`
|
||||
compact := `{"model":"group/r","messages":[{"role":"system","content":"You are a coding agent."},{"role":"user","content":"帮我写一个排序函数"},{"role":"assistant","content":"好的"},{"role":"user","content":[{"type":"text","text":"<system-reminder>todo</system-reminder>"},{"type":"text","text":"正在上下文压缩,请总结以上对话。"}]}]}`
|
||||
carryOn := `{"model":"group/r","messages":[{"role":"system","content":"You are a coding agent."},{"role":"user","content":"正在上下文压缩,请总结以上对话。"},{"role":"assistant","content":"好的"},{"role":"user","content":"接着写测试"}]}`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cond provider.Cond
|
||||
path string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{"chat system", provider.Cond{Field: "system", Op: "matches", Value: `/^你是对话标题命名/`}, "/v1/chat/completions", title, "kb"},
|
||||
{"anthropic's second block", provider.Cond{Field: "system", Op: "matches", Value: `^你是对话标题命名`}, "/v1/messages", titleAnthropic, "kb"},
|
||||
{"responses instructions", provider.Cond{Field: "system", Op: "matches", Value: `^你是对话标题命名`}, "/v1/responses", titleResponses, "kb"},
|
||||
{"responses developer", provider.Cond{Field: "system", Op: "starts", Value: "你是对话标题命名"}, "/v1/responses", titleDeveloper, "kb"},
|
||||
{"the user said it", provider.Cond{Field: "system", Op: "matches", Value: `^你是对话标题命名`}, "/v1/chat/completions", said, "ka"},
|
||||
{"claude code's own", provider.Cond{Field: "system", Op: "matches", Value: `^You are a Claude agent`}, "/v1/messages", asGroup(fixture(t, "claude-code-2.1.296.json")), "kb"},
|
||||
{"codex's own", provider.Cond{Field: "system", Op: "matches", Value: `^You are a coding agent running in the Codex CLI`}, "/v1/responses", asGroup(fixture(t, "codex-0.162.0.json")), "kb"},
|
||||
{"not in pi's", provider.Cond{Field: "system", Op: "contains", Value: "你是对话标题命名"}, "/v1/chat/completions", asGroup(fixture(t, "pi-1.1.0.json")), "ka"},
|
||||
{"compaction last", provider.Cond{Field: "last", Op: "matches", Value: `/^正在上下文压缩/`}, "/v1/chat/completions", compact, "kb"},
|
||||
{"compaction earlier", provider.Cond{Field: "last", Op: "matches", Value: `^正在上下文压缩`}, "/v1/chat/completions", carryOn, "ka"},
|
||||
{"system excludes", provider.Cond{Field: "system", Op: "excludes", Value: "标题"}, "/v1/chat/completions", compact, "kb"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, _, _ := ruled(t, provider.Rule{Use: "b/big", Where: []provider.Cond{tc.cond}})
|
||||
rec := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))
|
||||
r.Header.Set("x-session-id", tc.name)
|
||||
s.Handler().ServeHTTP(rec, r)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from "+tc.want) {
|
||||
t.Errorf("%d %.300s %+v", rec.Code, rec.Body.String(), lastRoute(s).Rule)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,9 +196,15 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a
|
||||
now := ruleClock()
|
||||
size := estimate(req)
|
||||
q := provider.RuleRequest{Tokens: size, Thinking: req.Thinking, Effort: req.Effort, Off: req.ThinkOff, Agent: agent, At: now, Subagent: req.subagent}
|
||||
if provider.RulesReadMessage(g.Rules) {
|
||||
if provider.RulesRead(g.Rules, "message") {
|
||||
_, q.Message = lastSaid(req, len(req.Messages)) // the user's own words, as the turn began
|
||||
}
|
||||
if provider.RulesRead(g.Rules, "system") {
|
||||
q.System = req.systemTexts()
|
||||
}
|
||||
if provider.RulesRead(g.Rules, "last") {
|
||||
q.Last = lastUserTexts(req)
|
||||
}
|
||||
for _, m := range req.Messages {
|
||||
if slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == Image }) {
|
||||
q.Images = true
|
||||
|
||||
@@ -1295,10 +1295,10 @@ function routingPage(part) {
|
||||
if ((m = /^effort (is not|is|≤) (\w+)$/.exec(c))) return whereText({ field: "effort", op: { "is not": "not", is: "is", "≤": "lte" }[m[1]], value: m[2] });
|
||||
if ((m = /^agent (is not|is) (.+)$/.exec(c))) return whereText({ field: "agent", op: m[1] === "is" ? "is" : "not", value: m[2].split("|").join(",") });
|
||||
if (c === "subagent" || c === "not subagent") return whereText({ field: "subagent", op: c === "subagent" ? "is" : "not" });
|
||||
if ((m = /^message (contains|doesn't contain|starts with|matches) (".*")$/.exec(c))) {
|
||||
let v = m[2];
|
||||
if ((m = /^(message|system|last) (contains|doesn't contain|starts with|matches) (".*")$/.exec(c))) {
|
||||
let v = m[3];
|
||||
try { v = JSON.parse(v); } catch { v = v.slice(1, -1); }
|
||||
return whereText({ field: "message", op: { contains: "contains", "doesn't contain": "excludes", "starts with": "starts", matches: "matches" }[m[1]], value: v });
|
||||
return whereText({ field: m[1], op: { contains: "contains", "doesn't contain": "excludes", "starts with": "starts", matches: "matches" }[m[2]], value: v });
|
||||
}
|
||||
if ((m = /^tokens ≥ (\d+)$/.exec(c))) return t("≥ {n} tokens", { n: Number(m[1]).toLocaleString(intlLang()) });
|
||||
if (c === "images") return t("has an image");
|
||||
@@ -5998,6 +5998,8 @@ function routingPage(part) {
|
||||
r.where = w;
|
||||
};
|
||||
const TOKEN_OPS = { gte: "≥", gt: ">", lt: "<", lte: "≤" };
|
||||
// the conditions that look for words in a text of the request
|
||||
const TEXT_FIELDS = ["message", "system", "last"];
|
||||
const MESSAGE_OPS = { contains: "has the words", excludes: "doesn't have the words", starts: "starts with the words", matches: "matches the expression" };
|
||||
function whereText(c) {
|
||||
const v = String(c.value ?? "");
|
||||
@@ -6014,6 +6016,8 @@ function routingPage(part) {
|
||||
}
|
||||
case "subagent": return c.op === "not" ? t("not sent by a subagent") : t("sent by a subagent");
|
||||
case "message": return t("message {op} “{text}”", { op: t(MESSAGE_OPS[c.op] || c.op), text: v });
|
||||
case "system": return t("system prompt {op} “{text}”", { op: t(MESSAGE_OPS[c.op] || c.op), text: v });
|
||||
case "last": return t("last user message {op} “{text}”", { op: t(MESSAGE_OPS[c.op] || c.op), text: v });
|
||||
}
|
||||
return [c.field, c.op, v].filter(Boolean).join(" ");
|
||||
}
|
||||
@@ -7901,6 +7905,8 @@ function routingPage(part) {
|
||||
const COND_KINDS = [
|
||||
["intent", "asks for", false],
|
||||
["message", "Message text", false],
|
||||
["system", "System prompt text", false],
|
||||
["last", "Last user message", false],
|
||||
["tokens", "Conversation length", false],
|
||||
["images", "has an image", false],
|
||||
["effort", "Reasoning level", false],
|
||||
@@ -7912,7 +7918,7 @@ function routingPage(part) {
|
||||
["time", "Hours and days", true],
|
||||
];
|
||||
// the field of a kind's conditions in the rule's where
|
||||
const KIND_FIELD = { tokens: "tokens", effort: "effort", agents: "agent", subagent: "subagent", message: "message" };
|
||||
const KIND_FIELD = { tokens: "tokens", effort: "effort", agents: "agent", subagent: "subagent", message: "message", system: "system", last: "last" };
|
||||
const condSet = (r, k) => {
|
||||
const c = KIND_FIELD[k] && whereOf(r, KIND_FIELD[k]);
|
||||
if (c && (k === "subagent" || String(c.value ?? "").trim())) return true;
|
||||
@@ -7925,7 +7931,7 @@ function routingPage(part) {
|
||||
openedOf(r).add(k);
|
||||
if (k === "images" || k === "compact") r[k] = true;
|
||||
if (k === "subagent") setWhere(r, "subagent", { op: "is" });
|
||||
if (k === "message" && !whereOf(r, "message")) setWhere(r, "message", { op: "contains", value: "" });
|
||||
if (TEXT_FIELDS.includes(k) && !whereOf(r, k)) setWhere(r, k, { op: "contains", value: "" });
|
||||
if (k === "intent" && !d.classifier && deciders.length) d.classifier = deciders[0].id;
|
||||
focusCond = { r, k };
|
||||
drawRules();
|
||||
@@ -8084,29 +8090,38 @@ function routingPage(part) {
|
||||
}
|
||||
// the message's own words, as the user wrote them when the turn
|
||||
// began: contains, doesn't contain, starts with, or a pattern
|
||||
if (kinds.includes("message")) {
|
||||
const mc = whereOf(r, "message") || (setWhere(r, "message", { op: "contains", value: "" }), whereOf(r, "message"));
|
||||
// a text of the request: the user's words as the turn began; or,
|
||||
// as the agent sent them (SucroseMoE on X: a harness's title or
|
||||
// compaction call told by its prompt, no model asked), a block of
|
||||
// its system prompt, or a text of its last user message
|
||||
for (const [k, cls, name, tip, eg, egRe] of [
|
||||
["message", "ms", "Message text", "The words the user wrote as the turn began, without what the agent adds to them; not case-sensitive", "e.g. run the tests", "^translate\\b"],
|
||||
["system", "sy", "System prompt text", "Any block of the system prompt, as the agent sent it; not case-sensitive", "e.g. title", "^You are"],
|
||||
["last", "lu", "Last user message", "Any text of the request's last user message, as the agent sent it, what the agent adds included; not case-sensitive", "e.g. summarize", "^Summarize"],
|
||||
]) {
|
||||
if (!kinds.includes(k)) continue;
|
||||
const mc = whereOf(r, k) || (setWhere(r, k, { op: "contains", value: "" }), whereOf(r, k));
|
||||
inPill.add(mc);
|
||||
const ms = el("span", "rt-cond ms");
|
||||
const ms = el("span", "rt-cond rt-tx " + cls);
|
||||
ms.onclick = (e) => { if (e.target === ms || e.target.tagName === "SPAN") mi.focus(); };
|
||||
ms.title = t("The words the user wrote as the turn began, without what the agent adds to them; not case-sensitive");
|
||||
ms.title = t(tip);
|
||||
const mi = input(mc.value || "", "");
|
||||
mi.maxLength = 500; // provider.MaxCondText
|
||||
const bad = () => { if (mc.op !== "matches") return false; try { new RegExp(mc.value); return false; } catch { return true; } };
|
||||
const look = () => {
|
||||
ms.classList.toggle("on", !!mc.value.trim());
|
||||
ms.classList.toggle("bad", bad());
|
||||
mi.placeholder = mc.op === "matches" ? "^translate\\b" : t("e.g. run the tests");
|
||||
mi.placeholder = mc.op === "matches" ? egRe : t(eg);
|
||||
fitBox(mi);
|
||||
};
|
||||
const mo = opBtn(t(MESSAGE_OPS[mc.op] || mc.op), Object.entries(MESSAGE_OPS).map(([v, w]) => ({ value: v, label: t(w), note: v === "matches" ? t("regular expression, any case") : "" })), () => mc.op,
|
||||
(v) => { mc.op = v; mo.textContent = t(MESSAGE_OPS[v]); look(); warn(); });
|
||||
mi.oninput = () => { mc.value = mi.value; look(); warn(); };
|
||||
mi.onkeydown = (e) => e.stopPropagation();
|
||||
ms.append(el("span", "", t("Message text")), mo, mi);
|
||||
ms.append(el("span", "", t(name)), mo, mi);
|
||||
look();
|
||||
wrap("message", ms);
|
||||
if (mine === "message") focus = () => mi.focus({ preventScroll: true });
|
||||
wrap(k, ms);
|
||||
if (mine === k) focus = () => mi.focus({ preventScroll: true });
|
||||
}
|
||||
// tokens: at least this long
|
||||
if (kinds.includes("tokens")) {
|
||||
@@ -8691,8 +8706,8 @@ function routingPage(part) {
|
||||
}
|
||||
// a condition left without its value is none (an emptied box)
|
||||
for (const r of d.rules) if (r.where) { r.where = r.where.filter((c) => c.field === "subagent" || String(c.value ?? "").trim() && !(c.field === "tokens" && !(+c.value > 0))); if (!r.where.length) delete r.where; }
|
||||
const badRe = d.rules.findIndex((r) => (r.where || []).some((c) => { if (c.field !== "message" || c.op !== "matches") return false; try { new RegExp(c.value); return false; } catch { return true; } }));
|
||||
if (badRe >= 0) return status(t("Rule {n}: what the message matches isn't a regular expression", { n: badRe + 1 }), "warn");
|
||||
const badRe = d.rules.findIndex((r) => (r.where || []).some((c) => { if (!TEXT_FIELDS.includes(c.field) || c.op !== "matches") return false; try { new RegExp(c.value); return false; } catch { return true; } }));
|
||||
if (badRe >= 0) return status(t("Rule {n}: what it matches isn't a regular expression", { n: badRe + 1 }), "warn");
|
||||
// a folder is a whole path (provider.cleanFolder)
|
||||
const badDir = d.rules.findIndex((r) => [...(r.folders || []), ...(r.exceptFolders || [])].some((f) => !/^(~$|~[\\/]|\/|\\\\|[A-Za-z]:([\\/]|$))/.test(f)));
|
||||
if (badDir >= 0) return status(t("Rule {n}: a folder is a whole path, like ~/work or /Users/me/work", { n: badDir + 1 }), "warn");
|
||||
|
||||
@@ -279,7 +279,15 @@ magpie.strings({
|
||||
"agent is none of": "Agent 不是",
|
||||
"Claude Code and Codex say when a subagent sends a turn; any other agent's turns count as not a subagent's": "Claude Code 和 Codex 会说明一轮是否由子代理发出;其他 Agent 的轮次都算作不是子代理",
|
||||
"the lead, or an agent that doesn't say": "主 Agent,或不说明的 Agent",
|
||||
"Rule {n}: what the message matches isn't a regular expression": "规则 {n}:消息匹配的不是有效的正则表达式",
|
||||
"System prompt text": "系统提示词内容",
|
||||
"Last user message": "最后一条用户消息",
|
||||
"system prompt {op} “{text}”": "系统提示词{op}“{text}”",
|
||||
"last user message {op} “{text}”": "最后一条用户消息{op}“{text}”",
|
||||
"Any block of the system prompt, as the agent sent it; not case-sensitive": "系统提示词的任意一段,按 Agent 发出的原样;不区分大小写",
|
||||
"Any text of the request's last user message, as the agent sent it, what the agent adds included; not case-sensitive": "请求中最后一条用户消息的任意一段文字,按 Agent 发出的原样,含 Agent 附加的内容;不区分大小写",
|
||||
"e.g. title": "例如 标题",
|
||||
"e.g. summarize": "例如 总结",
|
||||
"Rule {n}: what it matches isn't a regular expression": "规则 {n}:匹配的不是有效的正则表达式",
|
||||
"reasoning is off": "推理关闭",
|
||||
"1 rule": "1 条规则",
|
||||
"{n} rules": "{n} 条规则",
|
||||
@@ -1003,7 +1011,15 @@ magpie.strings({
|
||||
"agent is none of": "Agent 不是",
|
||||
"Claude Code and Codex say when a subagent sends a turn; any other agent's turns count as not a subagent's": "Claude Code 和 Codex 會說明一輪是否由子代理發出;其他 Agent 的輪次都算作不是子代理",
|
||||
"the lead, or an agent that doesn't say": "主 Agent,或不說明的 Agent",
|
||||
"Rule {n}: what the message matches isn't a regular expression": "規則 {n}:訊息符合的不是有效的正規表示式",
|
||||
"System prompt text": "系統提示詞內容",
|
||||
"Last user message": "最後一則使用者訊息",
|
||||
"system prompt {op} “{text}”": "系統提示詞{op}「{text}」",
|
||||
"last user message {op} “{text}”": "最後一則使用者訊息{op}「{text}」",
|
||||
"Any block of the system prompt, as the agent sent it; not case-sensitive": "系統提示詞的任一段,依 Agent 送出的原樣;不分大小寫",
|
||||
"Any text of the request's last user message, as the agent sent it, what the agent adds included; not case-sensitive": "請求中最後一則使用者訊息的任一段文字,依 Agent 送出的原樣,含 Agent 附加的內容;不分大小寫",
|
||||
"e.g. title": "例如 標題",
|
||||
"e.g. summarize": "例如 摘要",
|
||||
"Rule {n}: what it matches isn't a regular expression": "規則 {n}:符合的不是有效的正規表示式",
|
||||
"reasoning is off": "推理關閉",
|
||||
"1 rule": "1 條規則",
|
||||
"{n} rules": "{n} 條規則",
|
||||
@@ -1725,7 +1741,15 @@ magpie.strings({
|
||||
"agent is none of": "エージェント ≠",
|
||||
"Claude Code and Codex say when a subagent sends a turn; any other agent's turns count as not a subagent's": "Claude Code と Codex はサブエージェントが送ったターンかどうかを伝えます。ほかのエージェントのターンはサブエージェント以外として扱います",
|
||||
"the lead, or an agent that doesn't say": "リード、または伝えないエージェント",
|
||||
"Rule {n}: what the message matches isn't a regular expression": "ルール {n}: メッセージのマッチ条件が正規表現ではありません",
|
||||
"System prompt text": "システムプロンプト本文",
|
||||
"Last user message": "最後のユーザーメッセージ",
|
||||
"system prompt {op} “{text}”": "システムプロンプトが「{text}」{op}",
|
||||
"last user message {op} “{text}”": "最後のユーザーメッセージが「{text}」{op}",
|
||||
"Any block of the system prompt, as the agent sent it; not case-sensitive": "システムプロンプトのいずれかのブロック(エージェントが送ったまま)。大文字と小文字は区別しません",
|
||||
"Any text of the request's last user message, as the agent sent it, what the agent adds included; not case-sensitive": "リクエストの最後のユーザーメッセージのいずれかのテキスト(エージェントが送ったまま、付け加えた部分も含む)。大文字と小文字は区別しません",
|
||||
"e.g. title": "例: タイトル",
|
||||
"e.g. summarize": "例: 要約",
|
||||
"Rule {n}: what it matches isn't a regular expression": "ルール {n}: マッチ条件が正規表現ではありません",
|
||||
"reasoning is off": "推論オフ",
|
||||
"1 rule": "1 件のルール",
|
||||
"{n} rules": "{n} 件のルール",
|
||||
@@ -2449,7 +2473,15 @@ magpie.strings({
|
||||
"agent is none of": "Agent ist nicht",
|
||||
"Claude Code and Codex say when a subagent sends a turn; any other agent's turns count as not a subagent's": "Claude Code und Codex sagen, wann ein Subagent einen Turn sendet; Turns anderer Agents zählen als nicht von einem Subagent",
|
||||
"the lead, or an agent that doesn't say": "der Lead oder ein Agent, der es nicht sagt",
|
||||
"Rule {n}: what the message matches isn't a regular expression": "Regel {n}: Worauf die Nachricht passen soll, ist kein regulärer Ausdruck",
|
||||
"System prompt text": "Systemprompt-Text",
|
||||
"Last user message": "Letzte Nutzernachricht",
|
||||
"system prompt {op} “{text}”": "Systemprompt {op} „{text}“",
|
||||
"last user message {op} “{text}”": "letzte Nutzernachricht {op} „{text}“",
|
||||
"Any block of the system prompt, as the agent sent it; not case-sensitive": "Ein beliebiger Block des Systemprompts, wie der Agent ihn gesendet hat; Groß-/Kleinschreibung egal",
|
||||
"Any text of the request's last user message, as the agent sent it, what the agent adds included; not case-sensitive": "Ein beliebiger Text der letzten Nutzernachricht der Anfrage, wie der Agent ihn gesendet hat, samt seiner Zusätze; Groß-/Kleinschreibung egal",
|
||||
"e.g. title": "z. B. Titel",
|
||||
"e.g. summarize": "z. B. zusammenfassen",
|
||||
"Rule {n}: what it matches isn't a regular expression": "Regel {n}: Das Muster ist kein regulärer Ausdruck",
|
||||
"reasoning is off": "Reasoning aus",
|
||||
"1 rule": "1 Regel",
|
||||
"{n} rules": "{n} Regeln",
|
||||
|
||||
@@ -968,10 +968,10 @@ body.window .rt-gedit > .bar { --vfoot: 8px; }
|
||||
@media (hover: hover) and (pointer: fine) { .rt-op:hover { background: var(--pill-hover, var(--pill)); } }
|
||||
.rt-op:focus-visible { outline: none; background: var(--pill-hover, var(--pill)); }
|
||||
.rt-cond.ef { cursor: default; }
|
||||
.rt-cond.ms { cursor: text; }
|
||||
.rt-cond.ms > span { flex: none; }
|
||||
.rt-cond.ms > input { min-width: 0; flex: 0 1 auto; }
|
||||
.rt-cond.ms.bad { border-style: solid; border-color: var(--amber, var(--muted)); }
|
||||
.rt-cond.rt-tx { cursor: text; }
|
||||
.rt-cond.rt-tx > span { flex: none; }
|
||||
.rt-cond.rt-tx > input { min-width: 0; flex: 0 1 auto; }
|
||||
.rt-cond.rt-tx.bad { border-style: solid; border-color: var(--amber, var(--muted)); }
|
||||
/* the time zone a rule's hours are in, when the server's clock is another */
|
||||
.rt-zone { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
|
||||
.rt-cond[hidden] { display: none; }
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
// and one set to compare another way is saved as provider.Cond in where.
|
||||
// The group's card says the conditions. In every language, at a narrow
|
||||
// width with nothing run past the side.
|
||||
// SucroseMoE on X: a rule matches the system prompt or the last user
|
||||
// message as the agent sent them, by words or a regex, so a harness's
|
||||
// title or compaction call is routed with no model asked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -30,7 +33,13 @@ const ALL = [{ use: "b/other", where: [
|
||||
{ field: "tokens", op: "lt", value: "20000" }, { field: "effort", op: "not", value: "off" },
|
||||
{ field: "agent", op: "not", value: "codex" }, { field: "subagent", op: "is" },
|
||||
{ field: "message", op: "contains", value: "run the tests" },
|
||||
{ field: "system", op: "matches", value: "^你是对话标题命名" }, { field: "last", op: "starts", value: "正在上下文压缩" },
|
||||
] }];
|
||||
// a title call told by its system prompt, and a rule to add the rest to
|
||||
const SYS = [
|
||||
{ use: "b/other", where: [{ field: "system", op: "matches", value: "^你是对话标题命名" }] },
|
||||
{ use: "b/other", tokens: 1000 },
|
||||
];
|
||||
const groups = (rules) => ({
|
||||
models,
|
||||
groups: [{ id: "main", name: "Main", members: ["a/glm", "b/other"], routing: "order", ready: true,
|
||||
@@ -40,12 +49,14 @@ const groups = (rules) => ({
|
||||
|
||||
const words = {
|
||||
en: { card: "2. reasoning is not high → B · other", lt: "<", isNot: "≠", agentNot: "agent is none of", message: "Message text", subagent: "Subagent",
|
||||
startsWith: "starts with the words", notSub: "not sent by a subagent", sub: "sent by a subagent", contains: "has the words", save: "Save", add: "Add a rule" },
|
||||
startsWith: "starts with the words", notSub: "not sent by a subagent", sub: "sent by a subagent", contains: "has the words", save: "Save", add: "Add a rule",
|
||||
system: "System prompt text", last: "Last user message", matches: "matches the expression", sysCard: "system prompt matches the expression “^你是对话标题命名”" },
|
||||
zh: { card: "2. 推理不是 high → B · other", lt: "<", isNot: "≠", agentNot: "Agent 不是", message: "消息内容", subagent: "子代理",
|
||||
startsWith: "开头是", notSub: "不是子代理发出", sub: "子代理发出", contains: "包含", save: "保存", add: "添加规则" },
|
||||
"zh-TW": { isNot: "≠", agentNot: "Agent 不是", contains: "包含", sub: "子代理發出" },
|
||||
ja: { isNot: "≠", agentNot: "エージェント ≠", contains: "を含む", sub: "サブエージェントから" },
|
||||
de: { isNot: "≠", agentNot: "Agent ist nicht", contains: "enthält", sub: "von einem Subagent" },
|
||||
startsWith: "开头是", notSub: "不是子代理发出", sub: "子代理发出", contains: "包含", save: "保存", add: "添加规则",
|
||||
system: "系统提示词内容", last: "最后一条用户消息", matches: "匹配", sysCard: "系统提示词匹配“^你是对话标题命名”" },
|
||||
"zh-TW": { isNot: "≠", agentNot: "Agent 不是", contains: "包含", sub: "子代理發出", matches: "符合", startsWith: "開頭是" },
|
||||
ja: { isNot: "≠", agentNot: "エージェント ≠", contains: "を含む", sub: "サブエージェントから", matches: "にマッチ", startsWith: "で始まる" },
|
||||
de: { isNot: "≠", agentNot: "Agent ist nicht", contains: "enthält", sub: "von einem Subagent", matches: "passt auf", startsWith: "beginnt mit" },
|
||||
};
|
||||
const EDIT = { en: "Edit", zh: "编辑", "zh-TW": "編輯", ja: "編集", de: "Bearbeiten" };
|
||||
|
||||
@@ -196,6 +207,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await row.locator(".rt-addc").click();
|
||||
assert.equal(await page.locator(".proto-menu .pm-item", { hasText: w.message }).count(), 0);
|
||||
assert.equal(await page.locator(".proto-menu .pm-item", { hasText: w.subagent }).count(), 0);
|
||||
assert.equal(await page.locator(".proto-menu .pm-item", { hasText: w.system }).count(), 0);
|
||||
assert.equal(await page.locator(".proto-menu .pm-item", { hasText: w.last }).count(), 0);
|
||||
await page.keyboard.press("Escape");
|
||||
await press(page, page.locator(".rt-gedit button.primary", { hasText: w.save }));
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
@@ -203,6 +216,52 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual([save.body.rules[0].pause, save.body.rules[0].agents, save.body.rules[0].where], [true, [], [{ field: "agent", op: "not", value: "claude" }]]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: a rule matches the system prompt and the last user message`, async (t) => {
|
||||
const { page, group, errors, posts } = await open(engine, lang, 1100, t, SYS);
|
||||
const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n"));
|
||||
assert(title.includes(w.sysCard), `the card says the condition: ${title}`);
|
||||
|
||||
await press(page, group.locator("button", { hasText: EDIT[lang] }));
|
||||
const rows = page.locator(".rt-gedit .rt-rule");
|
||||
await rows.first().waitFor();
|
||||
const [r1, r2] = [rows.nth(0), rows.nth(1)];
|
||||
// saved as a pattern, it reads back as one
|
||||
assert.equal(await r1.locator(".rt-cond.sy .rt-op").textContent(), w.matches);
|
||||
assert.equal(await r1.locator(".rt-cond.sy input").inputValue(), "^你是对话标题命名");
|
||||
|
||||
// the last user message, from the + menu: starts with
|
||||
await press(page, r2.locator(".rt-addc"));
|
||||
await page.locator(".proto-menu .pm-item", { hasText: w.last }).click();
|
||||
const lu = r2.locator(".rt-cond.lu");
|
||||
await lu.locator("input").fill("正在上下文压缩");
|
||||
await lu.locator(".rt-op").click();
|
||||
assert.equal(await page.locator("select").count(), 0, "the app menu, not a native select");
|
||||
assert.equal(await page.locator("#list li").count(), 4);
|
||||
await pick(page, w.startsWith);
|
||||
assert.equal(await lu.locator(".rt-op").textContent(), w.startsWith);
|
||||
// the system prompt, a pattern: one that isn't shows so
|
||||
await press(page, r2.locator(".rt-addc"));
|
||||
await page.locator(".proto-menu .pm-item", { hasText: w.system }).click();
|
||||
const sy = r2.locator(".rt-cond.sy");
|
||||
await sy.locator(".rt-op").click();
|
||||
await pick(page, w.matches);
|
||||
await sy.locator("input").fill("(unclosed");
|
||||
assert.match(await sy.getAttribute("class"), /\bbad\b/);
|
||||
await sy.locator("input").fill("^You are");
|
||||
assert.doesNotMatch(await sy.getAttribute("class"), /\bbad\b/);
|
||||
assert.deepEqual(await overrun(page), []);
|
||||
|
||||
await press(page, page.locator(".rt-gedit button.primary", { hasText: w.save }));
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
|
||||
const save = posts.find((p) => p.path === "/api/groups/save");
|
||||
assert(save, `saved: ${JSON.stringify(posts)}`);
|
||||
const [s1, s2] = save.body.rules;
|
||||
assert.deepEqual(s1.where, [{ field: "system", op: "matches", value: "^你是对话标题命名" }], "kept as it was");
|
||||
assert.equal(s2.tokens, 1000);
|
||||
assert.deepEqual(s2.where, [{ field: "last", op: "starts", value: "正在上下文压缩" }, { field: "system", op: "matches", value: "^You are" }]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
// narrow, in every language: every field reads in its pill, nothing runs past
|
||||
for (const lang of Object.keys(words)) {
|
||||
@@ -216,6 +275,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal(await row.locator(".rt-aop").textContent(), words[lang].agentNot);
|
||||
assert.equal(await row.locator(".rt-sub").textContent(), words[lang].sub);
|
||||
assert.equal(await row.locator(".rt-cond.ms .rt-op").textContent(), words[lang].contains);
|
||||
assert.equal(await row.locator(".rt-cond.sy .rt-op").textContent(), words[lang].matches);
|
||||
assert.equal(await row.locator(".rt-cond.sy input").inputValue(), "^你是对话标题命名");
|
||||
assert.equal(await row.locator(".rt-cond.lu .rt-op").textContent(), words[lang].startsWith);
|
||||
assert.equal(await row.locator(".rt-more").count(), 0, "each in its own pill");
|
||||
if (process.env.SHOT) { await page.waitForTimeout(500); await row.scrollIntoViewIfNeeded(); await page.screenshot({ path: `${process.env.SHOT}/${engine}-${lang}-narrow.png` }); }
|
||||
assert.deepEqual(await overrun(page), []);
|
||||
|
||||
@@ -39,7 +39,7 @@ const groups = () => ({
|
||||
// the order a rule reads, as the editor draws its conditions
|
||||
const ORDER = ["intent", "tokens", "images", "effort", "compact", "agents", "folders", "exceptFolders", "time"];
|
||||
// the conditions a rule may ask besides (aipha2025 on X), which the + still offers
|
||||
const BESIDES = ["subagent", "message"];
|
||||
const BESIDES = ["subagent", "message", "system", "last"];
|
||||
|
||||
const words = {
|
||||
en: { edit: "Edit", save: "Save", image: "has an image", down: "Move down" },
|
||||
|
||||
@@ -479,7 +479,7 @@ func cleanRules(rules []Rule, members []string) ([]Rule, error) {
|
||||
case len([]rune(r.Intent)) > MaxIntent:
|
||||
return nil, fmt.Errorf("rule %d: an intent is at most %d characters", n, MaxIntent)
|
||||
case len(r.Conditions()) == 0:
|
||||
return nil, fmt.Errorf("rule %d: it needs a condition (tokens, images, effort, agents, subagent, message, intent, compacting, time or folders)", n)
|
||||
return nil, fmt.Errorf("rule %d: it needs a condition (tokens, images, effort, agents, subagent, message, system, last, intent, compacting, time or folders)", n)
|
||||
case r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact):
|
||||
return nil, fmt.Errorf("rule %d: a pause holds by hours, days, agents or folders only", n)
|
||||
}
|
||||
@@ -517,15 +517,19 @@ type RuleRequest struct {
|
||||
// be told.
|
||||
Subagent bool
|
||||
// Message is the user's own words at the turn's start, read only when
|
||||
// a rule has a message condition (RulesReadMessage).
|
||||
// a rule has a message condition (RulesRead).
|
||||
Message string
|
||||
// System is each block of the request's system prompt as the agent
|
||||
// sent it, and Last each text of its last user message, read only
|
||||
// when a rule has a system or last condition.
|
||||
System, Last []string
|
||||
}
|
||||
|
||||
// RulesReadMessage reports whether a rule of rules looks at the user's
|
||||
// message, which is then read for it.
|
||||
func RulesReadMessage(rules []Rule) bool {
|
||||
// RulesRead reports whether a rule of rules has a condition on field,
|
||||
// which is then read for it.
|
||||
func RulesRead(rules []Rule, field string) bool {
|
||||
return slices.ContainsFunc(rules, func(r Rule) bool {
|
||||
return slices.ContainsFunc(r.Where, func(c Cond) bool { return c.Field == "message" })
|
||||
return slices.ContainsFunc(r.Where, func(c Cond) bool { return c.Field == field })
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,12 @@ type Cond struct {
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// CondFields are the fields a condition can look at.
|
||||
var CondFields = []string{"tokens", "effort", "agent", "subagent", "message"}
|
||||
// CondFields are the fields a condition can look at. system and last
|
||||
// are the request's texts as the agent sent them (SucroseMoE on X: a
|
||||
// harness's title or compaction call told apart by its prompt, with no
|
||||
// model asked): system, each of its system prompt's blocks; last, each
|
||||
// text of its last user message.
|
||||
var CondFields = []string{"tokens", "effort", "agent", "subagent", "message", "system", "last"}
|
||||
|
||||
// CondOps are each field's ways to compare.
|
||||
var CondOps = map[string][]string{
|
||||
@@ -38,8 +42,14 @@ var CondOps = map[string][]string{
|
||||
"agent": {"is", "not"},
|
||||
"subagent": {"is", "not"},
|
||||
"message": {"contains", "excludes", "starts", "matches"},
|
||||
"system": {"contains", "excludes", "starts", "matches"},
|
||||
"last": {"contains", "excludes", "starts", "matches"},
|
||||
}
|
||||
|
||||
// textField reports whether a condition's field is a text it looks for
|
||||
// words in.
|
||||
func textField(f string) bool { return f == "message" || f == "system" || f == "last" }
|
||||
|
||||
// MaxCondText is how long a message condition's text may be, in
|
||||
// characters.
|
||||
const MaxCondText = 500
|
||||
@@ -101,16 +111,20 @@ func (c *Cond) clean() error {
|
||||
c.Value = strings.Join(agents, ",")
|
||||
case "subagent":
|
||||
c.Value = ""
|
||||
case "message":
|
||||
case "message", "system", "last":
|
||||
if c.Value = strings.TrimSpace(c.Value); c.Value == "" {
|
||||
return fmt.Errorf("a message condition needs the text it looks for")
|
||||
return fmt.Errorf("a %s condition needs the text it looks for", c.Field)
|
||||
}
|
||||
if len([]rune(c.Value)) > MaxCondText {
|
||||
return fmt.Errorf("a message condition's text is at most %d characters", MaxCondText)
|
||||
return fmt.Errorf("a %s condition's text is at most %d characters", c.Field, MaxCondText)
|
||||
}
|
||||
if c.Op == "matches" {
|
||||
// written as /…/, as in JavaScript
|
||||
if v := c.Value; len(v) > 2 && v[0] == '/' && v[len(v)-1] == '/' {
|
||||
c.Value = v[1 : len(v)-1]
|
||||
}
|
||||
if _, err := condRe(c.Value); err != nil {
|
||||
return fmt.Errorf("message matches %q: not a regular expression: %v", c.Value, err)
|
||||
return fmt.Errorf("%s matches %q: not a regular expression: %v", c.Field, c.Value, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,22 +198,48 @@ func (c Cond) Holds(q RuleRequest) bool {
|
||||
return !q.Subagent
|
||||
}
|
||||
case "message":
|
||||
msg, v := strings.ToLower(q.Message), strings.ToLower(c.Value)
|
||||
switch c.Op {
|
||||
case "contains":
|
||||
return strings.Contains(msg, v)
|
||||
case "excludes":
|
||||
return !strings.Contains(msg, v)
|
||||
case "starts":
|
||||
return strings.HasPrefix(strings.TrimSpace(msg), strings.TrimSpace(v))
|
||||
case "matches":
|
||||
re, err := condRe(c.Value)
|
||||
return err == nil && re.MatchString(q.Message)
|
||||
}
|
||||
return c.holdsIn([]string{q.Message})
|
||||
case "system":
|
||||
return c.holdsIn(q.System)
|
||||
case "last":
|
||||
return c.holdsIn(q.Last)
|
||||
}
|
||||
return false // a condition this magpie doesn't know never holds
|
||||
}
|
||||
|
||||
// holdsIn is a text condition over texts: it holds when one of them has
|
||||
// (starts with, matches) the words, and for excludes when none has them.
|
||||
func (c Cond) holdsIn(texts []string) bool {
|
||||
v := strings.ToLower(c.Value)
|
||||
var re *regexp.Regexp
|
||||
if c.Op == "matches" {
|
||||
var err error
|
||||
if re, err = condRe(c.Value); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, text := range texts {
|
||||
switch c.Op {
|
||||
case "contains", "excludes":
|
||||
if strings.Contains(strings.ToLower(text), v) {
|
||||
return c.Op == "contains"
|
||||
}
|
||||
case "starts":
|
||||
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(text)), strings.TrimSpace(v)) {
|
||||
return true
|
||||
}
|
||||
case "matches":
|
||||
if re.MatchString(text) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return c.Op == "excludes"
|
||||
}
|
||||
|
||||
// textOps are a text condition's ops as Text writes them.
|
||||
var textOps = map[string]string{"contains": "contains", "excludes": "doesn't contain", "starts": "starts with", "matches": "matches"}
|
||||
|
||||
// Text is the condition as a rule's conditions show it.
|
||||
func (c Cond) Text() string {
|
||||
switch c.Field {
|
||||
@@ -214,8 +254,8 @@ func (c Cond) Text() string {
|
||||
return "not subagent"
|
||||
}
|
||||
return "subagent"
|
||||
case "message":
|
||||
return "message " + map[string]string{"contains": "contains", "excludes": "doesn't contain", "starts": "starts with", "matches": "matches"}[c.Op] + " " + strconv.Quote(c.Value)
|
||||
case "message", "system", "last":
|
||||
return c.Field + " " + textOps[c.Op] + " " + strconv.Quote(c.Value)
|
||||
}
|
||||
return strings.TrimSpace(c.Field + " " + c.Op + " " + c.Value)
|
||||
}
|
||||
@@ -270,6 +310,10 @@ func ParseCond(s string) (Cond, error) {
|
||||
field = "effort"
|
||||
case "text", "content", "prompt":
|
||||
field = "message"
|
||||
case "system[0]", "sys", "instructions", "system-prompt":
|
||||
field = "system"
|
||||
case "user[-1]", "last-user", "lastuser", "last-message":
|
||||
field = "last"
|
||||
case "length", "context":
|
||||
field = "tokens"
|
||||
}
|
||||
|
||||
@@ -75,6 +75,21 @@ func TestCondHolds(t *testing.T) {
|
||||
{Cond{"message", "matches", `^fix .*bug$`}, RuleRequest{Message: "a bug to fix"}, false},
|
||||
{Cond{"message", "contains", "翻译"}, RuleRequest{Message: "帮我翻译这段"}, true},
|
||||
|
||||
// the system prompt's blocks and the last user message's texts
|
||||
// (SucroseMoE on X): one of them holds it
|
||||
{Cond{"system", "matches", `^你是对话标题命名`}, RuleRequest{System: []string{"x-anthropic-billing-header: cc_version=2", "你是对话标题命名助手,"}}, true},
|
||||
{Cond{"system", "matches", `^你是对话标题命名`}, RuleRequest{System: []string{"请注意:你是对话标题命名助手"}}, false},
|
||||
{Cond{"system", "matches", `^你是对话标题命名`}, RuleRequest{Message: "你是对话标题命名", Last: []string{"你是对话标题命名"}}, false},
|
||||
{Cond{"system", "starts", "You are"}, RuleRequest{System: []string{"billing", " you are a title namer"}}, true},
|
||||
{Cond{"system", "contains", "title"}, RuleRequest{System: []string{"a", "Make a TITLE"}}, true},
|
||||
{Cond{"system", "excludes", "title"}, RuleRequest{System: []string{"a", "Make a TITLE"}}, false},
|
||||
{Cond{"system", "excludes", "title"}, RuleRequest{System: []string{"a", "b"}}, true},
|
||||
{Cond{"system", "excludes", "title"}, RuleRequest{}, true},
|
||||
{Cond{"system", "contains", "title"}, RuleRequest{}, false},
|
||||
{Cond{"last", "matches", `^正在上下文压缩`}, RuleRequest{Last: []string{"<system-reminder>x</system-reminder>", "正在上下文压缩,请总结"}}, true},
|
||||
{Cond{"last", "matches", `^正在上下文压缩`}, RuleRequest{Message: "正在上下文压缩", System: []string{"正在上下文压缩"}}, false},
|
||||
{Cond{"last", "starts", "正在"}, RuleRequest{Last: []string{"好的,正在"}}, false},
|
||||
|
||||
{Cond{"weather", "is", "rain"}, RuleRequest{}, false}, // one this magpie doesn't know
|
||||
{Cond{"tokens", "eq", "1"}, RuleRequest{Tokens: 1}, false},
|
||||
} {
|
||||
@@ -148,6 +163,9 @@ func TestCleanRulesWhere(t *testing.T) {
|
||||
{Cond{"message", "contains", " "}, "needs the text"},
|
||||
{Cond{"message", "contains", strings.Repeat("x", MaxCondText+1)}, "at most"},
|
||||
{Cond{"message", "matches", "(unclosed"}, "not a regular expression"},
|
||||
{Cond{"system", "matches", "(unclosed"}, "system matches"},
|
||||
{Cond{"last", "contains", " "}, "a last condition needs the text"},
|
||||
{Cond{"system", "is", "x"}, "a system condition is"},
|
||||
} {
|
||||
_, err := cleanRules([]Rule{{Use: "a/m", Where: []Cond{tc.c}}}, members)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.err) || !strings.HasPrefix(err.Error(), "rule 1:") {
|
||||
@@ -196,6 +214,11 @@ func TestParseCond(t *testing.T) {
|
||||
"content starts with /review": {"message", "starts", "/review"},
|
||||
`message matches ^fix\b`: {"message", "matches", `^fix\b`},
|
||||
"message contains is not a thing ": {"message", "contains", "is not a thing"},
|
||||
"system matches ^你是对话标题命名": {"system", "matches", "^你是对话标题命名"},
|
||||
"system[0] matches /^你是对话标题命名/": {"system", "matches", "^你是对话标题命名"},
|
||||
"user[-1] matches /^正在上下文压缩/": {"last", "matches", "^正在上下文压缩"},
|
||||
"last starts with 正在上下文压缩": {"last", "starts", "正在上下文压缩"},
|
||||
"system does not contain title": {"system", "excludes", "title"},
|
||||
} {
|
||||
got, err := ParseCond(in)
|
||||
if err != nil || got != want {
|
||||
@@ -239,9 +262,9 @@ func TestParseRuleWhen(t *testing.T) {
|
||||
|
||||
// Conditions shows each as a list and a trace do.
|
||||
func TestWhereConditions(t *testing.T) {
|
||||
r := Rule{Use: "a/m", Where: []Cond{{"tokens", "lt", "20000"}, {"effort", "not", "off"}, {"agent", "not", "codex,opencode"}, {"subagent", "not", ""}, {"message", "excludes", "x"}}}
|
||||
r := Rule{Use: "a/m", Where: []Cond{{"tokens", "lt", "20000"}, {"effort", "not", "off"}, {"agent", "not", "codex,opencode"}, {"subagent", "not", ""}, {"message", "excludes", "x"}, {"system", "matches", "^你是"}, {"last", "starts", "正在"}}}
|
||||
got := strings.Join(r.Conditions(), "; ")
|
||||
if got != `tokens < 20000; effort is not off; agent is not codex|opencode; not subagent; message doesn't contain "x"` {
|
||||
if got != `tokens < 20000; effort is not off; agent is not codex|opencode; not subagent; message doesn't contain "x"; system matches "^你是"; last starts with "正在"` {
|
||||
t.Errorf("%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,7 +338,7 @@ func (m *model) openClassifier(g provider.Group) {
|
||||
const ruleHint = `use=<model>, and any of: tokens=200k · images · effort=on|low|medium|high|xhigh|max · agents=codex,claude
|
||||
intent="a quick question" (the group's classifier=<model> tells it) · compact
|
||||
time=09:00-18:00 (22:00-08:00 runs past midnight) · days=mon-fri · tz=Asia/Shanghai (this computer's zone if none) · folders=~/work/acme,~/oss · except-folders=~/old · at=<n> for its place
|
||||
when="effort is not off" · when="tokens < 20k" · when="agent is not codex" · when=subagent · when="message contains …"
|
||||
when="effort is not off" · when="tokens < 20k" · when="agent is not codex" · when=subagent · when="message contains …" · when="system matches ^You are a title"
|
||||
use-effort=low|medium|high|xhigh|max: the reasoning the model is asked for, whatever the agent asked
|
||||
or pause=<model> time=… days=… agents=… folders=… except-folders=…: the model is left out of the group then, not even a fallback`
|
||||
|
||||
|
||||
@@ -248,6 +248,7 @@ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,<span class
|
||||
magpie group rule add opus-anywhere pause=copilot/claude-opus-5.5 time=14:00-18:00 days=mon-fri <span class="c"># その時間帯は外す</span>
|
||||
magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task <span class="c"># ~/big-task のタスク専用:ほかのフォルダでは外す</span>
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when=<span class="s">"effort is off"</span> when=<span class="s">"not subagent"</span> <span class="c"># 推論オフでサブエージェントでないリクエスト</span>
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when=<span class="s">"system matches ^你是对话标题命名"</span> <span class="c"># システムプロンプトでタイトル生成リクエストを見分ける</span>
|
||||
magpie group set coder models+=group/opus-anywhere <span class="c"># グループの中のグループ</span>
|
||||
magpie group rule opus-anywhere <span class="c"># ルール一覧。rule rm|mv <n>、rule classifier <group> <model></span>
|
||||
magpie group copy opus-anywhere <span class="s">"Opus test"</span> <span class="c"># モデル・ルーティング・ルールが同じ複製。別々に変更できる</span>
|
||||
|
||||
@@ -248,6 +248,7 @@ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,<span class
|
||||
magpie group rule add opus-anywhere pause=copilot/claude-opus-5.5 time=14:00-18:00 days=mon-fri <span class="c"># left out in those hours</span>
|
||||
magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task <span class="c"># the model kept for the task in ~/big-task: left out of every other folder</span>
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when=<span class="s">"effort is off"</span> when=<span class="s">"not subagent"</span> <span class="c"># reasoning off, not a subagent</span>
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when=<span class="s">"system matches ^你是对话标题命名"</span> <span class="c"># a harness's title call, told by its system prompt</span>
|
||||
magpie group set coder models+=group/opus-anywhere <span class="c"># a group in a group</span>
|
||||
magpie group rule opus-anywhere <span class="c"># its rules; rule rm|mv <n>, rule classifier <group> <model></span>
|
||||
magpie group copy opus-anywhere <span class="s">"Opus test"</span> <span class="c"># the same models, routing and rules, to change on its own</span>
|
||||
|
||||
@@ -248,6 +248,7 @@ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,<span class
|
||||
magpie group rule add opus-anywhere pause=copilot/claude-opus-5.5 time=14:00-18:00 days=mon-fri <span class="c"># 这段时间不用它</span>
|
||||
magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task <span class="c"># 只留给 ~/big-task 里的任务:其他文件夹不用它</span>
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when=<span class="s">"effort is off"</span> when=<span class="s">"not subagent"</span> <span class="c"># 关了推理、又不是子代理的请求</span>
|
||||
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when=<span class="s">"system matches ^你是对话标题命名"</span> <span class="c"># 按系统提示词认出标题命名请求,不用模型判断</span>
|
||||
magpie group set coder models+=group/opus-anywhere <span class="c"># 路由组里放路由组</span>
|
||||
magpie group rule opus-anywhere <span class="c"># 查看规则;rule rm|mv <n>,rule classifier <组> <模型> 换判断模型</span>
|
||||
magpie group copy opus-anywhere <span class="s">"Opus test"</span> <span class="c"># 复制一份:模型、路由方式和规则都一样,可单独修改</span>
|
||||
|
||||
Reference in New Issue
Block a user