diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 78b68b788..8641c0daf 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -195,7 +195,7 @@ recorded as a prediction failure (`noPrediction`). - A rule can set the reasoning its member is asked for (`Rule.UseEffort`, `useEffort` in the group's JSON, `use-effort=low` typed; #2633, dengtongcai: an intent picks the model and the effort as a pair). It is an output like `Use`, not a condition like `Effort`. `ruleFor` copies it onto the hit (`RuleHit.UseEffort`) from the rule that put a member first, outer or nested; `ruleOver` keeps that rule's members, and `ruleEffort` gives each candidate of them the level fitted to its model's own (`fitLevel`), which `withFixedEffort` writes into the request's field for its protocol (Chat's `reasoning_effort`, Responses' `reasoning.effort`, Anthropic's thinking budget or `output_config.effort`) even when the agent asked none. A member fixed at an effort keeps its own; otherwise the rule's beats the model's suffix, the turn's pick and the agent's pick, and isn't bounded by the group's levels. A model whose levels aren't known (`Efforts` empty) is asked as the agent asked, as with the auto verdict. The members the group fails over to are asked it too (#3664): the effort is the turn's decision, so when the rule's own member is turned away the member that takes the request over is asked the same level, fitted to its model, rather than the agent's. A rule that names the candidate goes before one it only fails over from, and a nested group's rule decides for that group's members only: when the whole nested group fails, the outer group's member outside it is asked as the agent asked, or by the outer group's rule (`TestIntentEffortSurvivesTheGroupsFailover`, `TestNestedRuleEffortStaysInItsGroup`). A Gemini-protocol client's request is left as it came, as for every effort magpie sets. `cleanRules` refuses a value outside `provider.Efforts` and a pause with one. The try records it (`Try.RuleEffort`), and the Routing page says the rule set it. `rule_effort_test.go`, `grouprule_useeffort_test.go`, `routing-rule-effort.test.cjs`. - A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` or `Current working directory:` in the system prompt, and OpenCode's `Working directory:` inside its `` block. The caller's own layer — the system prompt and its `{role: "system"}` messages — is read whole, a `claude --bare` run's `CWD: ` among the forms; a user turn counts only for the forms a caller states in one (``, OpenCode's ``, Claude Code's ``, which says a folder it moved to): a working-directory line a user message quotes is no caller's word (#4940). Never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule). - A rule by agent (`Rule.Agents`, `agents=codex,sillytavern`) matches the agent the gateway names the request's (`agentOf` in [`gateway.go`](../../internal/gateway/gateway.go): its `magpie-` key, else its User-Agent), in lower case (`cleanRules`, `MatchesBesidesIntent`, `Pauses`). A client magpie doesn't know is named by its User-Agent's product name, before the first `/` or space (`usage.AgentOf`), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those `/api/usage?period=30d` heard from that it doesn't (not `other`, nor `magpie`), and takes a name typed in its filter as the gateway reads a User-Agent (`uaName` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), through the picker's `field.typed`): "MyApp/2.0 (Linux)" is `myapp`. `routing-rule-agent-typed.test.cjs`. - - A rule's field/op/value conditions (`Rule.Where`, `provider.Cond` in [`rulecond.go`](../../internal/provider/rulecond.go); `when="effort is not off"` on the command line; aipha2025 on X) say what the fields above can't, each of which must hold beside them. The fields and ops (`CondOps`): `tokens` ≥ > < ≤ a length; `effort` is / is not off, on or a level, and ≥ ≤ a level, where off is the agent turning reasoning off (`Request.ThinkOff`) or asking none, ≤ holds for off, and reasoning at no stated level is neither ≥ nor ≤ one; `agent` is / is not, as `Rule.Agents` reads agents; `subagent` is / is not, the request from a subagent its agent started, which only Claude Code (`x-claude-code-agent-id`, `subOf`) and Codex (`collab_spawn`) tell, set on `Request.subagent` where the rules' request is parsed, so another agent's subagent counts as not one; and `message` contains, doesn't contain, starts with or matches (a regular expression), upper or lower case alike, against the user's own words of the last user message that has any (`lastSaid`, so not an agent's reminders), read only when a rule has such a condition (`RulesReadMessage`). Like every other condition they are looked at as a turn begins, and the turn's tool rounds stay with what was decided. Old rules have no `where` and route as before; a magpie from before Where reads a rule of them alone as one with no condition, which matches nothing. A pause takes agent conditions only. A rule with any never lifts what the group tells agents it can take (`ruledEntry`). The Routing page edits them in the same pills: the tokens pill's ≥ is a menu of ≥ > < ≤, the reasoning pill's of ≥ = ≠ ≤ with off among its values, the agents pill's of "agent is one of" / "agent is none of", and Subagent and Message are kinds of their own in Add a condition (`whereOf`, `setWhere` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)); what the old fields can hold stays in them. The trace names a `where` condition from `Cond.Text` in the page's words (`condText`, then `whereText`). `TestCondHolds`, `TestParseCond`, `TestParseRuleWhen`, `TestRuleWithoutWhereUnchanged`, `TestRuleWhereDecides`, `TestRuleMessageIsTheUsers`, `routing-rule-ops.test.cjs`. + - A rule's field/op/value conditions (`Rule.Where`, `provider.Cond` in [`rulecond.go`](../../internal/provider/rulecond.go); `when="effort is not off"` on the command line; aipha2025 on X) say what the fields above can't, each of which must hold beside them. The fields and ops (`CondOps`): `tokens` ≥ > < ≤ a length; `effort` is / is not off, on or a level, and ≥ ≤ a level, where off is the agent turning reasoning off (`Request.ThinkOff`) or asking none, ≤ holds for off, and reasoning at no stated level is neither ≥ nor ≤ one; `agent` is / is not, as `Rule.Agents` reads agents; `subagent` is / is not, the request from a subagent its agent started, which only Claude Code (`x-claude-code-agent-id`, `subOf`) and Codex (`collab_spawn`) tell, set on `Request.subagent` where the rules' request is parsed, so another agent's subagent counts as not one; and `message` contains, doesn't contain, starts with or matches (a regular expression), upper or lower case alike, against the user's own words of the last user message that has any (`lastSaid`, so not an agent's reminders), read only when a rule has such a condition (`RulesRead`); `system` and `last` (SucroseMoE on X: a harness's title or compaction call told apart by its own prompt, no model asked) take the same ops against the request's texts as the agent sent them, and hold when one of them does (`excludes` when none does): `system` each block of the system prompt (`Request.systemParts`, `systemRaw`, read by `systemTexts` only when a rule asks: Anthropic's system blocks, so Claude Code's billing header is a block of its own; a Chat system or developer message; Responses' instructions and each system or developer item; Gemini's systemInstruction), `last` each text part of the last user message, reminders included (`lastUserTexts`; none when it holds only tool results). A regular expression may be written `/…/`. A request the turn's tool rounds hold (`turnIn`) keeps the turn's decision, so a `last` condition is met as the turn begins. Like every other condition they are looked at as a turn begins, and the turn's tool rounds stay with what was decided. Old rules have no `where` and route as before; a magpie from before Where reads a rule of them alone as one with no condition, which matches nothing. A pause takes agent conditions only. A rule with any never lifts what the group tells agents it can take (`ruledEntry`). The Routing page edits them in the same pills: the tokens pill's ≥ is a menu of ≥ > < ≤, the reasoning pill's of ≥ = ≠ ≤ with off among its values, the agents pill's of "agent is one of" / "agent is none of", and Subagent and Message are kinds of their own in Add a condition (`whereOf`, `setWhere` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)); what the old fields can hold stays in them. The trace names a `where` condition from `Cond.Text` in the page's words (`condText`, then `whereText`). `TestCondHolds`, `TestParseCond`, `TestParseRuleWhen`, `TestRuleWithoutWhereUnchanged`, `TestRuleWhereDecides`, `TestRuleMessageIsTheUsers`, `TestRuleSystemAndLastText`, `routing-rule-ops.test.cjs`. - A pause rule (`Rule.Pause`, `pause=`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause= except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`. - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing groups page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week), or at a fixed amount of a window counted in a unit with its total (`AccountWindowAmounts`, 9won_25273 on Discord: 300 of a day's 1000 credits; held once the window's count reaches it, `WindowCaps.limitShare`, `TestWindowAmountHoldsTheAccount`), and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. With every account held and no fallback left to take it, a request for a model the user put in routing groups of their own, asked bare (no provider in its id, or Codex's own model that `codexAccounts` put on `codex/`, `providerPicked`), goes on to those groups, in the user's order, each as its own routing orders it (`provider.GroupsAfter`, `groupsAfter`, planned again in serve with them after the fallbacks; a group magpie found, hidden or switched off, or one with no other member, is none). The Codex app signed in to ChatGPT asks Codex's own model, never the group built around it, so its capped account answered 429 though a group had two APIs after it (adorable_piglet on Discord, v0.1.3354; `TestCappedCodexOwnModelGoesToItsGroup`). A request that names the provider (`claude/claude-opus-5-5`, its flat or aliased spelling, another magpie's call) is that provider's alone (`namedProvider`): past the cap it goes to the provider's own fallbacks, else the cap's 429, never to a group that merely has the model in it (Anotiaww on X: a Claude account at its cap was answered by a WorkBuddy member of the user's group with nothing said; `TestNamedProviderCappedRefuses`). `CapStop` still answers the 429, and a request for the group itself was routed so before (`TestCappedSubscriptionGivesWayInGroup`). A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Planning goes by the last reading, so turns sent together were each planned on the same one: an account a point under its cap took all of them and went past it by what they used between them (dyzdyz010 on Discord: capped at 90%, used to 100%). In serve's walk an account within 5 points of a usage cap (`nearCapOf`, `nearCapPoints`, `cap_near.go`) takes one turn at a time (`Server.nearCap`, its turn held until the try ends): a turn that finds it busy goes to the next candidate first, the account moved behind them once (`nearBehind`); the last candidate waits. Once its turn comes `capHeld` judges it again, by what the reply before it left (Codex's `codex.rate_limits`, Claude's `rate_limit_event`), or, when that reply said nothing of the account's usage, by a reading taken again then (`nearCapAgain`, at most `carefulWait`); held, it is passed over, and when it was the last the agent gets `cappedError`'s 429. The cap is passed by one turn at most, as a gateway key's limit is, Claude Code accounts as Codex's (`TestNearCapTakesOneTurnAtATime`, `TestNearCapWaitsThenHolds`, `TestNearCapReadsAgainAfterASilentReply`, `TestFarFromCapTurnsGoTogether`, `TestNearCapClaudeAccountsTakeOneTurnEach`). A conversation kept on its account by Stays: Strict goes on past the cap as `strictKeep` keeps it, and takes no turn there (`TestStrictAffinityGoesPastTheCap`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. A header value is ASCII on the wire and fetch refuses one that isn't, so an account whose user isn't ASCII (北冥, plugins#615) is named percent-encoded; `pinnedName` decodes it, the value as written matches too, and the trace and the call's record name it decoded (`TestAccountPinnedPercentEncoded`). diff --git a/internal/cli/groups_rules_cli.go b/internal/cli/groups_rules_cli.go index e5df436ba..8256b2687 100644 --- a/internal/cli/groups_rules_cli.go +++ b/internal/cli/groups_rules_cli.go @@ -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 diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 8c9651dbd..ba844f425 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -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) } diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 9402735dd..d814b3d36 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -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": diff --git a/internal/gateway/gemini.go b/internal/gateway/gemini.go index 445ba0921..002b2ecd7 100644 --- a/internal/gateway/gemini.go +++ b/internal/gateway/gemini.go @@ -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 { diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 69fc0421c..1b96b1dcf 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -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 { diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 4f3eda2f6..b15e815ae 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -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 diff --git a/internal/gateway/rule_where_test.go b/internal/gateway/rule_where_test.go index d5df516f7..e9e55cb79 100644 --- a/internal/gateway/rule_where_test.go +++ b/internal/gateway/rule_where_test.go @@ -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":"todo"},{"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) + } + }) + } +} diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index 0a5caaa56..d716a8a37 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -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 diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 7109c8676..fd890bce1 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -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"); diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 357f51069..fc8ef0d8b 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -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", diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 7bd614018..78c369ceb 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -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; } diff --git a/internal/gui/tests/routing-rule-ops.test.cjs b/internal/gui/tests/routing-rule-ops.test.cjs index d45da5cf6..8c97592fe 100644 --- a/internal/gui/tests/routing-rule-ops.test.cjs +++ b/internal/gui/tests/routing-rule-ops.test.cjs @@ -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), []); diff --git a/internal/gui/tests/routing-rules-line.test.cjs b/internal/gui/tests/routing-rules-line.test.cjs index fc616a6c5..b00feed31 100644 --- a/internal/gui/tests/routing-rules-line.test.cjs +++ b/internal/gui/tests/routing-rules-line.test.cjs @@ -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" }, diff --git a/internal/provider/grouprule.go b/internal/provider/grouprule.go index cbcd2b02d..42f637eb7 100644 --- a/internal/provider/grouprule.go +++ b/internal/provider/grouprule.go @@ -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 }) }) } diff --git a/internal/provider/rulecond.go b/internal/provider/rulecond.go index 585bd7bc3..08836f031 100644 --- a/internal/provider/rulecond.go +++ b/internal/provider/rulecond.go @@ -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" } diff --git a/internal/provider/rulecond_test.go b/internal/provider/rulecond_test.go index 3e5f4ab3f..db514f403 100644 --- a/internal/provider/rulecond_test.go +++ b/internal/provider/rulecond_test.go @@ -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{"x", "正在上下文压缩,请总结"}}, 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) } } diff --git a/internal/tui/routing.go b/internal/tui/routing.go index c2bf5a4c4..a977c4a5a 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -338,7 +338,7 @@ func (m *model) openClassifier(g provider.Group) { const ruleHint = `use=, and any of: tokens=200k · images · effort=on|low|medium|high|xhigh|max · agents=codex,claude intent="a quick question" (the group's classifier= 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= 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= time=… days=… agents=… folders=… except-folders=…: the model is left out of the group then, not even a fallback` diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 2df96d4c1..4cc682e4e 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -248,6 +248,7 @@ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,# その時間帯は外す magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task # ~/big-task のタスク専用:ほかのフォルダでは外す magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when="effort is off" when="not subagent" # 推論オフでサブエージェントでないリクエスト +magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when="system matches ^你是对话标题命名" # システムプロンプトでタイトル生成リクエストを見分ける magpie group set coder models+=group/opus-anywhere # グループの中のグループ magpie group rule opus-anywhere # ルール一覧。rule rm|mv <n>、rule classifier <group> <model> magpie group copy opus-anywhere "Opus test" # モデル・ルーティング・ルールが同じ複製。別々に変更できる diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 82a04a9ca..f008492d0 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -248,6 +248,7 @@ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,# left out in those hours magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task # the model kept for the task in ~/big-task: left out of every other folder magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when="effort is off" when="not subagent" # reasoning off, not a subagent +magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when="system matches ^你是对话标题命名" # a harness's title call, told by its system prompt magpie group set coder models+=group/opus-anywhere # a group in a group magpie group rule opus-anywhere # its rules; rule rm|mv <n>, rule classifier <group> <model> magpie group copy opus-anywhere "Opus test" # the same models, routing and rules, to change on its own diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index 25903414f..162fdf516 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -248,6 +248,7 @@ magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,# 这段时间不用它 magpie group rule add opus-anywhere pause=claude/claude-opus-5-5 except-folders=~/big-task # 只留给 ~/big-task 里的任务:其他文件夹不用它 magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when="effort is off" when="not subagent" # 关了推理、又不是子代理的请求 +magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash when="system matches ^你是对话标题命名" # 按系统提示词认出标题命名请求,不用模型判断 magpie group set coder models+=group/opus-anywhere # 路由组里放路由组 magpie group rule opus-anywhere # 查看规则;rule rm|mv <n>,rule classifier <组> <模型> 换判断模型 magpie group copy opus-anywhere "Opus test" # 复制一份:模型、路由方式和规则都一样,可单独修改