Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

routing: a rule's agent picker lists agents heard from and takes a typed User-Agent name (raikyou on Discord)

yetonee5b57794e22d
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 5dd154cf5..cc807e91f 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -93,6 +93,7 @@ recorded as a prediction failure (`noPrediction`).
- The classifier's requests are magpie's own (#1839). Asked in words, they go out with `RouterAgent`'s User-Agent (`magpie-router/1`), so their records' agent is magpie and `callKind` marks them `routing`; a decision model's (Jev, System One) record is written with `Kind: "routing"` too. They go to the same key or account as any other request and count in its totals, while `usage.Group.Own` (`Record.ByMagpie`: agent `magpie` or one of its `magpie-` User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (`modelRef.Sub`, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (`classifierSub` in `plugins/routing/client.js`). `TestIntentRoutesATurn`, `TestJevPicksTheIntent`, `TestSummaryCountsMagpiesOwnCallsApart`, `TestByMagpie`, `TestServedRefSaysASubscription`, `own-requests.test.cjs`.
- 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 as the agent asked. 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$\<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. 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: <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 `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-<name>` 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 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, 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=<model> 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`.
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`). 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`). 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: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap <id> 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap <id> off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). The shortest cap otherwise is a minute, the first rest; `rest-cap <id> 30s` is turned away and names `off`. 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 Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). 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 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). 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. A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. 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. A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest only: the backoff count stays, and a refusal after it rests the key again the usual way. 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`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. 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. Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`).
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index e48f9b8c6..bcaa9562e 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -4605,7 +4605,7 @@ function openPicker(agent, field, anchor, ev, only) {
}
const q = $("#q");
q.value = "";
- q.placeholder = modelPicker && extra(field) ? t("{field} — filter, or type any model id…", { field: t(field.label) }) : modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) });
+ q.placeholder = field.placeholder || (modelPicker && extra(field) ? t("{field} — filter, or type any model id…", { field: t(field.label) }) : modelPicker ? t("Filter, or type any model id…") : t("Filter {field}…", { field: t(field.label) }));
filter();
// On touch screens leave the keyboard closed until the filter is tapped,
// so opening a model list leaves room to browse its choices.
@@ -4843,6 +4843,14 @@ function filter(keep) {
if (typed && pick.free && ["model", "small", "large", "executor", "planner", ...ROLE_MODELS].includes(pick.field.label) && !pick.items.some((o) => o.value === typed)) {
pick.items.push({ value: typed, note: t("use as typed"), custom: true });
}
+ // a picker that takes a name it doesn't list (a rule's agents: one known
+ // only by its User-Agent) offers what is typed as the field reads it, or
+ // the option that name already is
+ const own = typed && pick.field.typed?.(typed);
+ if (own) {
+ const listed = pick.options.find((o) => o.value === own.value);
+ if (!pick.items.includes(listed)) pick.items.push(listed || { ...own, custom: true });
+ }
pick.items = foldSame(pick.items);
// a model the filter finds among those kept for routing groups, which
// aren't offered: said why, rather than missing without a word
diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js
index 7b209f36a..b8344c91c 100644
--- a/internal/gui/assets/plugins/routing/client.js
+++ b/internal/gui/assets/plugins/routing/client.js
@@ -465,6 +465,11 @@ function routingPage(part) {
const LONE = "Only one account or key is on for this, so routing has nothing to choose between. Turn on a second in the provider's editor, and how it routes is set under Several accounts or keys below.";
const agentOf = (id) => (state.clients || state.agents).find((a) => a.id === id);
+ // uaName is a client as the gateway names one it doesn't know
+ // (usage.AgentOf): its User-Agent's product name, before the first / or
+ // space, in lower case as a rule keeps it. "SillyTavern/1.12" is
+ // sillytavern; a comma would part it in two (ParseRule)
+ const uaName = (s) => String(s || "").trim().split(/[\/\s,]/)[0].toLowerCase();
const agentName = (id) => agentOf(id)?.name || (id && id !== "other" ? id : t("your agent"));
// who names an account or key in a sentence
const who = (w) => w.kind === "provider" ? w.name : w.who;
@@ -4440,6 +4445,13 @@ function routingPage(part) {
// More are picked with the model picker the agents use.
const infoOf = (id) => g?.memberInfo?.find((x) => x.id === id);
const pickFrom = (label, anchor, ev, options, onPick, value = "") => openPicker({ id: "", name: "", fields: [] }, { key: "rule", label, value, menu: true, options, onPick }, anchor, ev);
+ // the agents magpie heard from in the last 30 days that it doesn't
+ // know, by the names the gateway gave them (usage.AgentOf), asked for
+ // once while the editor is open; none when usage can't be read
+ let heardFrom = null;
+ const heard = () => heardFrom || (heardFrom = api("usage?period=30d")
+ .then((u) => (u?.agents || []).map((a) => uaName(a.id)).filter((id) => id && id !== "other" && id !== "magpie"))
+ .catch(() => []));
const box = el("div", "fallback");
const list = el("div", "fbl");
const addBtn = el("button", "rt-gadd");
@@ -5032,18 +5044,31 @@ function routingPage(part) {
wrap("compact", cp);
if (mine === "compact") focus = () => cp.focus({ preventScroll: true });
}
- // agents
+ // agents: the ones magpie knows, the others it has heard from, and
+ // any typed by the name the gateway gives a client it doesn't know
+ // (raikyou on Discord: SillyTavern, one's own app)
if (kinds.includes("agents")) {
const clients = state.clients || state.agents || [];
const agentsName = () => r.agents.length ? r.agents.map((id) => clients.find((a) => a.id === id)?.name || id).join(", ") : t("any agent");
const ag = el("button", "rt-cond" + (r.agents.length ? " on" : ""), agentsName());
- ag.onclick = (ev) => pickFrom("agent", ag, ev, [
- { value: "", label: t("any agent"), note: t("not a condition") },
- ...clients.map((a) => ({ value: a.id, label: a.name, icon: a.icon, note: r.agents.includes(a.id) ? "✓" : "" })),
- ], (v) => {
- r.agents = !v ? [] : r.agents.includes(v) ? r.agents.filter((x) => x !== v) : [...r.agents, v];
- ag.textContent = agentsName(); ag.classList.toggle("on", r.agents.length > 0); warn();
- });
+ heard();
+ ag.onclick = async (ev) => {
+ ev.stopPropagation();
+ const known = new Set(clients.map((a) => a.id));
+ const others = [...(await heard()), ...r.agents].filter((id, i, all) => !known.has(id) && all.indexOf(id) === i);
+ const tick = (id) => r.agents.includes(id) ? "✓" : "";
+ openPicker({ id: "", name: "", fields: [] }, { key: "rule", label: "agent", value: "", menu: true,
+ placeholder: t("Filter, or type an agent's name…"),
+ typed: (s) => { const id = uaName(s); return id && { value: id, label: id, note: t("the name its User-Agent begins with") }; },
+ options: [
+ { value: "", label: t("any agent"), note: t("not a condition") },
+ ...clients.map((a) => ({ value: a.id, label: a.name, icon: a.icon, note: tick(a.id) })),
+ ...others.map((id) => ({ value: id, label: id, icon: "generic", note: tick(id) || t("heard from in the last 30 days") })),
+ ], onPick: (v) => {
+ r.agents = !v ? [] : r.agents.includes(v) ? r.agents.filter((x) => x !== v) : [...r.agents, v];
+ ag.textContent = agentsName(); ag.classList.toggle("on", r.agents.length > 0); warn();
+ } }, ag, ev);
+ };
wrap("agents", ag);
if (mine === "agents") focus = () => { ag.focus({ preventScroll: true }); ag.onclick({ stopPropagation() {} }); };
}
diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js
index 77aeaac09..bab1bfde3 100644
--- a/internal/gui/assets/plugins/routing/i18n.js
+++ b/internal/gui/assets/plugins/routing/i18n.js
@@ -2,6 +2,9 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
+ "Filter, or type an agent's name…": "筛选,或输入 Agent 名称…",
+ "the name its User-Agent begins with": "User-Agent 开头的名称",
+ "heard from in the last 30 days": "近 30 天有请求",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie 为子代理设定的推理强度是 {effort};仍按模型支持的等级适配,并保留路由组成员的固定强度。",
"{agent}'s call to magpie's web_search MCP tool": "{agent} 对 magpie 的 web_search MCP 工具的调用",
"{agent}'s {model}": "{agent} 的 {model}",
@@ -532,6 +535,9 @@ magpie.strings({
"{h} h {m} min": "{h} 小时 {m} 分钟",
},
"zh-TW": {
+ "Filter, or type an agent's name…": "篩選,或輸入 Agent 名稱…",
+ "the name its User-Agent begins with": "User-Agent 開頭的名稱",
+ "heard from in the last 30 days": "近 30 天有請求",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie 為子代理設定的推理強度是 {effort};仍按模型支援的等級適配,並保留路由群組成員的固定強度。",
"{agent} guessed your next message for its composer by itself, reading the whole conversation again. Not a turn of the conversation; Settings › General › Codex composer predictions picks its model, and Codex's Settings › General › Show predictions turns it off.": "{agent} 自行為輸入框猜測你的下一則訊息,每次都把整段對話重讀一遍。不屬於對話輪次;在 設定 › 常規 › Codex 輸入框預測 裡選它用的模型,在 Codex 的 設定 › 一般 › 顯示預測內容 裡可以關掉。",
"{agent}'s call to magpie's web_search MCP tool": "{agent} 對 magpie 的 web_search MCP 工具的呼叫",
@@ -1062,6 +1068,9 @@ magpie.strings({
"{h} h {m} min": "{h} 小時 {m} 分鐘",
},
ja: {
+ "Filter, or type an agent's name…": "絞り込み、またはエージェント名を入力…",
+ "the name its User-Agent begins with": "User-Agent の先頭の名前",
+ "heard from in the last 30 days": "過去 30 日にリクエストあり",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "magpie で設定したサブエージェントの推論レベルは {effort} です。モデルが対応するレベルへの調整と、ルーティンググループのメンバーに固定されたレベルは引き続き適用されます。",
"{agent}'s call to magpie's web_search MCP tool": "{agent} による magpie の web_search MCP ツールの呼び出し",
"{agent}'s {model}": "{agent} の {model}",
@@ -1592,6 +1601,9 @@ magpie.strings({
"These routing groups will no longer be available to agents.": "これらのルーティンググループはエージェントから利用できなくなります。",
},
de: {
+ "Filter, or type an agent's name…": "Filtern oder Namen eines Agenten eingeben…",
+ "the name its User-Agent begins with": "der Name, mit dem sein User-Agent beginnt",
+ "heard from in the last 30 days": "in den letzten 30 Tagen gesehen",
"The subagent effort set in magpie is {effort}; the model's supported levels and a routing group's fixed member effort still apply.": "Der in magpie gesetzte Reasoning-Effort der Subagenten ist {effort}; die unterstützten Stufen des Modells und die feste Stufe eines Mitglieds der Routing-Gruppe gelten weiterhin.",
"{agent}'s call to magpie's web_search MCP tool": "den Aufruf von {agent} an magpies MCP-Werkzeug web_search",
"{agent}'s {model}": "{model} von {agent}",
diff --git a/internal/gui/tests/routing-rule-agent-typed.test.cjs b/internal/gui/tests/routing-rule-agent-typed.test.cjs
new file mode 100644
index 000000000..1f2836b6e
--- /dev/null
+++ b/internal/gui/tests/routing-rule-agent-typed.test.cjs
@@ -0,0 +1,190 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// A rule's agents may be one magpie doesn't know (raikyou on Discord:
+// SillyTavern, one's own app with its own User-Agent). The gateway names
+// such a client by its User-Agent's product name (usage.AgentOf), and a
+// rule matches it in lower case. In the editor the agent picker offers the
+// agents magpie knows, then those usage heard from in the last 30 days that
+// it doesn't (not "other", nor magpie's own), and a name typed in the
+// filter, read as the gateway reads a User-Agent: "MyApp/2.0 (Linux)" is
+// myapp, and a name that is a known agent's is that agent. Saved as
+// agents:[…]. In every language, and at a phone's width the menu stays on
+// the screen with nothing run past the side.
+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", agents: ["codex"] }] }],
+ pools: [],
+});
+// /api/usage?period=30d's agents, as usageapi.Page names them: a known
+// one, one by its User-Agent as the gateway kept it, and the two the
+// picker leaves out
+const usage = { agents: [
+ { id: "claude", name: "Claude Code", icon: "claudecode-color", calls: 9 },
+ { id: "SillyTavern", name: "SillyTavern", icon: "generic", calls: 4 },
+ { id: "other", name: "other", icon: "generic", calls: 2 },
+ { id: "magpie", name: "magpie", icon: "generic", calls: 1 },
+] };
+
+const words = {
+ en: { edit: "Edit", save: "Save", filter: "Filter, or type an agent's name…", heard: "heard from in the last 30 days", typed: "the name its User-Agent begins with" },
+ zh: { edit: "编辑", save: "保存", filter: "筛选,或输入 Agent 名称…", heard: "近 30 天有请求", typed: "User-Agent 开头的名称" },
+ "zh-TW": { edit: "編輯", save: "儲存", filter: "篩選,或輸入 Agent 名稱…", heard: "近 30 天有請求", typed: "User-Agent 開頭的名稱" },
+ ja: { edit: "編集", save: "保存", filter: "絞り込み、またはエージェント名を入力…", heard: "過去 30 日にリクエストあり", typed: "User-Agent の先頭の名前" },
+ de: { edit: "Bearbeiten", save: "Speichern", filter: "Filtern oder Namen eines Agenten eingeben…", heard: "in den letzten 30 Tagen gesehen", typed: "der Name, mit dem sein User-Agent beginnt" },
+};
+
+function serve(lang, posts, asked) {
+ const state = {
+ agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }],
+ clients: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }, { id: "codex", name: "Codex", icon: "codex-color" }],
+ profiles: [], settings: { lang, theme: "light" },
+ };
+ 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
+ return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
+ }
+ if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
+ if (url.pathname === "/api/usage") {
+ asked.push(url.search);
+ return json(url.searchParams.get("period") === "30d" ? usage : { agents: [] });
+ }
+ 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 = [], asked = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", serve(lang, posts, asked));
+ await page.goto("http://magpie.test/?view=routing");
+ const group = page.locator(".rt-group").first();
+ await group.waitFor();
+ return { page, group, errors, posts, asked };
+}
+
+// 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);
+ await b.waitFor();
+ 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);
+}
+
+// the menu's rows, by name
+const names = (page) => page.locator("#list li .v").evaluateAll((vs) => vs.map((v) => v.textContent));
+
+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 for an agent magpie knows only by its User-Agent`, async (t) => {
+ const { page, group, errors, posts, asked } = await open(t, engine, lang, 1100);
+ await press(page, group.locator("button", { hasText: w.edit }));
+ const ed = page.locator(".rt-gedit");
+ const ag = ed.locator(".rt-rule").first().locator('.rt-c[data-k="agents"] > button.rt-cond');
+ await ag.waitFor();
+ assert.equal(await ag.textContent(), "Codex");
+
+ // the known agents, then the one usage heard from, by the gateway's name
+ await press(page, ag);
+ const q = page.locator("#q");
+ await q.waitFor();
+ assert.equal(await q.getAttribute("placeholder"), w.filter);
+ await page.waitForFunction(() => [...document.querySelectorAll("#list li .v")].some((v) => v.textContent === "sillytavern"));
+ const listed = await names(page);
+ assert.deepEqual(listed.slice(1), ["Claude Code", "Codex", "sillytavern"], `known, then heard from: ${JSON.stringify(listed)}`);
+ const heard = page.locator("#list li", { hasText: "sillytavern" });
+ assert((await heard.textContent()).includes(w.heard), `said where it came from: ${await heard.textContent()}`);
+ assert.equal(asked.filter((x) => x === "?period=30d").length, 1, `usage asked once, for 30 days: ${asked}`);
+ await press(page, heard);
+ assert.equal(await ag.textContent(), "Codex, sillytavern");
+
+ // a name typed in, as the gateway reads a User-Agent
+ await press(page, ag);
+ await q.waitFor();
+ await q.fill("MyApp/2.0 (Linux)");
+ const typed = page.locator("#list li", { hasText: "myapp" });
+ await typed.waitFor();
+ assert((await typed.textContent()).includes(w.typed), `said how it is read: ${await typed.textContent()}`);
+ await q.press("Enter");
+ assert.equal(await ag.textContent(), "Codex, sillytavern, myapp");
+ assert.equal(await ag.getAttribute("class"), "rt-cond on");
+
+ // a known agent's name typed is that agent, once
+ await press(page, ag);
+ await q.waitFor();
+ await q.fill("Codex/0.50");
+ await page.waitForFunction(() => document.querySelectorAll("#list li .v").length > 0);
+ assert.deepEqual(await names(page), ["Codex"]);
+ // the ones picked come back ticked, the typed one among them
+ await q.fill("");
+ await page.waitForFunction(() => [...document.querySelectorAll("#list li .v")].some((v) => v.textContent === "myapp"));
+ assert.deepEqual((await names(page)).slice(1), ["Claude Code", "Codex", "sillytavern", "myapp"]);
+ await page.keyboard.press("Escape");
+
+ // saved as the gateway names them
+ const saveBtn = ed.locator("button.primary", { hasText: w.save });
+ 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.agents]), [["b/kimi", ["codex", "sillytavern", "myapp"]]]);
+ assert.deepEqual(errors, []);
+ });
+
+ test(`${engine} ${lang}: the agent picker 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 ag = page.locator('.rt-gedit .rt-rule .rt-c[data-k="agents"] > button.rt-cond').first();
+ await ag.waitFor();
+ await press(page, ag);
+ const q = page.locator("#q");
+ await q.waitFor();
+ await q.fill("SillyTavern-Desktop/1.0");
+ await page.locator("#list li", { hasText: "sillytavern-desktop" }).waitFor();
+ const pop = await page.locator("#pop").boundingBox();
+ assert(pop.x >= 0 && pop.x + pop.width <= 390 + 1, `the menu stays on the screen: ${JSON.stringify(pop)}`);
+ await q.press("Enter");
+ assert.equal(await ag.textContent(), "Codex, sillytavern-desktop");
+ const [b, row] = await Promise.all([ag.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 agents' 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, []);
+ });
+ }
+}