routing: a group's rule can hold by the folder the agent works in (Cario0x on X)

Cario0x on X asked to route by the project being worked on. A group's rule now has a
"folders" condition: it matches when the request's working folder is one of the listed
folders or inside one. It combines (AND) with the existing conditions: tokens, images,
intent, time, agents and quota.

- gateway/workdir.go reads the folder each agent states in its own request:
  - Claude Code: "Primary working directory", including "(was …)" after a move.
  - Codex: <environment_context><cwd>.
  - Pi: <cwd>.
  - OpenCode: <env> "Working directory".
  The last one stated wins. Assistant text and tool results are ignored. A request
  that states no folder matches no folder rule: unknown, never empty.
- provider/rulefolder.go matches a folder only at a path boundary.
  - ~ is the home folder.
  - C:\x is the same folder as /mnt/c/x, and \\wsl$\Distro\x as /x.
  - Case is ignored on macOS and Windows, and always for a drive.
  - A rule's folder must be a whole path. Pause rules can't have folders.
- The trace's RuleHit.Folder makes the Routing page say "The agent works in …".
- GUI: an "in folder" condition in the group editor, hidden on pause rules. Strings in
  zh, zh-TW, ja and de.
- CLI: `magpie group rule add … folders=~/oss,"~/My Project"`. The TUI shows the
  condition.
- Docs: docs/subsystems/gateway-routing.md and site start.html (en, zh, ja).

Fixtures are real requests from Claude Code 2.1.296, Codex 0.162.0 and Pi 1.1.0, run in
a sandbox from a folder named "a&b <c> 中文" or "My Proj", with the sandbox path
replaced.

Run at this head:
- go test ./... green.
- gofmt -l clean.
- go vet green for darwin, GOOS=linux -tags nogui and GOOS=windows.
- GUI routing-folder.test.cjs: chromium and webkit, en, zh, zh-TW, ja and de, 1100px
  and 390px (no horizontal scroll). It fails on the old routing.js.
- Related routing, group and i18n GUI tests: 85/85.
- Full GUI suite: 5611/5631 under --test-concurrency=6. Rerun alone, every failure
  passes except:
  - skill-install-agents-all (chromium, 420px), which is red on origin/main too: #1554.
  - The menu-scroll track flake, which flakes on main as well: #1550.
- e2e: a sandbox HOME, a dev build and fake upstreams, with real Claude Code 2.1.296
  (`claude -p --model group/fd`).
  - From proj/acme/web, rule 1 matched and the request went to kb.
  - From proj/acme-old, no rule matched and the request went to ka. The trace and UI
    showed the folder.
This commit is contained in:
yetone
2026-10-11 10:17:16 +08:00
parent 3964ea656c
commit ae70d8eac8
20 changed files with 766 additions and 26 deletions
+2
View File
@@ -38,6 +38,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it.
- A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Only a ChatGPT account's model can be set (`provider.SetCodexSubagentModel`), as nothing else reads the sealed task. When no ChatGPT account on in magpie serves it now, or a gateway key held to some models may not use it, the subagent goes on the model asked for. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. The lead's turns, titles and every other kind are never moved.
- Rules and image inputs are handled here too.
- 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$\<distro>` or `\\wsl.localhost\<distro>` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. The folder is read from the request only when a rule of the group has 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: <path>` (its `<`/`>` as entities; ` (was <old>)` after a change dropped), Codex's `<environment_context>` `<cwd>`, Pi's `<cwd>` in the system prompt, and OpenCode's `Working directory:` inside its `<env>` block. Only the system prompt and the user's and system messages' text count, 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 rule by folder matches it (unknown, never empty). A pause rule can't have folders. 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`, `routing-folder.test.cjs`.
- A pause rule (`Rule.Pause`, `pause=<model>`; 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 and agents 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. `rules_pause_test.go`.
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) 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`). 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`); otherwise a capped or barred set returns `cappedError` or `barredError`. 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.
4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were.
@@ -195,6 +196,7 @@ go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|
go test -tags nogui ./internal/gateway -run 'TestSearchMCP'
go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts'
go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag'
go test -tags nogui ./internal/provider ./internal/gateway -run 'TestFolderUnder|TestRuleFoldersCleaned|TestRuleMatchesByFolder|TestParseRuleFolders|TestWorkDir|TestRuleByFolder'
go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestDeclareSearch|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestSkipsRedaction|TestSetRPM'
```
+7 -1
View File
@@ -16,7 +16,7 @@ const ruleUsage = `usage:
magpie group rule <group> the group's rules
magpie group rule add <group> use=<model> [tokens=<n>] [images] [effort=on|low|medium|high|xhigh|max] [agents=a,b…]
[intent="<what the message asks for>"] [compact] [time=HH:MM-HH:MM] [days=mon-fri]
[classifier=<model>] [at=<n>]
[folders=<folder>,…] [classifier=<model>] [at=<n>]
a rule: a turn that matches it goes to <model>, one of the group's
(or group/<id>, a group in it), first; a model in the group at an
effort of its own is named with it (use=glm/glm-5.3-flash:high)
@@ -52,6 +52,11 @@ const ruleUsage = `usage:
runs past midnight) — a provider's peak-price hours sent to another, say
days only on these days (mon-fri, sat,sun); with time, a window past midnight is of the day it
begins on. Days alone hold all day
folders the agent works in one of these folders, or a folder inside one (~/work/acme, ~/oss;
C:\work, which is /mnt/c/work in WSL): a project, or every project under a folder. The
folder is the one the agent tells its model in the request (Claude Code, Codex, OpenCode,
Pi); a request that doesn't tell it matches no folder. Quote a folder with a space:
folders="~/My Project,~/oss"
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
@@ -59,6 +64,7 @@ const ruleUsage = `usage:
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact
magpie group rule add cheap use=glm/glm-5.3 time=14:00-18:00 days=mon-fri
magpie group rule add cheap pause=glm/glm-5.3 time=14:00-18:00 days=mon-fri
magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash intent="a quick question" classifier=groq/llama-3.1-8b-instant`
// parseTokens reads 200000, 200k, 1.5m.
+7 -1
View File
@@ -40,6 +40,9 @@ type RuleHit struct {
Tokens int `json:"tokens"` // how long the request was taken to be
Images bool `json:"images,omitempty"` // it carries an image
Effort string `json:"effort,omitempty"` // the reasoning asked for: a level, or "on"
// Folder: the working folder the agent said, looked at when a rule
// is by folder; "" when it said none
Folder string `json:"folder,omitempty"`
// Unready: the member the rule names has nobody to take it now, and
// the group routes the request as it would without the rule.
Unready bool `json:"unready,omitempty"`
@@ -164,7 +167,10 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a
if had && tr.input > q.Tokens {
q.Tokens = tr.input // what the vendor counted last, a floor: the conversation only grew since
}
hit := &RuleHit{Turn: turn, Tokens: q.Tokens, Images: q.Images, Effort: q.Effort, Bare: len(g.Rules) == 0}
if slices.ContainsFunc(g.Rules, func(r provider.Rule) bool { return len(r.Folders) > 0 }) {
q.Folder = workDir(req)
}
hit := &RuleHit{Turn: turn, Tokens: q.Tokens, Images: q.Images, Effort: q.Effort, Folder: q.Folder, Bare: len(g.Rules) == 0}
defer func() {
// whatever put a member first, the rules after it that match too
// say who comes next
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+89
View File
@@ -0,0 +1,89 @@
package gateway
// The folder an agent works in, as it tells its model in the request — for
// a group's rule by folder (provider.Rule.Folders). Each agent says it its
// own way, every format here taken from the agent's own request:
//
// - Claude Code (2.1.296): its environment, " - Primary working
// directory: /x", in the system prompt or a system message; when the
// folder changes, "Primary working directory: /y (was /x)". < and > in
// the path come as &lt; and &gt;.
// - Codex (0.162): a user message's <environment_context> with
// "<cwd>/x</cwd>", the path's &, < and > as entities.
// - Pi (1.1): the system prompt's "<cwd>\n/x\n</cwd>", backslashes as /.
// - OpenCode (2.0): "<env>\n Working directory: /x\n…</env>", in the
// system prompt or, when it changes, a later message.
//
// Of those it says, the last one goes: an agent that moved says so after.
// An agent that says none of them has no folder: a rule by folder doesn't
// match it.
import (
"html"
"regexp"
"strings"
)
var (
ccWorkDir = regexp.MustCompile(`(?m)^(?: - )?Primary working directory: (.+)$`)
// the folder a <cwd> holds: Codex's on its line, Pi's on its own
cwdTag = regexp.MustCompile(`<cwd>\s*([^<\n]+?)\s*</cwd>`)
envDir = regexp.MustCompile(`(?m)^\s*Working directory: (.+)$`)
wasDir = regexp.MustCompile(` \(was .*\)$`)
)
// workDir is the folder the request says its agent works in; "" when it
// doesn't say.
func workDir(req *Request) string {
if req == nil {
return ""
}
dir := workDirIn(req.System, "")
for _, m := range req.Messages {
if m.Role == "assistant" {
continue // the model's words, not the agent's
}
for _, p := range m.Parts {
if p.Kind == Text {
dir = workDirIn(p.Text, dir)
}
}
}
return dir
}
// workDirIn is the last folder text says, else dir.
func workDirIn(text, dir string) string {
if !strings.Contains(text, "irectory: ") && !strings.Contains(text, "<cwd>") {
return dir
}
at := -1
take := func(i int, v string) {
if v = strings.TrimSpace(html.UnescapeString(v)); v != "" && i > at {
at, dir = i, v
}
}
for _, m := range ccWorkDir.FindAllStringSubmatchIndex(text, -1) {
take(m[0], wasDir.ReplaceAllString(text[m[2]:m[3]], ""))
}
for _, m := range cwdTag.FindAllStringSubmatchIndex(text, -1) {
take(m[0], text[m[2]:m[3]])
}
// OpenCode's, only within its <env>
for rest, off := text, 0; ; {
i := strings.Index(rest, "<env>")
if i < 0 {
break
}
j := strings.Index(rest[i:], "</env>")
if j < 0 {
break
}
block := rest[i : i+j]
if m := envDir.FindStringSubmatchIndex(block); m != nil {
take(off+i+m[0], block[m[2]:m[3]])
}
rest, off = rest[i+j:], off+i+j
}
return dir
}
+140
View File
@@ -0,0 +1,140 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// The fixtures are requests the agents sent a fake upstream, run in a
// sandbox home from a folder named "a&b <c> 中文" (Claude Code 2.1.296,
// Codex 0.162.0) or "My Proj" (Pi 1.1.0); the sandbox's path is replaced
// with /Users/me/work.
func fixture(t *testing.T, name string) []byte {
t.Helper()
b, err := os.ReadFile(filepath.Join("testdata", "workdir", name))
if err != nil {
t.Fatal(err)
}
return b
}
// Each agent's folder is read from its own request, entities and all.
func TestWorkDirOfEachAgent(t *testing.T) {
for _, tc := range []struct {
file string
parse func([]byte) (*Request, error)
want string
}{
{"claude-code-2.1.296.json", parseAnthropic, "/Users/me/work/proj/a&b <c> 中文"},
{"codex-0.162.0.json", parseResponses, "/Users/me/work/proj/a&b <c> 中文"},
{"pi-1.1.0.json", parseChat, "/Users/me/work/proj/My Proj"},
} {
req, err := tc.parse(fixture(t, tc.file))
if err != nil {
t.Fatal(tc.file, err)
}
if got := workDir(req); got != tc.want {
t.Errorf("%s: %q, want %q", tc.file, got, tc.want)
}
}
}
// OpenCode 2.0.20's environment, as its source writes it (its run waits on
// a background service a sandbox doesn't start): in the system prompt,
// and when it changes, after.
func TestWorkDirOpenCode(t *testing.T) {
env := func(dir string) string {
return strings.Join([]string{"<env>", " Working directory: " + dir, " Workspace root folder: /Users/me", " Is directory a git repo: yes", " Platform: darwin",
" Prefer /tmp/x over generic system temporary directories such as /tmp; it is pre-created and approved for external access.", "</env>"}, "\n")
}
req := &Request{System: "You are opencode.\nHere is some useful information about the environment you are running in:\n" + env("/Users/me/acme"),
Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}}
if got := workDir(req); got != "/Users/me/acme" {
t.Errorf("%q", got)
}
req.Messages = append(req.Messages, Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "ok"}}},
Message{Role: "user", Parts: []Part{{Kind: Text, Text: "The environment you are running in is now:\n" + env("/Users/me/oss")}}})
if got := workDir(req); got != "/Users/me/oss" {
t.Errorf("changed: %q", got)
}
}
// Claude Code moved to another folder says so after, with the one it was
// in (its source: "Primary working directory: /y (was /x)"); the last
// said goes. What the model or a tool said, or a "Working directory:" out
// of OpenCode's <env>, isn't the agent's folder; nothing said is unknown.
func TestWorkDirLastSaidAndOnlyByTheAgent(t *testing.T) {
req, err := parseAnthropic(fixture(t, "claude-code-2.1.296.json"))
if err != nil {
t.Fatal(err)
}
req.Messages = append(req.Messages,
Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: " - Primary working directory: /from/the/model"}}},
Message{Role: "user", Parts: []Part{{Kind: ToolResult, Text: "<cwd>/from/a/tool</cwd>"}, {Kind: Text, Text: "<system-reminder>\nPrimary working directory: /Users/me/next (was /Users/me/work/proj/a&b &lt;c&gt; 中文)\n</system-reminder>"}}},
)
if got := workDir(req); got != "/Users/me/next" {
t.Errorf("%q", got)
}
for _, text := range []string{"hi", "Working directory: /x", "the <cwd></cwd> tag"} {
if got := workDir(&Request{System: "You are an agent.", Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: text}}}}}); got != "" {
t.Errorf("%q: %q", text, got)
}
}
}
// The agents' own requests go by a group's rule by folder, each over its
// own protocol: the folder under the rule's to its member, the trace
// telling the folder, the rule's condition and that it matched; one out
// of it, or with no folder said, by the group's order.
func TestRuleByFolder(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the fixtures' folders are Unix paths")
}
s, _, _ := ruled(t, provider.Rule{Use: "b/big", Folders: []string{"/Users/me/work/proj"}})
group := 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)
}
for _, tc := range []struct {
name, path, body, folder string
n int
}{
{"claude code", "/v1/messages", group(fixture(t, "claude-code-2.1.296.json")), "/Users/me/work/proj/a&b <c> 中文", 1},
{"codex", "/v1/responses", group(fixture(t, "codex-0.162.0.json")), "/Users/me/work/proj/a&b <c> 中文", 1},
{"pi", "/v1/chat/completions", group(fixture(t, "pi-1.1.0.json")), "/Users/me/work/proj/My Proj", 1},
{"pi elsewhere", "/v1/chat/completions", strings.ReplaceAll(group(fixture(t, "pi-1.1.0.json")), "/Users/me/work/proj/", "/Users/me/work/project/"), "/Users/me/work/project/My Proj", 0},
{"no folder", "/v1/chat/completions", chat("hi", nil, 0, ""), "", 0},
} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))
req.Header.Set("x-session-id", tc.name)
s.Handler().ServeHTTP(rec, req)
want := map[int]string{0: "from ka", 1: "from kb"}[tc.n]
r := lastRoute(s)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), want) {
t.Errorf("%s: %d %.300s", tc.name, rec.Code, rec.Body.String())
continue
}
if r.Rule == nil || r.Rule.N != tc.n || r.Rule.Folder != tc.folder {
t.Errorf("%s: rule %+v", tc.name, r.Rule)
continue
}
if tc.n == 1 && (len(r.Rule.When) != 1 || r.Rule.When[0] != "folder /Users/me/work/proj") {
t.Errorf("%s: when %q", tc.name, r.Rule.When)
}
}
}
+20
View File
@@ -2973,6 +2973,11 @@ const I18N = {
"When": "当",
"has an image": "带图片",
"compacting": "压缩上下文时",
"in {folders}": "在 {folders} 中",
"The agent works in {folder}.": "Agent 的工作目录是 {folder}。",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "Agent 的工作目录是这些文件夹之一或其子文件夹(以它告诉模型的为准:Claude Code、Codex、OpenCode、Pi);不说明工作目录的 Agent 不匹配",
"in folder": "项目文件夹",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "规则 {n}:文件夹需是完整路径,如 ~/work 或 /Users/me/work",
"from": "从",
"to": "到",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "本轮在此时段内(按本机时间)开始时生效,例如把某家高峰计价时段的请求转给另一家",
@@ -7188,6 +7193,11 @@ const I18N = {
"When": "當",
"has an image": "帶圖片",
"compacting": "壓縮上下文時",
"in {folders}": "在 {folders} 中",
"The agent works in {folder}.": "Agent 的工作目錄是 {folder}。",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "Agent 的工作目錄是這些資料夾之一或其子資料夾(以它告訴模型的為準:Claude Code、Codex、OpenCode、Pi);不說明工作目錄的 Agent 不符合",
"in folder": "專案資料夾",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "規則 {n}:資料夾需是完整路徑,如 ~/work 或 /Users/me/work",
"from": "從",
"to": "到",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "本輪在此時段內(按本機時間)開始時生效,例如把某家高峰計價時段的請求轉給另一家",
@@ -11420,6 +11430,11 @@ const I18N = {
"When": "条件",
"has an image": "画像あり",
"compacting": "コンパクト化中",
"in {folders}": "{folders} 内",
"The agent works in {folder}.": "エージェントの作業フォルダは {folder} です。",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "エージェントがモデルに伝える作業フォルダ(Claude Code、Codex、OpenCode、Pi)がこれらのフォルダかその中にあるとき。伝えないエージェントは一致しません",
"in folder": "フォルダ",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "ルール {n}:フォルダは ~/work や /Users/me/work のような完全なパスで指定してください",
"from": "から",
"to": "まで",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "ターンがこの時間帯(このコンピューターの時刻)に始まったとき — たとえば、あるプロバイダのピーク料金の時間帯を別のプロバイダへ送るなど",
@@ -15649,6 +15664,11 @@ const I18N = {
"When": "Wenn",
"has an image": "enthält ein Bild",
"compacting": "beim Kompaktieren",
"in {folders}": "in {folders}",
"The agent works in {folder}.": "Der Agent arbeitet in {folder}.",
"The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched": "Der Agent arbeitet in einem dieser Ordner oder einem Ordner darin, wie er es dem Modell sagt (Claude Code, Codex, OpenCode, Pi); ein Agent, der es nicht sagt, passt nicht",
"in folder": "im Ordner",
"Rule {n}: a folder is a whole path, like ~/work or /Users/me/work": "Regel {n}: Ein Ordner ist ein ganzer Pfad, etwa ~/work oder /Users/me/work",
"from": "von",
"to": "bis",
"The turn begins within these hours, on this computer's clock — a provider's peak-price hours sent to another, say": "Die Runde beginnt in diesen Stunden, nach der Uhr dieses Computers – etwa um die Spitzenpreis-Stunden eines Anbieters an einen anderen zu geben",
+2
View File
@@ -527,6 +527,8 @@ button.rt-session { cursor: pointer; }
.rt-cond.tk { cursor: text; }
.rt-cond.in { cursor: text; }
.rt-cond.in input, .editor .rt-cond.in input[type="text"] { width: 24ch; }
.rt-cond.fd { cursor: text; }
.rt-cond.fd input, .editor .rt-cond.fd input[type="text"] { width: 24ch; }
/* a rule's hours: two times in the pill, typed; one that isn't a time is marked */
.rt-cond.tm { cursor: text; }
.rt-cond.tm input.clock, .editor .rt-cond.tm input.clock[type="text"] { width: 5.5ch; text-align: center; }
+26 -10
View File
@@ -590,21 +590,23 @@
if (!r.rule || r.rule.bare) return null;
const x = { ...r.rule, use: useName(r, r.rule.use) };
const when = (x.when || []).map(condText).join(", ");
// the folder the agent said it works in, when a rule asks for one
const dir = x.folder ? " " + t("The agent works in {folder}.", { folder: x.folder }) : "";
if (x.use && !x.unready) {
const held = t("Rule {n} ({when}) sent turn {turn} to {use} as it began; the turn stays with whoever took it then.", { n: x.n, when, turn: x.turn, use: x.use });
if (x.compact) return lead ? t("The agent is compacting the conversation, so rule {n} sends the summary to {use}; the conversation stays on the model it was on.", { n: x.n, use: x.use }) + (x.small?.length ? " " + t("Passed over, as the conversation is longer than they take: {models}.", { models: x.small.map((id) => useName(r, id)).join(", ") }) : "") : null;
if (x.held) return lead || affWhy(r, true) ? held : null;
if (x.grown) return lead ? t("Within turn {turn} the conversation grew to about {tokens} tokens, more than the model it was on takes, so rule {n} ({when}) moves it to {use}.", { turn: x.turn, tokens: tokens(x.tokens), n: x.n, when, use: x.use }) : null;
if (!lead) return null;
if (x.then?.length) return t("Turn {turn} begins and rule {n} matches — {when} — so {use} goes first; if it fails, {then}, which the rules after it that match too name, then the group's others.", { turn: x.turn, n: x.n, when, use: x.use, then: x.then.map((id) => useName(r, id)).join(", ") });
return t("Turn {turn} begins and rule {n} matches — {when} — so {use} goes first; the group's others stay behind it if it fails.", { turn: x.turn, n: x.n, when, use: x.use });
if (x.then?.length) return t("Turn {turn} begins and rule {n} matches — {when} — so {use} goes first; if it fails, {then}, which the rules after it that match too name, then the group's others.", { turn: x.turn, n: x.n, when, use: x.use, then: x.then.map((id) => useName(r, id)).join(", ") }) + dir;
return t("Turn {turn} begins and rule {n} matches — {when} — so {use} goes first; the group's others stay behind it if it fails.", { turn: x.turn, n: x.n, when, use: x.use }) + dir;
}
if (x.use && x.instead) return lead ? t("Rule {n} matches, but {use} has no account or key that can take this request, so a later matching rule puts {instead} first.", { n: x.n, use: x.use, instead: useName(r, x.instead) }) : null;
if (lead) return null;
if (x.use) return t("Rule {n} matches, but {use} has no account or key that can take this request, so the group's order stands.", { n: x.n, use: x.use });
if (x.waits) return t("This turn began before magpie saw it, so the rules wait for the next one.");
if (x.held) return null;
return t("No rule matches turn {turn} (about {n} tokens{img}).", { turn: x.turn, n: tokens(x.tokens), img: x.images ? t(", with an image") : "" });
return t("No rule matches turn {turn} (about {n} tokens{img}).", { turn: x.turn, n: tokens(x.tokens), img: x.images ? t(", with an image") : "" }) + dir;
}
// treeText is a group's models, those of a group in it in brackets after
// its name: a/m, Fast [b/m, c/m]
@@ -678,6 +680,7 @@
if (c === "compacting") return t("compacting");
if ((m = /^effort ≥ (\w+)$/.exec(c))) return t("reasoning ≥ {level}", { level: m[1] });
if ((m = /^agent (.+)$/.exec(c))) return m[1].split("|").map(agentName).join(" / ");
if ((m = /^folder (.+)$/.exec(c))) return t("in {folders}", { folders: m[1].split("|").join(" / ") });
if ((m = /^time (all day|(\d\d:\d\d)–(\d\d:\d\d))(?: (.+))?$/.exec(c))) {
// the days as the gateway writes them: Mon–Fri, Sat,Sun, Mon,Wed–Fri
const days = [];
@@ -3041,6 +3044,7 @@
if (r.intent) bits.push(t("asks for “{intent}”", { intent: r.intent }));
if (r.compact) bits.push(t("compacting"));
if (r.time) bits.push(timeText(r.time));
if (r.folders?.length) bits.push(t("in {folders}", { folders: r.folders.join(" / ") }));
return bits.join(" · ");
}
const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -3129,7 +3133,7 @@
// there, rather than leaving the slot empty.
const openGroupEditor = async (g) => {
if (groupDirty() && !(await confirmDiscard())) return false;
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
renderGroups();
return true;
};
@@ -3272,7 +3276,7 @@
if (groupDirty() && !(await confirmDiscard())) return;
const g = tp.group;
gSel = null;
gEdit = { id: "", draft: { name: tplName(tp), slug: g.id, members: [...g.members], match: [], matched: [], fast: [], off: [], routing: g.routing || "", affinity: "", rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], time: null })), classifier: g.classifier || "", effort: "", levels: [] } };
gEdit = { id: "", draft: { name: tplName(tp), slug: g.id, members: [...g.members], match: [], matched: [], fast: [], off: [], routing: g.routing || "", affinity: "", rules: (g.rules || []).map((r) => ({ ...r, intent: r.intent || "", agents: [...(r.agents || [])], folders: [], time: null })), classifier: g.classifier || "", effort: "", levels: [] } };
renderGroups();
const ed = gList.querySelector(".rt-gedit");
ed?.scrollIntoView({ block: "nearest" });
@@ -4135,11 +4139,20 @@
drawTime(); warn();
});
drawTime();
// folders: the project the agent works in, as it tells its model
// (Cario0x on X), typed comma separated; a folder inside one counts
const fd = el("span", "rt-cond fd" + (r.folders?.length ? " on" : ""));
fd.onclick = () => fi.focus();
const fi = input((r.folders || []).join(", "), "~/work/acme, ~/oss");
fd.title = t("The agent works in one of these folders or a folder inside one, as it tells the model (Claude Code, Codex, OpenCode, Pi); an agent that doesn't say isn't matched");
fi.oninput = () => { r.folders = fi.value.split(",").map((x) => x.trim()).filter(Boolean); fd.classList.toggle("on", r.folders.length > 0); };
fi.onkeydown = (e) => e.stopPropagation();
fd.append(el("span", "", t("in folder")), fi);
// a pause holds by hours, days and agents only: the others are
// about a request, and a pause keeps the model out of every one
const byRequest = [tk, im, ef, it, cp];
const byRequest = [tk, im, ef, it, cp, fd];
for (const c of byRequest) c.hidden = !!r.pause;
when.append(tk, im, ef, ag, it, cp, tm, dayBtn);
when.append(tk, im, ef, ag, it, cp, fd, tm, dayBtn);
// the member it sends to
const use = el("div", "rt-use");
const ub = el("button", "rt-cond on");
@@ -4170,7 +4183,7 @@
], (v) => {
r.pause = v === "pause";
// what a pause doesn't take is cleared, not kept out of sight
if (r.pause) Object.assign(r, { tokens: 0, images: false, effort: "", intent: "", compact: false });
if (r.pause) Object.assign(r, { tokens: 0, images: false, effort: "", intent: "", compact: false, folders: [] });
drawRules();
}, r.pause ? "pause" : "send");
use.append(act, ub, hint);
@@ -4187,7 +4200,7 @@
focusIntent = null;
};
let focusIntent = null;
const newRule = () => ({ use: d.members[d.members.length - 1], pause: false, tokens: 0, images: false, effort: "", agents: [], intent: "", compact: false, time: null });
const newRule = () => ({ use: d.members[d.members.length - 1], pause: false, tokens: 0, images: false, effort: "", agents: [], intent: "", compact: false, folders: [], time: null });
rAdd.onclick = () => { d.rules.push(newRule()); drawRules(); };
const addIntentRule = () => {
asking = newRule();
@@ -4333,7 +4346,10 @@
? t("Rule {n}: its hours are the whole day — pick days, or other hours", { n: badTime + 1 })
: t("Rule {n}: the hours are two times like 09:00 and 18:00", { n: badTime + 1 }), "warn");
}
const bare = d.rules.findIndex((r) => !r.pause && !r.tokens && !r.images && !r.effort && !r.agents.length && !r.intent && !r.compact && !r.time);
// a folder is a whole path (provider.cleanFolder)
const badDir = d.rules.findIndex((r) => (r.folders || []).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");
const bare = d.rules.findIndex((r) => !r.pause && !r.tokens && !r.images && !r.effort && !r.agents.length && !r.intent && !r.compact && !r.time && !r.folders?.length);
if (bare >= 0) return status(t("Rule {n} needs a condition", { n: bare + 1 }), "warn");
const bareP = d.rules.findIndex((r) => r.pause && !r.time && !r.agents.length);
if (bareP >= 0) return status(t("Rule {n}: a pause needs hours, days or agents", { n: bareP + 1 }), "warn");
+158
View File
@@ -0,0 +1,158 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A routing group's rule may be for the folder the agent works in (Cario0x
// on X: routing by the project being worked on). The group's rule reads its
// folders; the trace tells the rule matched by folder and the folder the
// agent said; in the editor the folders are a condition of their own, typed
// comma separated, a folder that isn't a whole path refused before saving,
// a rule with only folders not refused as having no condition, and saved
// as folders:[…]. In every language, and at a phone's width the condition
// stays inside the editor.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const models = [
{ id: "a/opus", name: "opus", providerName: "A", icon: "generic", context: 1000000, ready: true },
{ id: "b/kimi", name: "kimi", providerName: "B", icon: "generic", context: 256000, ready: true },
];
const groups = () => ({
models,
groups: [{ id: "main", name: "Main", members: ["a/opus", "b/kimi"], routing: "order", ready: true,
memberInfo: [{ id: "a/opus", ready: true, context: 1000000 }, { id: "b/kimi", ready: true, context: 256000 }], rules: [{ use: "b/kimi", folders: ["~/work/acme", "/srv/oss"] }] }],
pools: [],
});
const now = Date.now();
const route = {
id: 7, seq: 7, time: new Date(now - 2000).toISOString(), agent: "claude", model: "main", provider: "b", done: true, status: 200, ms: 900, tokens: 9000,
group: { id: "main", name: "Main", members: ["a/opus", "b/kimi"] },
order: [{ id: "b", provider: "b", name: "B", kind: "key", model: "kimi", known: true }, { id: "a", provider: "a", name: "A", kind: "key", model: "opus", known: true }],
tries: [{ id: "b", model: "kimi", start: new Date(now - 2000).toISOString(), done: true, ms: 800, status: 200 }],
rule: { n: 1, use: "b/kimi", when: ["folder ~/work/acme|/srv/oss"], turn: 2, tokens: 9000, folder: "/Users/me/work/acme/web" },
};
const words = {
en: { cond: "in ~/work/acme / /srv/oss", dir: "The agent works in /Users/me/work/acme/web.", label: "in folder", bad: "Rule 1: a folder is a whole path, like ~/work or /Users/me/work", edit: "Edit", save: "Save" },
zh: { cond: "在 ~/work/acme / /srv/oss 中", dir: "Agent 的工作目录是 /Users/me/work/acme/web。", label: "项目文件夹", bad: "规则 1:文件夹需是完整路径,如 ~/work 或 /Users/me/work", edit: "编辑", save: "保存" },
"zh-TW": { cond: "在 ~/work/acme / /srv/oss 中", dir: "Agent 的工作目錄是 /Users/me/work/acme/web。", label: "專案資料夾", bad: "規則 1:資料夾需是完整路徑,如 ~/work 或 /Users/me/work", edit: "編輯", save: "儲存" },
ja: { cond: "~/work/acme / /srv/oss 内", dir: "エージェントの作業フォルダは /Users/me/work/acme/web です。", label: "フォルダ", bad: "ルール 1:フォルダは ~/work や /Users/me/work のような完全なパスで指定してください", edit: "編集", save: "保存" },
de: { cond: "in ~/work/acme / /srv/oss", dir: "Der Agent arbeitet in /Users/me/work/acme/web.", label: "im Ordner", bad: "Regel 1: Ein Ordner ist ein ganzer Pfad, etwa ~/work oder /Users/me/work", edit: "Bearbeiten", save: "Speichern" },
};
function serve(lang, posts) {
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
let first = true;
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
const routes = first ? [route] : [];
first = false;
return json({ mine: true, now: new Date().toISOString(), seq: 7, totals: { requests: 1, rerouted: 0, errors: 0 }, routes });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json(groups());
if (url.pathname.startsWith("/api/groups/")) {
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
return json(groups());
}
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await r.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(t, engine, lang, width) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage();
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=routing");
const group = page.locator(".rt-group").first();
await group.waitFor();
return { page, group, errors, posts };
}
// the view wheeled down to a button, as the reader would (the page keeps
// still for any other scroll), and the button clicked where it is
async function press(page, b) {
await page.mouse.move(Math.min(550, page.viewportSize().width / 2), 600);
for (let i = 0; i < 10 && (await b.boundingBox()).y > 1400 - 160; i++) {
await page.mouse.wheel(0, 300);
await page.waitForTimeout(150);
}
const bb = await b.boundingBox();
await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: a rule by folder`, async (t) => {
const { page, group, errors, posts } = await open(t, engine, lang, 1100);
// the trace: the rule matched by its folders, and the folder the agent said
await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.dir);
const said = await page.evaluate(() => document.documentElement.innerText);
assert(said.includes(w.cond), `the rule's folders are told: ${said.slice(0, 2000)}`);
// the group's rule, in words
const title = await group.evaluate((g) => [...g.querySelectorAll("[title]")].map((e) => e.title).join("\n"));
assert(title.includes(`1. ${w.cond} →`), `the rule reads by its folders: ${title}`);
// the editor: the folders typed in their own condition
await group.locator("button", { hasText: w.edit }).click();
const ed = page.locator(".rt-gedit");
const fd = ed.locator(".rt-rule").first().locator(".rt-cond.fd");
await fd.waitFor();
assert.equal(await fd.getAttribute("class"), "rt-cond fd on");
assert.equal(await fd.locator("span").first().textContent(), w.label);
const box = fd.locator("input");
assert.equal(await box.inputValue(), "~/work/acme, /srv/oss");
// not a whole path: refused, nothing saved
await box.fill("work/acme");
const saveBtn = ed.locator("button.primary", { hasText: w.save });
await press(page, saveBtn);
await page.waitForFunction((s) => document.documentElement.innerText.includes(s), w.bad);
assert.equal(posts.filter((p) => p.path === "/api/groups/save").length, 0);
// emptied, the rule has no condition and the folder's is off
await box.fill("");
assert.equal(await fd.getAttribute("class"), "rt-cond fd");
// whole paths, one with a space: saved as typed, a rule with folders alone
await box.fill("~/work/acme , ~/My Project/,");
assert.equal(await fd.getAttribute("class"), "rt-cond fd on");
await press(page, saveBtn);
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
const save = posts.find((p) => p.path === "/api/groups/save");
assert(save, `saved: ${JSON.stringify(posts)}`);
assert.deepEqual(save.body.rules.map((r) => [r.use, r.folders]), [["b/kimi", ["~/work/acme", "~/My Project/"]]]);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a rule by folder at a phone's width`, async (t) => {
const { page, group, errors } = await open(t, engine, lang, 390);
await press(page, group.locator("button", { hasText: w.edit })); // the group is below the fold here
const fd = page.locator(".rt-gedit .rt-rule").first().locator(".rt-cond.fd");
await fd.waitFor();
const [b, row] = await Promise.all([fd.boundingBox(), page.locator(".rt-gedit .rt-rule").first().boundingBox()]);
assert(b.x >= row.x - 1 && b.x + b.width <= row.x + row.width + 1, `the folders' condition stays in its rule: ${JSON.stringify([b, row])}`);
const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert(wide <= 0, `no sideways scroll: ${wide}px`);
assert.deepEqual(errors, []);
});
}
}
+33 -4
View File
@@ -61,6 +61,12 @@ type Rule struct {
// Time: the turn begins within these hours of the day, local time — a
// vendor's peak-price hours sent to another, say.
Time *TimeWindow `json:"time,omitempty"`
// Folders: the request's working folder, as the agent states it in
// the request, is one of these or inside one — a project, or every
// project under a folder (Cario0x on X). "~/work", "/Users/me/x",
// "C:\work"; WSL's /mnt/c/work is C:\work. When the agent doesn't
// say its folder, it doesn't match.
Folders []string `json:"folders,omitempty"`
// Pause: rather than sending to Use first, the rule leaves Use out of
// the group while it holds (John on Discord: a model paused in a
// vendor's peak hours). Only Time and Agents can be its conditions,
@@ -241,6 +247,9 @@ func (r Rule) Conditions() []string {
if r.Time != nil {
out = append(out, "time "+r.Time.Text())
}
if len(r.Folders) > 0 {
out = append(out, "folder "+strings.Join(r.Folders, "|"))
}
return out
}
@@ -255,6 +264,20 @@ func cleanRules(rules []Rule, members []string) ([]Rule, error) {
r.Agents[j] = strings.ToLower(r.Agents[j])
}
n := i + 1
var folders []string
for _, p := range r.Folders {
if strings.TrimSpace(p) == "" {
continue
}
c, err := cleanFolder(p)
if err != nil {
return nil, fmt.Errorf("rule %d: %w", n, err)
}
if !slices.Contains(folders, c) {
folders = append(folders, c)
}
}
r.Folders = folders
if r.Time != nil {
w := *r.Time
if err := w.clean(); err != nil {
@@ -277,8 +300,8 @@ 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, intent, compacting or time)", n)
case r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact):
return nil, fmt.Errorf("rule %d: it needs a condition (tokens, images, effort, agents, intent, compacting, time or folders)", n)
case r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact || len(r.Folders) > 0):
return nil, fmt.Errorf("rule %d: a pause holds by hours, days or agents only", n)
}
if len(r.Agents) == 0 {
@@ -304,6 +327,9 @@ type RuleRequest struct {
// At is when the request came, for a rule's hours; a zero time is in
// none.
At time.Time
// Folder is the working folder the agent says the request is from;
// "" when it doesn't say, which is in no rule's folders.
Folder string
}
// Matches reports whether the request is one the rule sends to its member
@@ -333,6 +359,9 @@ func (r Rule) MatchesBesidesIntent(q RuleRequest) bool {
if r.Time != nil && !r.Time.Holds(q.At) {
return false
}
if len(r.Folders) > 0 && !slices.ContainsFunc(r.Folders, func(root string) bool { return FolderUnder(q.Folder, root) }) {
return false
}
switch r.Effort {
case "":
case "on":
@@ -431,11 +460,11 @@ func ruledEntry(e *Entry, g Group, ms []Member, entries []Entry) {
if !ok || r.Pause {
continue
}
if r.Images && r.Tokens == 0 && r.Effort == "" && len(r.Agents) == 0 && r.Intent == "" && !r.Compact && r.Time == nil && sees(x) && !e.Images &&
if r.Images && r.Tokens == 0 && r.Effort == "" && len(r.Agents) == 0 && r.Intent == "" && !r.Compact && r.Time == nil && len(r.Folders) == 0 && sees(x) && !e.Images &&
!slices.ContainsFunc(g.Rules[:i], func(b Rule) bool { y, ok := of(b.Use); return !b.Pause && (!ok || !sees(y)) }) {
e.Images, e.ImageInput = true, x.ImageInput
}
if r.Tokens == 0 || r.Images || r.Effort != "" || len(r.Agents) > 0 || r.Intent != "" || r.Compact || r.Time != nil || x.Context <= e.Context {
if r.Tokens == 0 || r.Images || r.Effort != "" || len(r.Agents) > 0 || r.Intent != "" || r.Compact || r.Time != nil || len(r.Folders) > 0 || x.Context <= e.Context {
continue // only a rule of length alone takes every long request
}
// every request up to the rule's length must fit whoever may get
+87
View File
@@ -0,0 +1,87 @@
package provider
// A rule's folders (Rule.Folders): the request's working folder, as the
// agent states it in the request (gateway/workdir.go), is one of them or
// under one (Cario0x on X: routing by the project being worked on).
import (
"fmt"
"os"
"path"
"regexp"
"runtime"
"strings"
)
// foldCase: folders are told apart without case, as macOS's and
// Windows's file systems tell them by default; tests set it.
var foldCase = runtime.GOOS == "darwin" || runtime.GOOS == "windows"
// ruleHome is the home folder a rule's ~ stands for; tests set it.
var ruleHome = func() string { h, _ := os.UserHomeDir(); return h }
var (
drivePath = regexp.MustCompile(`^[A-Za-z]:(/|$)`)
wslMount = regexp.MustCompile(`^/mnt/([A-Za-z])(/|$)`)
wslShare = regexp.MustCompile(`(?i)^//wsl(\$|\.localhost)/[^/]+(/|$)`)
)
// folderKey puts a folder the one way it is compared: forward slashes, ~
// as the home folder, a Windows drive as WSL mounts it (C:\x and
// /mnt/c/x are one), a WSL distro's share as the distro's own path
// (\\wsl$\Ubuntu\home\x is /home/x), no trailing slash, and without case
// where the system's folders have none (a drive's always). "" when it
// isn't a whole path.
func folderKey(p string) string {
p = strings.ReplaceAll(strings.TrimSpace(p), `\`, "/")
if p == "~" || strings.HasPrefix(p, "~/") {
h := strings.ReplaceAll(ruleHome(), `\`, "/")
if h == "" {
return ""
}
p = h + p[1:]
}
fold := foldCase
if m := wslShare.FindString(p); m != "" {
p = "/" + p[len(m):]
}
if drivePath.MatchString(p) {
p = "/mnt/" + strings.ToLower(p[:1]) + p[2:]
}
if m := wslMount.FindStringSubmatch(p); m != nil {
p = "/mnt/" + strings.ToLower(m[1]) + p[len("/mnt/")+1:]
fold = true // a Windows drive, from either side
}
if !strings.HasPrefix(p, "/") {
return ""
}
p = path.Clean(p)
if fold {
p = strings.ToLower(p)
}
return p
}
// FolderUnder reports whether folder is root or a folder inside it: at a
// path's boundary, so /a/b is not under /a/bc. An unknown folder ("") is
// under none.
func FolderUnder(folder, root string) bool {
f, r := folderKey(folder), folderKey(root)
if f == "" || r == "" {
return false
}
return f == r || r == "/" || strings.HasPrefix(f, r+"/")
}
// cleanFolder checks a rule's folder is a whole path, ~/x or C:\x, and
// keeps it as the user typed it but for a trailing slash.
func cleanFolder(p string) (string, error) {
p = strings.TrimSpace(p)
if t := strings.TrimRight(p, `/\`); t != "" && !(len(t) == 2 && t[1] == ':') {
p = t // the root, and a drive's, keep theirs
}
if p != "~" && !strings.HasPrefix(p, "~/") && !strings.HasPrefix(p, `~\`) && !strings.HasPrefix(p, "/") && !strings.HasPrefix(p, `\\`) && !drivePath.MatchString(strings.ReplaceAll(p, `\`, "/")) {
return "", fmt.Errorf("the folder %q is not a whole path (/Users/me/work, ~/work, C:\\work)", p)
}
return p, nil
}
+154
View File
@@ -0,0 +1,154 @@
package provider
import (
"slices"
"strings"
"testing"
)
func folderEnv(t *testing.T, fold bool, home string) {
t.Helper()
oldFold, oldHome := foldCase, ruleHome
foldCase, ruleHome = fold, func() string { return home }
t.Cleanup(func() { foldCase, ruleHome = oldFold, oldHome })
}
// A folder is under a rule's folder at a path's boundary only, ~ is the
// home folder, a Windows drive is one with its WSL mount and a WSL
// distro's share with the distro's own path, and case counts only where
// the system's folders have it.
func TestFolderUnder(t *testing.T) {
folderEnv(t, false, "/home/me")
for _, tc := range []struct {
folder, root string
want bool
}{
{"/a/b", "/a/b", true},
{"/a/b/c", "/a/b", true},
{"/a/b/", "/a/b", true},
{"/a/b", "/a/b/", true},
{"/a/bc", "/a/b", false},
{"/a", "/a/b", false},
{"/a/b/../x", "/a/b", false},
{"/A/B", "/a/b", false}, // Linux: case counts
{"/home/me/work/acme", "~/work", true},
{"/home/me/work", "~", true},
{"/home/mex", "~", false},
{"/home/me/x", "~/", true},
{`C:\Users\me\work\acme`, `C:\Users\me\work`, true},
{`c:\users\ME\work\acme`, `C:\Users\me\work`, true}, // a drive: no case, from either side
{"/mnt/c/Users/me/work/acme", `C:\Users\me\work`, true},
{`C:\Users\me\work`, "/mnt/c/users/me/work", true},
{"/mnt/c/Users/me/workx", `C:\Users\me\work`, false},
{"/home/me/proj", `\\wsl$\Ubuntu\home\me`, true},
{"/home/me/proj", `\\wsl.localhost\Ubuntu-24.04\home\me\proj`, true},
{"/x", "/", true},
{"", "/", false}, // the agent didn't say: no rule matches it
{"", "~", false},
{"relative/x", "/", false},
} {
if got := FolderUnder(tc.folder, tc.root); got != tc.want {
t.Errorf("FolderUnder(%q, %q) = %v, want %v", tc.folder, tc.root, got, tc.want)
}
}
folderEnv(t, true, "/Users/Me")
for _, tc := range []struct {
folder, root string
want bool
}{
{"/users/me/Work/Acme", "~/work", true}, // macOS, Windows: no case
{"/Users/Me/Workshop", "~/work", false},
} {
if got := FolderUnder(tc.folder, tc.root); got != tc.want {
t.Errorf("fold: FolderUnder(%q, %q) = %v, want %v", tc.folder, tc.root, got, tc.want)
}
}
folderEnv(t, true, "")
if FolderUnder("/x/y", "~") {
t.Error("~ with no home folder known matched")
}
}
// A rule's folders are whole paths, kept as typed but for a trailing
// slash; a pause rule can't have them; folders alone are a condition.
func TestRuleFoldersCleaned(t *testing.T) {
members := []string{"a/m", "b/m"}
out, err := cleanRules([]Rule{{Use: "b/m", Folders: []string{" ~/work/acme/ ", "", "~/work/acme", `C:\work\`, "/", `C:\`}}}, members)
if err != nil {
t.Fatal(err)
}
if want := []string{"~/work/acme", `C:\work`, "/", `C:\`}; !slices.Equal(out[0].Folders, want) {
t.Errorf("folders %q, want %q", out[0].Folders, want)
}
if c := out[0].Conditions(); !slices.Equal(c, []string{`folder ~/work/acme|C:\work|/|C:\`}) {
t.Errorf("conditions %q", c)
}
for _, bad := range []Rule{
{Use: "b/m", Folders: []string{"work/acme"}},
{Use: "b/m", Folders: []string{"~work"}},
{Use: "b/m", Pause: true, Folders: []string{"/x"}},
{Use: "b/m", Folders: []string{" "}}, // nothing left: no condition
} {
if _, err := cleanRules([]Rule{bad}, members); err == nil {
t.Errorf("%+v was taken", bad)
}
}
}
// A rule by folder matches a request from under one of its folders, with
// its other conditions, and never one whose folder isn't known.
func TestRuleMatchesByFolder(t *testing.T) {
folderEnv(t, false, "/home/me")
r := Rule{Use: "b/m", Folders: []string{"~/work/acme", "/srv/oss"}}
for _, tc := range []struct {
q RuleRequest
want bool
}{
{RuleRequest{Folder: "/home/me/work/acme"}, true},
{RuleRequest{Folder: "/home/me/work/acme/web"}, true},
{RuleRequest{Folder: "/srv/oss/x"}, true},
{RuleRequest{Folder: "/home/me/work/acme-old"}, false},
{RuleRequest{Folder: "/home/me/work"}, false},
{RuleRequest{}, false},
} {
if got := r.Matches(tc.q); got != tc.want {
t.Errorf("%+v: %v", tc.q, got)
}
}
both := Rule{Use: "b/m", Folders: []string{"/srv/oss"}, Tokens: 1000}
if both.Matches(RuleRequest{Folder: "/srv/oss", Tokens: 10}) || !both.Matches(RuleRequest{Folder: "/srv/oss", Tokens: 2000}) {
t.Error("a folder and a length: both must hold")
}
if MatchRule([]Rule{{Use: "a/m", Agents: []string{"codex"}}, r}, RuleRequest{Agent: "claude", Folder: "/srv/oss"}) != 1 {
t.Error("the rule by folder after one by agent")
}
}
// folders= is typed as other words are, comma separated, quoted when a
// folder has a space, and read back the same.
func TestParseRuleFolders(t *testing.T) {
g := Group{ID: "g", Members: []string{"a/m", "b/x"}}
r, _, _, err := ParseRule(g, RuleWords(`use=x folders="~/My Project,/srv/oss/" tokens=10k`))
if err != nil {
t.Fatal(err)
}
if !slices.Equal(r.Folders, []string{"~/My Project", "/srv/oss"}) {
t.Fatalf("folders %q", r.Folders)
}
line := r.Line()
if !strings.Contains(line, `folders="~/My Project,/srv/oss"`) {
t.Errorf("line %s", line)
}
back, _, _, err := ParseRule(g, RuleWords(line))
if err != nil || !slices.Equal(back.Folders, r.Folders) {
t.Errorf("read back %q: %v", back.Folders, err)
}
if r, _, _, err := ParseRule(g, RuleWords(`use=x folder=~/a`)); err != nil || r.Line() != "use=b/x folders=~/a" {
t.Errorf("%q %v", r.Line(), err)
}
for _, bad := range []string{`use=x folders=`, `use=x folders=work`, `pause=x time=09:00-18:00 folders=/a`} {
if _, _, _, err := ParseRule(g, RuleWords(bad)); err == nil {
t.Errorf("%s was taken", bad)
}
}
}
+25 -3
View File
@@ -1,7 +1,8 @@
package provider
// A rule as it is typed: use=<model> tokens=200k images effort=high
// agents=a,b intent="…" compact time=09:00-18:00 days=mon-fri, or
// agents=a,b intent="…" compact time=09:00-18:00 days=mon-fri
// folders=~/work,"~/My Project", or
// pause=<model> time=… days=… agents=… — by magpie group rule and the
// TUI's routing page.
@@ -155,6 +156,20 @@ func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err
r.Time = &TimeWindow{From: "00:00", To: "00:00"} // the whole day, unless time= says
}
r.Time.Days = days
case "folders", "folder", "in", "project", "projects":
for _, p := range strings.Split(v, ",") {
if p = strings.TrimSpace(p); p == "" {
continue
}
c, err := cleanFolder(p)
if err != nil {
return r, 0, "", err
}
r.Folders = append(r.Folders, c)
}
if len(r.Folders) == 0 {
return r, 0, "", fmt.Errorf("folders names the working folders it holds in: folders=~/work/acme,~/oss")
}
case "classifier", "classify", "by":
if classifier = strings.TrimSpace(v); classifier == "" {
return r, 0, "", fmt.Errorf("classifier=<model>: the model that tells which intent a message is")
@@ -166,13 +181,13 @@ func ParseRule(g Group, words []string) (r Rule, at int, classifier string, err
}
at = n
default:
return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, pause, tokens, images, effort, agents, intent, compact, time, days, classifier, at)", w)
return r, 0, "", fmt.Errorf(UnknownRuleWord+"%q (use, pause, tokens, images, effort, agents, intent, compact, time, days, folders, classifier, at)", w)
}
}
if r.Use == "" {
return r, 0, "", fmt.Errorf("use=<model> (or pause=<model>) is missing: one of %s", strings.Join(g.Members, ", "))
}
if r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact) {
if r.Pause && (r.Tokens > 0 || r.Images || r.Effort != "" || r.Intent != "" || r.Compact || len(r.Folders) > 0) {
return r, 0, "", fmt.Errorf("pause=<model> holds by time=, days= or agents= only")
}
if r.Pause && r.Time == nil && len(r.Agents) == 0 {
@@ -276,5 +291,12 @@ func (r Rule) Line() string {
out = append(out, "days="+strings.ReplaceAll(strings.ToLower(r.Time.DaysText()), "–", "-"))
}
}
if len(r.Folders) > 0 {
v := strings.ReplaceAll(strings.Join(r.Folders, ","), `"`, "")
if strings.ContainsAny(v, " \t") {
v = `"` + v + `"`
}
out = append(out, "folders="+v)
}
return strings.Join(out, " ")
}
+1 -1
View File
@@ -282,7 +282,7 @@ func (m *model) openClassifier(g provider.Group) {
// ruleHint is what a rule is typed as.
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 (local; 22:00-08:00 runs past midnight) · days=mon-fri · at=<n> for its place
time=09:00-18:00 (local; 22:00-08:00 runs past midnight) · days=mon-fri · folders=~/work/acme,~/oss · at=<n> for its place
or pause=<model> time=… days=… agents=…: the model is left out of the group then, not even a fallback`
// openRule asks for a rule: a new one, or rule i (from 0) typed again.
+4 -2
View File
@@ -184,7 +184,7 @@
<tr><td>オフ <code>off</code></td><td>リクエストごとに改めてルーティングします。</td></tr>
</table></div>
<h3 id="rules">ルール · ターンを指定したモデルへ</h3>
<p>グループの <span class="ui">Rules</span> は、指定した種類のターンをグループ内の特定のモデルに送ります。種類とは、長いもの(<code>tokens ≥ N</code>)、画像を含むもの、推論を求めるもの(オン、または一定レベル以上)、特定のエージェントからのもの、あなたが記述した内容を求めるもの(<em>インテント</em>)、エージェントがコンテキストを圧縮するもの、です。メッセージを送ると上から順に評価され、最初に一致したルールのモデルが先頭になり、失敗したときはグループの他のモデルが後に続きます。どのルールにも一致しないターンは、グループの通常のルーティングに従い、それまでの送り先に留まります。</p>
<p>グループの <span class="ui">Rules</span> は、指定した種類のターンをグループ内の特定のモデルに送ります。種類とは、長いもの(<code>tokens ≥ N</code>)、画像を含むもの、推論を求めるもの(オン、または一定レベル以上)、特定のエージェントからのもの、あなたが記述した内容を求めるもの(<em>インテント</em>)、エージェントがコンテキストを圧縮するもの、特定のフォルダ(プロジェクト)で作業しているもの、です。ルールの条件はすべて満たす必要があるので、「~/work/acme 内で、かつ長い」のようにも書けます。メッセージを送ると上から順に評価され、最初に一致したルールのモデルが先頭になり、失敗したときはグループの他のモデルが後に続きます。どのルールにも一致しないターンは、グループの通常のルーティングに従い、それまでの送り先に留まります。</p>
<ul>
<li>ルールはターンの開始時に決まり、エージェントがツールの結果を返している間もそのターンは同じモデルに留まるため、ベンダーのキャッシュが途中で失われません。唯一の例外として、ターンがモデルのコンテキストを超えて大きくなった場合は、それを受け付けられるメンバーに移ります。</li>
<li>トークン数は、リクエストのサイズから推定した値と、会話の直前のリクエストでベンダーが数えた値のうち、大きいほうを使います。余裕を持たせてください。200k のモデルなら、ルールは 199k ではなく 150k にします。</li>
@@ -192,7 +192,8 @@
<li>インテントは、ユーザーが求めていることを数語で表したものです(「テストを書く・直す」「ちょっとした質問」など)。ターンの開始時に、グループの分類モデル(magpie にある任意のモデル。小さく高速で推論なしのものが最適です)に、一致しうるインテントのうちユーザーのメッセージがどれに当たるかを一度だけ尋ねます。送られるのはそのメッセージだけで、会話全体ではありません。分類モデルが失敗した、遅すぎた(8 秒)、または判断できなかった場合は、どのインテントも一致せず、そのターンは他のルールに従います。インテントのないルールでいずれにせよ決まる場合は問い合わせず、同じメッセージについて二度尋ねることもありません。その呼び出しは使用量に magpie 自身の呼び出しとして表示されます。何を尋ねるのか、回答がどう使われるのか、失敗したらどうなるのかの詳細は<a href="/docs/ja/intent">インテントルーティング</a>を参照してください。</li>
<li><span class="ui">compacting</span> は、エージェントが会話を圧縮するとき(Claude Code の <code>/compact</code> と自動圧縮、Codex、OpenCode、Pi、Gemini CLI、Qwen Code、Kimi Code)に一致します。これにより、会話は元のモデルのまま、要約だけをより安く速いモデルに書かせられます。圧縮は単独で判断されます。圧縮が起きたターンとそのキャッシュは元の送り先に留まります。会話がルールのモデルが受け付けられる長さを超えている場合は、次に一致するルール、またはグループの順序で決まります。</li>
<li><b>時間帯と曜日。</b>ルールは、このコンピューターの時計で、特定の時間帯や曜日だけ有効にできます(ベンダーのピーク時間など)。その間のターンを別のモデルに送るルールでは、ベンダーのモデルはフォールバックとして後ろに残ります。完全に外すには、ルールの <span class="ui">送信先</span> を <span class="ui">一時停止</span> に変えます。ルールが有効な間(時間帯、曜日、エージェント)、そのモデルはグループから外れ、先頭にもフォールバックにもならず、会話の継続でも使われません。時間帯が終われば戻ります。一時停止は時間帯、曜日、エージェントだけで判断し、グループのモデルがすべて一時停止中ならエージェントにそう伝えます。</li>
<li>ルーティングタブには、各ターンをどのルールがどこへ送ったか、分類モデルが何と答えたかが表示されます。</li>
<li><b>フォルダ。</b><span class="ui">フォルダ</span> は、エージェントの作業フォルダが指定したフォルダのどれか、またはその中にあるときに一致します。<code>~/work/acme</code> は <code>~/work/acme/web</code> を含み、<code>~/work/acme-old</code> は含みません。フォルダはエージェントがリクエストでモデルに伝えるもの(Claude Code、Codex、OpenCode、Pi が伝えます)なので、伝えないエージェントはフォルダのルールに一致しません。<code>~</code> はホームフォルダ、<code>C:\work</code> は WSL の <code>/mnt/c/work</code> と同じで、macOS と Windows では大文字小文字を区別しません。</li>
<li>ルーティングタブには、各ターンをどのルールがどこへ送ったか、分類モデルが何と答えたか、エージェントが伝えた作業フォルダが表示されます。</li>
</ul>
<h3 id="nested">グループの中のグループ</h3>
<p>グループのモデルには別のグループも含められます。<span class="ui">Add a model</span> の <em>Routing groups</em> の下から選ぶか、ターミナルで <code>models+=group/&lt;id&gt;</code> を使います。中に入ったグループは順序の中でその位置を占め、自分のモデルの間では自分のルーティングとルールに従って振り分けます。たとえば Coder を <code>deepseek-v4-pro</code>、次に <em>Fast</em> とし、Fast は安いモデルを独自の順序で並べる、といった構成ができます。Coder のルールでターンを <code>group/fast</code> に送れば、どのモデルを先にするかは Fast 自身のルールが決めます。</p>
@@ -217,6 +218,7 @@ magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5
magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k <span class="c"># 長いターンはまずこれへ</span>
magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=<span class="s">"ちょっとした質問"</span> classifier=groq/llama-3.1-8b-instant
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact <span class="c"># /compact の要約は安いモデルへ</span>
magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,<span class="s">"~/My Project"</span> <span class="c"># これらのプロジェクトのターンはまずこのモデルへ</span>
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 set coder models+=group/opus-anywhere <span class="c"># グループの中のグループ</span>
magpie group rule opus-anywhere <span class="c"># ルール一覧。rule rm|mv &lt;n&gt;、rule classifier &lt;group&gt; &lt;model&gt;</span>
+4 -2
View File
@@ -184,7 +184,7 @@
<tr><td>Off <code>off</code></td><td>Every request is routed afresh.</td></tr>
</table></div>
<h3 id="rules">Rules · a turn to a chosen model</h3>
<p>A group’s <span class="ui">Rules</span> send a turn to one of its models when the turn is of a kind you name: long (<code>tokens ≥ N</code>), carrying an image, asking for reasoning (on, or at least a level), from certain agents, asking for something you describe (an <em>intent</em>), or the agent compacting its context. They are looked at top first when you send a message; the first that matches puts its model first, with the group’s others behind it if it fails. A turn no rule matches is routed as the group always routes, and keeps to where it was.</p>
<p>A group’s <span class="ui">Rules</span> send a turn to one of its models when the turn is of a kind you name: long (<code>tokens ≥ N</code>), carrying an image, asking for reasoning (on, or at least a level), from certain agents, asking for something you describe (an <em>intent</em>), the agent compacting its context, or working in one of some folders (a project). A rule’s conditions all have to hold, so one can say “in ~/work/acme, and long”. They are looked at top first when you send a message; the first that matches puts its model first, with the group’s others behind it if it fails. A turn no rule matches is routed as the group always routes, and keeps to where it was.</p>
<ul>
<li>A rule decides as a turn begins, and the turn stays on that model while the agent sends tool results back, so what the vendor cached isn’t lost halfway. The one exception: a turn that grows past its model’s context moves to a member that takes it.</li>
<li>Tokens are estimated from the request’s size, or what the vendor counted for the conversation’s last request, whichever is more. Leave some margin: a rule at 150k for a 200k model, not 199k.</li>
@@ -192,7 +192,8 @@
<li>An intent is a few words for what the user asks for — “writing or fixing tests”, “a quick question”. As a turn begins, the group’s classifier — any model magpie has; a small, fast one without reasoning is best — is asked once which of the intents that could match the user’s message is. Only the message is sent, not the conversation. If it fails, is slow (8 s) or can’t say, no intent matches and the turn goes by the other rules. It isn’t asked when a rule without an intent would decide anyway, and the same message isn’t asked about twice. Its calls show in Usage as magpie’s own. Exactly what it is asked, how its answer is used and what happens when it fails: <a href="/docs/intent">Intent routing</a>.</li>
<li><span class="ui">compacting</span> matches an agent compacting its conversation — Claude Code’s <code>/compact</code> and auto-compact, Codex, OpenCode, Pi, Gemini CLI, Qwen Code, Kimi Code — so a cheaper, faster model writes the summary while the conversation stays on its own. A compaction is decided on its own: the turn it happens in, and its cache, stay where they were. When the conversation is longer than the rule’s model takes, the next rule that matches, or the group’s order, decides instead.</li>
<li><b>Hours and days.</b> A rule can hold only at some hours, on some days, by this computer’s clock — a vendor’s peak hours, say. A rule that sends those turns elsewhere still leaves the vendor’s model behind it for failover. To keep a model out entirely, turn the rule’s <span class="ui">send to</span> into <span class="ui">pause</span>: while it holds (its hours and days, its agents), that model is left out of the group — never first, never a fallback, not kept for the conversation it was in — and it is back once they end. A pause holds by hours, days and agents only; if every model of the group is paused, the agent is told so.</li>
<li>The Routing tab says which rule sent each turn where, and what the classifier said.</li>
<li><b>Folders.</b> <span class="ui">in folder</span> matches a turn from an agent working in one of the folders you list, or a folder inside one: <code>~/work/acme</code> takes <code>~/work/acme/web</code>, not <code>~/work/acme-old</code>. The folder is the one the agent tells its model in the request — Claude Code, Codex, OpenCode and Pi say it — so an agent that doesn’t say its folder matches no folder rule. <code>~</code> is your home folder, <code>C:\work</code> is also WSL’s <code>/mnt/c/work</code>, and on macOS and Windows case doesn’t count.</li>
<li>The Routing tab says which rule sent each turn where, what the classifier said, and the folder the agent said it was in.</li>
</ul>
<h3 id="nested">Groups in groups</h3>
<p>A group’s models can include another group: pick it under <em>Routing groups</em> in <span class="ui">Add a model</span>, or <code>models+=group/&lt;id&gt;</code> from a terminal. The group in it takes its place in the order and routes among its own models by its own routing and rules. So Coder can be <code>deepseek-v4-pro</code> then <em>Fast</em>, and Fast its own order of cheap models. A Coder rule can send a turn to <code>group/fast</code>, and Fast’s own rules then pick which of its models goes first.</p>
@@ -217,6 +218,7 @@ magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5
magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k <span class="c"># long turns to it first</span>
magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=<span class="s">"a quick question"</span> classifier=groq/llama-3.1-8b-instant
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact <span class="c"># /compact summaries to a cheap model</span>
magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,<span class="s">"~/My Project"</span> <span class="c"># turns in those projects to it first</span>
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 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 &lt;n&gt;, rule classifier &lt;group&gt; &lt;model&gt;</span>
+4 -2
View File
@@ -184,7 +184,7 @@
<tr><td>关闭 <code>off</code></td><td>每个请求都重新路由。</td></tr>
</table></div>
<h3 id="rules">规则 · 把某类对话交给指定模型</h3>
<p>路由组的 <span class="ui">规则</span> 把符合条件的一轮对话交给组里指定的模型:够长(<code>tokens ≥ N</code>)、带图片、要求推理(开启,或不低于某个强度)、来自某些 Agent,用户想做的事符合你描述的<em>意图</em>,或者 Agent 正在压缩上下文。每次你发新消息时从上往下检查,第一条命中的规则把它的模型排在最前,其余成员排在后面做故障转移。没有命中任何规则的一轮照组本来的方式路由,并保持在原来的账号上。</p>
<p>路由组的 <span class="ui">规则</span> 把符合条件的一轮对话交给组里指定的模型:够长(<code>tokens ≥ N</code>)、带图片、要求推理(开启,或不低于某个强度)、来自某些 Agent,用户想做的事符合你描述的<em>意图</em>、Agent 正在压缩上下文,或者 Agent 在某些文件夹(项目)里工作。一条规则的条件要同时满足,所以可以写“在 ~/work/acme 里,并且够长”。每次你发新消息时从上往下检查,第一条命中的规则把它的模型排在最前,其余成员排在后面做故障转移。没有命中任何规则的一轮照组本来的方式路由,并保持在原来的账号上。</p>
<ul>
<li>规则只在一轮开始时决定;Agent 回传工具结果的过程中一直留在那个模型上,不会半途换掉而丢掉厂商的缓存。唯一例外:这一轮涨到超过所在模型的上下文,会换到装得下的成员。</li>
<li>token 数取请求大小的估算与厂商对这个会话上一个请求的计数中较大的一个。请留出余量:给 200k 的模型设 150k,而不是 199k。</li>
@@ -192,7 +192,8 @@
<li>意图是用几个词描述用户想做什么,例如“写或修测试”“一个简单问题”。每一轮开始时,magpie 会问一次组里指定的意图判断模型:用户这条消息属于哪个可能命中的意图。这个模型可以是 magpie 里的任意模型,建议选小而快、不带推理的。发过去的只有这条消息,不包括整段对话。它出错、超时(8 秒)或给不出答案时,意图条件都不命中,这一轮按其他规则走。如果前面有不带意图的规则已经能决定,就不会去问;同一条消息也不会问两次。它的调用在用量里显示为 magpie 自己的调用。它具体被问了什么、回答怎么用、失败时怎么办,详见<a href="/docs/zh/intent">意图路由</a>。</li>
<li><span class="ui">压缩上下文时</span>:Agent 压缩对话上下文时命中——Claude Code 的 <code>/compact</code> 和自动压缩、Codex、OpenCode、Pi、Gemini CLI、Qwen Code、Kimi Code——让更便宜、更快的模型来写总结,对话本身仍留在原来的模型上。压缩请求单独决定:它所在的这一轮和缓存都留在原处。对话比规则里的模型能装下的还长时,改由下一条命中的规则或组本来的顺序决定。</li>
<li><b>时段和星期。</b>规则可以只在某些时段、某几天生效,按这台电脑的时钟——比如厂商的高峰期。把这段时间的对话“先发给”别的模型,厂商那个模型仍排在后面做故障转移。要把它完全拿掉,把规则里的 <span class="ui">先发给</span> 改成 <span class="ui">暂停</span>:规则生效期间(它的时段、星期和 Agent),这个模型移出分组——不排第一、不做备用、也不会因为会话粘性被留住——时段过了自动回来。暂停只按时段、星期和 Agent 判断;组里所有模型都被暂停时,会告诉 Agent。</li>
<li>路由标签页会显示每一轮是被哪条规则送到哪里的,以及意图判断模型给出的答案。</li>
<li><b>文件夹。</b><span class="ui">项目文件夹</span>:Agent 的工作目录是你列出的文件夹之一或其子文件夹时命中:<code>~/work/acme</code> 包括 <code>~/work/acme/web</code>,不包括 <code>~/work/acme-old</code>。文件夹以 Agent 在请求里告诉模型的为准——Claude Code、Codex、OpenCode 和 Pi 都会说——不说明工作目录的 Agent 不会命中任何按文件夹的规则。<code>~</code> 是你的主目录,<code>C:\work</code> 也就是 WSL 里的 <code>/mnt/c/work</code>,macOS 和 Windows 上不区分大小写。</li>
<li>路由标签页会显示每一轮是被哪条规则送到哪里的、意图判断模型给出的答案,以及 Agent 说的工作目录。</li>
</ul>
<h3 id="nested">路由组里放路由组</h3>
<p>路由组的成员也可以是另一个路由组:在 <span class="ui">添加模型</span> 的 <em>路由组</em> 分类里选它,或者在终端里用 <code>models+=group/&lt;id&gt;</code>。子组占据它在顺序里的位置,在自己的模型之间按自己的路由方式和规则分配。比如 Coder 可以是 <code>deepseek-v4-pro</code>,然后是 <em>Fast</em>,而 Fast 是几个便宜模型的顺序。Coder 的规则可以把一轮对话交给 <code>group/fast</code>,再由 Fast 自己的规则决定它里面哪个模型排第一。</p>
@@ -217,6 +218,7 @@ magpie group set opus-anywhere models+=openrouter/anthropic/claude-opus-5.5
magpie group rule add opus-anywhere use=openrouter/anthropic/claude-opus-5.5 tokens=150k <span class="c"># 长对话优先发给它</span>
magpie group rule add opus-anywhere use=copilot/claude-opus-5.5 intent=<span class="s">"一个简单问题"</span> classifier=groq/llama-3.1-8b-instant
magpie group rule add opus-anywhere use=deepseek/deepseek-v4-flash compact <span class="c"># /compact 的总结交给便宜的模型</span>
magpie group rule add opus-anywhere use=kimi/kimi-k2.6 folders=~/oss,<span class="s">"~/My Project"</span> <span class="c"># 这些项目里的对话先发给它</span>
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 set coder models+=group/opus-anywhere <span class="c"># 路由组里放路由组</span>
magpie group rule opus-anywhere <span class="c"># 查看规则;rule rm|mv &lt;n&gt;,rule classifier &lt;组&gt; &lt;模型&gt; 换判断模型</span>