gateway: a routing group's intent sureness is its own, intent-sure= (#5101)

Jev's sure of an intent had to reach jevSure, a fixed 0.4, for every
group. zminds measured 39 of 237 turns in one day (16.5%) refused at sure
0.153 to 0.395, and those turns went by the group's routing as if it had
no intent rules. A group can now set its own threshold: intentSure, from
0 (take Jev's likeliest intent however unsure) to 1. Missing keeps 0.4.

readJev keeps Jev's likeliest intent, its sure and Topic (an answer of
intents rather than levels). ruleFor applies the group's own sure through
intentOf, so two groups sharing one classifier and its cached answer each
judge it at their own. "none of these" is never an intent, at 0 too.
Levels and effort are as before.

Set from a terminal: magpie group set <group> intent-sure=0.25, empty to
unset. SaveGroup and the CLI refuse a value outside 0 to 1, NaN too: the
patch's `v < 0 || v > 1` let intent-sure=NaN through the CLI, which
SaveGroup then failed on as "json: unsupported value". cloneGroups copies
the new pointer, since TestCloneGroupsSharesNothing went red on it.

Changed from ggbdpq's patch on #5101:
- The group editor's "Intent sure" row is left out. Its hints were long
  secondary text, it showed for every classifier when only Jev answers
  with a sure, and it had no GUI test. The Routing page instead carries
  intentSure through each save it makes of a group (the editor's Save,
  the routing menu, the manual pick), so a value set from the CLI isn't
  wiped by the next GUI save.
- Its i18n strings and site/public/docs/intent.html are left out. A
  site/ change waits for the maintainer (docs/contributors.md). The site
  diff was documentation text only: a paragraph id="sure", a sentence
  in "Match the rules" and one table row. It had no links or scripts.
- docs/subsystems/gateway-routing.md has a bullet for IntentSure.

Run on mote (mote-run):
- gofmt -l internal/: clean.
- go vet -tags nogui, also with GOOS=linux and GOOS=windows, on
  internal/gateway, internal/cli and internal/provider: clean.
- go test -tags nogui -run 'TestGroupIntentSure|TestJev|Rule|Classif|Decide'
  ./internal/gateway: ok.
- -run 'Group|Apply' ./internal/cli: ok.
- -run 'Group|Save|Clone' ./internal/provider: ok.
- go test -run Budget ./internal/gui: ok.
- node --test group-intent-sure (new), routing-group-strategy and
  group-first-token, in Chromium and WebKit: 42 pass, 0 fail.
- i18n-keys has one red, "a plugin's words are its own". It fails the
  same on origin/main b712adb84 and is filed as #5327, #5332 and #5426.
  i18n-en-no-cjk: ok.

Broken by hand, each red, then restored:
- sureNeeded always returns 0.4: TestGroupIntentSureThreshold,
  ZeroTakesTheArgmax and IsPerGroup FAIL.
- The patch's `< 0 || > 1` checks put back: TestGroupIntentSurePairs
  FAILs on "NaN" and "nan"; TestGroupIntentSureRange FAILs on NaN.
- The cloneGroups copy removed: TestCloneGroupsSharesNothing FAILs.
- The editor's Save sending intentSure null: group-intent-sure FAILs 4/4
  ("the editor's Save keeps it").
- The routing menu's pick sending null: it FAILs 4/4 ("a routing pick
  keeps it").

Not tried: a real Jev account with a group at 0.25; the full suite.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
yetone
2026-11-06 10:44:24 +08:00
co-authored by ggbdpq
parent 429f9317d2
commit 7e5a54147f
12 changed files with 414 additions and 16 deletions
+1
View File
@@ -165,6 +165,7 @@ recorded as a prediction failure (`noPrediction`).
- Rules and image inputs are handled here too.
- A rule is decided as a user's turn begins and held for the rest of it (`ruleFor`, [`rules.go`](../../internal/gateway/rules.go)). What counts as the user's own words is one helper, `userWords`/`userSaid` in [`prompt.go`](../../internal/gateway/prompt.go), which the turn count (`turnIn`), the classifier's question (`userText`), the conversation's key (`firstWords`, in `ruleKey` and the affinity scope), the conversation's id where no session header names it (`userOpens`, in `conversationID`), Copilot's Auto (`lastUserText`) and the prompt breakdown's turns (`userSays`) all go by. It drops `<system-reminder …>` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's `<environment_context>`, `<user_instructions>`, `<turn_aborted>`, `<user_shell_command>`, `<subagent_notification>` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's `<task-notification>`, `<subagent-notification>`, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's `<plugin_reference>`; the Codex app's `<in-app-browser-context …>`; Reasonix's `<session-context …>`, its snapshot of the workspace (keeyangyy, #3938). The Codex app's context before `## My request (for Codex):` is dropped and what follows it kept (the `injected` list beside `agentsFor`). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (`within`), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words (`userText`: past 4000 runes, its first 3000 and last 1000). It is told what came before it too (`turnBefore`, @HirotaNagai on X: a short follow-up said alone, 继续 or fix that, came out the hardest kind): the user's message before it, the same way and cut to 1000 runes (`priorCap`: the first 750 and the last 250), and the assistant's last reply between the two, its text parts alone and their last 1000 runes. A tool call's arguments, a tool's result, thinking, a search's hits and the system prompt are never in either, and a reply of only tool calls is none. Jev gets them in its `state` as `previous_user_message` and `previous_assistant_reply` beside `message`, `previous_message_kind` and `previous_message_reasoning`, each only when there is one, and its intent, level and effort instructions name the ones there are (`jevState`, `priorAsk` in [`decide.go`](../../internal/gateway/decide.go)); a classifier asked in words gets them in `<previous_user_message>` and `<previous_assistant_reply>` before `<message>` (`writePrior`). Both come from the request the rules parsed, so Privacy masks them as it masks the message, and the answer kept for a message is kept for it with what came before (`classify`'s key). `TestTurnBeforeEachProtocol`, `TestTurnBeforeCuts`, `TestJevIsToldWhatCameBefore`, `TestChatClassifierIsToldWhatCameBefore`, `TestClassifyKeepsAnAnswerPerTurnBefore`, `TestJevSeesTheTurnBefore`. `firstWords` hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). `TestTurnInSkipsWhatTheAgentPutIn`, `TestUserTextSkipsWhatTheAgentPutIn`, `TestFirstWordsAreWhatTheUserSaid`, `TestIntentHoldsPastWhatTheAgentPutIn`.
- A rule's members go first (`ruleOver`, `applyRule`): the members it names, in order, then those the matching rules after it name (`ruleOrder`), each not resting, then the group's others to fail over to. A member that is a group in the group is one member here: its models keep the order the group's own routing planned them, where ranking each by the group's listed order pinned a rotate group's first member on every request the rule put it first (#2407, `TestRuleNamingARotateGroupKeepsItsTurns`). That holds within the turn too, at the group's rule and at each nested group's (`nestedRules`): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (`Affinity.Why` `rule`). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. `TestHeldRuleFailsOverWithinItsMember`. Two groups in the group may share a model (the same provider, model and effort): it is asked once a request, where the walk met it first, and `provider.Member.Also` keeps its later places, each with its own path, `At` (its place in the walk) and Fast. A rule naming the later group has the model as that group does (`Member.In`, `membersNamed`), in that group's own order, and the nested rules below it, Fast and the first token's wait go by that group's way down (`homed`, `homeCands`). Before #2361 (davisjiahao) such a rule found none of the shared models, read unready, and the group ahead of it answered. A pause rule naming the later group still leaves a shared model to the group ahead of it. `rule_shared_test.go`.
- How sure a decision model (Jev) must be of an intent for it to count is the group's own (`provider.Group.IntentSure`, JSON `intentSure`, 0 to 1; missing keeps `jevSure`, 0.4; `magpie group set <group> intent-sure=0.25`, empty to unset; SaveGroup and the CLI refuse a value outside 0 to 1, NaN too; `cloneGroups` copies it). `readJev` keeps Jev's likeliest intent with its sure and marks a topic answer (`verdict.Topic`); `ruleFor` applies the group's sure (`intentOf`), so two groups sharing one classifier and its cached answer each judge it at their own. "none of these" is never an intent, at 0 too, and levels keep the turn before's level when torn, as before. A chat model asked in words answers with no sure and is taken as it answers. The Routing page carries the value through every save of a group but has no field for it yet (#5101). `TestGroupIntentSure*`.
- A classifier's timeout is global (`Settings.ClassifyTimeout`, JSON `classifyTimeout`, seconds, in [`settings.go`](../../internal/settings/settings.go)). Missing or 0 keeps the 8-second default; saving accepts 1–60 seconds or 0 and rejects negative values or values above 60. `Settings.ClassifyWait` bounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1. `classifyTimeout()` reads it for each call: both `askChat` in [`classify.go`](../../internal/gateway/classify.go) and `askJev` in [`decide.go`](../../internal/gateway/decide.go) give the classifier that time, including its provider's failover. A request shares one such wait across every routing group it goes through (`Server.askWaited`, from the first classifier asked): a nested ruled group asked with less left gets only that, one asked once it is spent goes by its order at once (`waitSpent`, "spent by the routing group above"), and a classifier or decision key cut short that way is not rested (`cutShort`). Each nested level had a whole wait of its own before, so three ruled levels whose classifiers didn't answer held a request past the unrouted watch's 2 minutes, a 504 (heatonz on Discord, v0.1.2215; `TestNestedGroupsShareTheClassifierWait`, `TestDecisionKeyCutShortIsNotRested`). Settings → Models → Replies → *Intent classifier timeout* (`renderReplies` in [`app.js`](../../internal/gui/assets/app.js)) offers 8, 15, 30 and 60 seconds and shows a custom valid value as its own choice. A change applies to the next classifier call, with no restart; the existing fallback, 30-second cooldown (`classifyRest`) and 10-minute answer cache (`classifyKeep`) still apply.
- A classifier that can't say which kind a turn is (an error, no answer within `classifyTimeout()`, an answer that isn't a number, or resting `classifyRest` after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (`Classified.Fallback` is `previous`, its `Error` kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (`classWhy`). The turn's decision itself (`turnRules`) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. `TestIntentClassifierFailsKeepsThePreviousIntent`, `routing-intent-fallback.test.cjs`.
- A group's classifier is asked only for that group's own turns: a request whose model is the group (`group/<id>`, its bare name, or a stand-in an agent's config names it by: Claude Code's tiers, Codex's bare name), or a group in it that its rules or order put first (`nestedRules`). A request for another model or group asks it nothing. The Routing page's card says why the classifier couldn't say the last time *that group* asked it (`GroupClassifierFailure`, kept by `classifiedFor` in `ruleFor`): the classifier's own words and time, resting or not, until it answers that group, and nothing once the group's classifier changed. Keyed by the classifier model alone, a group nothing reached showed another group's failure on a classifier they share (jjt on Discord). A classifier on a subscription out of its quota is not asked of the vendor again until the reset: out of quota, its account rests until the quota comes back (`restAfter`: the time the refusal names, else when the account's window renews), and the classifier's call meanwhile gets that refusal back from magpie, at most once each `classifyRest`. `TestClassifierFailureIsTheGroupsOwn`.
+22 -1
View File
@@ -34,6 +34,9 @@ const groupUsage = `usage:
it is in follow; an agent set to the old id needs setting again),
effort=auto (the classifier picks each turn's reasoning; needs classifier=),
effort=agent (the agent's again), classifier=<provider/model>|group/<id>,
intent-sure=<0…1> (how sure the classifier must be of an intent for it
to count; 0 takes its likeliest however unsure, "none of these" never
counting; empty is the 0.4 groups have always asked),
pick=<model> (routing=manual, every request to that one of its models),
fast=<m1>[,m2…] (the models sent in their vendor's fast mode; empty for none),
weight=<m1>=<n>[,m2=<n>…] (each model's share under routing=weight,
@@ -524,6 +527,21 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st
}
case "classifier", "classify":
g.Classifier = strings.TrimPrefix(strings.TrimSpace(v), "magpie/")
case "intent-sure", "intentsure":
// how sure the classifier must be of an intent for it to count
// (#5101): 0 takes its likeliest however unsure, "none of
// these" never counting; empty is 0.4 as groups have always
// asked
if strings.TrimSpace(v) == "" {
g.IntentSure = nil
break
}
sure, perr := strconv.ParseFloat(strings.TrimSpace(v), 64)
if perr != nil || !(sure >= 0 && sure <= 1) { // NaN too
err = fmt.Errorf("intent-sure is from 0 to 1, as intent-sure=0.25 (empty is the 0.4 groups have always asked), not %q", v)
break
}
g.IntentSure = &sure
case "fast":
// the members sent in their vendor's fast mode, as they are in
// the group
@@ -567,7 +585,7 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st
g.Pick, err = pickMember(g.Members, v)
g.Routing = provider.Manual
default:
return fmt.Errorf("unknown field %q (fields: name, models, models+, models-, routing, pick, stays, context, levels, family, effort, classifier, fast, weight, listed; magpie group help)", k)
return fmt.Errorf("unknown field %q (fields: name, models, models+, models-, routing, pick, stays, context, levels, family, effort, classifier, intent-sure, fast, weight, listed; magpie group help)", k)
}
if err != nil {
return err
@@ -1231,6 +1249,9 @@ func showGroup(g provider.Group) error {
}
kv("classifier", g.Classifier+muted.Render(what))
}
if g.IntentSure != nil {
kv("intent-sure", fmt.Sprintf("%g", *g.IntentSure)+muted.Render(" how sure the classifier must be of an intent for it to count; 0 takes its likeliest"))
}
if u := groupUses()[g.ID]; len(u) > 0 {
kv("used by", green.Render(strings.Join(u, ", ")))
}
@@ -0,0 +1,36 @@
package cli
import (
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// intent-sure= sets how sure the classifier must be of a group's intent
// (#5101): from 0 to 1, empty back to the 0.4 every group asked before, and
// anything else, NaN among it, refused with the group unchanged.
func TestGroupIntentSurePairs(t *testing.T) {
none := func(string) (string, error) { return "", nil }
g := provider.Group{}
for _, c := range []struct {
v string
want float64
}{{"0.25", 0.25}, {"0", 0}, {"1", 1}, {" 0.6 ", 0.6}} {
if err := applyGroupPairs(&g, []string{"intent-sure=" + c.v}, none, false); err != nil || g.IntentSure == nil || *g.IntentSure != c.want {
t.Fatalf("intent-sure=%q: %v %v, want %g", c.v, err, g.IntentSure, c.want)
}
}
for _, v := range []string{"-0.1", "1.5", "NaN", "nan", "high"} {
err := applyGroupPairs(&g, []string{"intent-sure=" + v}, none, false)
if err == nil || !strings.Contains(err.Error(), "from 0 to 1") {
t.Errorf("intent-sure=%q: %v, want refused", v, err)
}
if g.IntentSure == nil || *g.IntentSure != 0.6 {
t.Errorf("intent-sure=%q changed the group: %v", v, g.IntentSure)
}
}
if err := applyGroupPairs(&g, []string{"intentsure="}, none, false); err != nil || g.IntentSure != nil {
t.Fatalf("empty: %v %v, want nil", err, g.IntentSure)
}
}
+7 -1
View File
@@ -73,7 +73,13 @@ type verdict struct {
// choice a decision model named — kept even when no intent came of
// it, so the trace tells "said none" from an answer the rules
// couldn't take (#4598)
Said string
Said string
// Topic: the answer is of topics a message may be none of (a decision
// model's intent answer), not levels every message is at. Jev's
// likeliest intent is kept in Intent as it said it, and the group's
// own sure of it applied where it is known (intentOf): a chat model's
// answer is already the one of it that counts.
Topic bool
Effort string // the reasoning the turn wants; "" when not asked
Score float64 // how hard the classifier took the turn to be, from 0 (low) to 3 (xhigh)
Sure float64 // how confident Jev was of the intent, from 0 to 1
+38 -6
View File
@@ -29,10 +29,11 @@ import (
"github.com/yetone/magpie/internal/usage"
)
// jevSure is how confident Jev must be of an intent for it to count.
// Confidence runs from 0, every option as likely, to 1, one certain, as
// System One gives it (provider.Confidence), read from the answer's
// probabilities wherever it has them (sureOf).
// jevSure is how confident Jev must be of an intent for it to count, a
// group setting its own (provider.Group.IntentSure). Confidence runs from
// 0, every option as likely, to 1, one certain, as System One gives it
// (provider.Confidence), read from the answer's probabilities wherever it
// has them (sureOf).
const jevSure = 0.4
// sureOf is how sure an answer is of its choice on jevSure's scale: from
@@ -234,7 +235,13 @@ func effortAsk(prev before) string {
}
// readJev is the verdict in a System One reply to jevBody, the answer
// without "none of these" counting when the intents are levels.
// without "none of these" counting when the intents are levels. The sure
// an intent needs is the group's own (rulesOf applies it): Jev's likeliest
// intent is kept as it said it (Said), and the intents' own answer as Said
// with Topic marking it a topic — a message may be none of those — rather
// than a level every message is at, whose torn pick holds (the level half
// below). Whether an intent came of it is decided where the group's own
// sure is known, so the answer still tells why it went as it did.
func readJev(b []byte, intents []string, levels bool, prev before) (verdict, error) {
var out struct {
Model string `json:"model"`
@@ -256,7 +263,8 @@ func readJev(b []byte, intents []string, levels bool, prev before) (verdict, err
if a, ok := out.Answers["intent"]; ok && len(intents) > 0 && !levels {
v.Sure = sureOf(a.Confidence, a.Probabilities)
v.Said = a.Choice // as it said it, no intent come of it or not (#4598)
if a.Choice != noIntent && v.Sure >= jevSure {
v.Topic = true
if a.Choice != noIntent {
v.Intent = intentNamed(intents, a.Choice)
}
}
@@ -280,6 +288,30 @@ func readJev(b []byte, intents []string, levels bool, prev before) (verdict, err
return v, nil
}
// sureNeeded is how sure a group asks its classifier to be of an intent:
// the group's own (IntentSure), or 0.4 as groups have always asked.
func sureNeeded(g provider.Group) float64 {
if g.IntentSure != nil {
return *g.IntentSure
}
return jevSure
}
// intentOf v is the intent of v's answer at the group's own sure
// (sureNeeded): a topic answer counts once Jev is sure enough of it —
// "none of these", said or picked, never being an intent — while a level
// is the level it said, every message being at one. A topic answer unsure
// at the group's sure is no intent.
func intentOf(v verdict, g provider.Group) string {
if !v.Topic {
return v.Intent
}
if v.Sure < sureNeeded(g) || v.Said == noIntent || v.Intent == "" {
return ""
}
return v.Intent
}
// intentNamed is the one of intents named, or "".
func intentNamed(intents []string, name string) string {
for _, in := range intents {
+145
View File
@@ -0,0 +1,145 @@
package gateway
import (
"fmt"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// #5101: the confidence an intent needs of Jev was fixed at 0.4 for every
// group. A group may set its own (IntentSure): lower it and Jev's unsure
// picks count, raise it and fewer do, set it to 0 and every pick but
// "none of these" counts.
// chatFor is chat for the group named, not group/r.
func chatFor(group, first string, extra string) string {
if extra != "" {
extra = "," + extra
}
return fmt.Sprintf(`{"model":%s%s,"messages":[{"role":"user","content":%s}]}`, quote(group), extra, quote(first))
}
// ptrSure is the group's IntentSure as a test names it.
func ptrSure(sure float64) *float64 { return &sure }
// sure 0.3 misses a group's intent rule at the default 0.4, hits it with
// IntentSure 0.25, and counts again at 0.4 once the field is gone.
func TestGroupIntentSureThreshold(t *testing.T) {
s, _, _, j := jevved(t, "", provider.Rule{Use: "b/big", Intent: "debugging"})
j.choice, j.sure = "debugging", 0.3
_, r := postOK(t, s, "d0", chat("why does this crash?", nil, 0, ""))
if r.Rule.N != 0 || r.Rule.Classified.Intent != "" || r.Rule.Classified.Sure != 0.3 {
t.Fatalf("default 0.4: %+v", r.Rule.Classified)
}
// a torn pick stays none at 0.4 but matches at 0.25
g, _, _ := provider.FindGroup("group/r")
sure := 0.25
g.IntentSure = &sure
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
_, r = postOK(t, s, "d1", chat("why does this crash, again?", nil, 0, ""))
if r.Rule.N != 1 || r.Rule.Classified.Intent != "debugging" || r.Rule.Classified.Sure != 0.3 {
t.Fatalf("0.25: %+v", r.Rule.Classified)
}
// the trace keeps the sure and the said with it, whichever way the
// threshold went
if r.Rule.Classified.Said != "debugging" {
t.Fatalf("said: %+v", r.Rule.Classified)
}
// unset: 0.4 again
g.IntentSure = nil
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
_, r = postOK(t, s, "d2", chat("why does this crash, still?", nil, 0, ""))
if r.Rule.N != 0 || r.Rule.Classified.Intent != "" {
t.Fatalf("unset: %+v", r.Rule.Classified)
}
}
// IntentSure 0 takes Jev's pick whatever its sure, "none of these" still
// not an intent; the effort is picked as ever.
func TestGroupIntentSureZeroTakesTheArgmax(t *testing.T) {
s, _, _, j := jevved(t, provider.EffortAuto, provider.Rule{Use: "b/big", Intent: "debugging"})
j.choice, j.sure = "debugging", 0.01
g, _, _ := provider.FindGroup("group/r")
zero := 0.0
g.IntentSure = &zero
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
out, r := postOK(t, s, "z1", chat("why does this crash?", nil, 0, `,"reasoning_effort":"low"`))
if !strings.Contains(out, "from kb") || r.Rule.N != 1 || r.Rule.Classified.Intent != "debugging" || r.Rule.Classified.Sure != 0.01 {
t.Fatalf("zero: %s %+v", out, r.Rule.Classified)
}
// none of these is no intent, not even at 0
j.choice = noIntent
_, r = postOK(t, s, "z2", chat("what now?", nil, 0, `,"reasoning_effort":"low"`))
if r.Rule.N != 0 || r.Rule.Classified.Intent != "" || r.Rule.Classified.Said != noIntent {
t.Fatalf("none of these at 0: %+v", r.Rule.Classified)
}
if r.Rule.Classified.Effort == "" {
t.Fatalf("effort not asked: %+v", r.Rule.Classified)
}
}
// A group's IntentSure is of the group's own: another group classifying
// with the same classifier keeps the default 0.4.
func TestGroupIntentSureIsPerGroup(t *testing.T) {
s, _, _, j := jevved(t, "", provider.Rule{Use: "b/big", Intent: "debugging"})
j.choice, j.sure = "debugging", 0.3
g, _, _ := provider.FindGroup("group/r")
sure := 0.25
g.IntentSure = &sure
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
other := provider.Group{ID: "other", Name: "Other", Members: []string{"a/small", "b/big"}, Routing: provider.Rotate, Classifier: "ts/jev-latest",
Rules: []provider.Rule{{Use: "a/small", Intent: "debugging"}}}
if err := provider.SaveGroup(other); err != nil {
t.Fatal(err)
}
out, r := postOK(t, s, "p1", chatFor("group/other", "why does this crash?", ""))
if !strings.Contains(out, "from ka") || r.Rule.N != 0 || r.Rule.Classified.Intent != "" {
t.Fatalf("other group at 0.4: %s %+v", out, r.Rule.Classified)
}
out, r = postOK(t, s, "p2", chat("why does this crash, again?", nil, 0, ""))
if !strings.Contains(out, "from kb") || r.Rule.N != 1 || r.Rule.Classified.Intent != "debugging" {
t.Fatalf("ruled group at 0.25: %s %+v", out, r.Rule.Classified)
}
}
// The group's IntentSure out of range is refused, 0 through 1 kept.
func TestGroupIntentSureRange(t *testing.T) {
for _, x := range []float64{-0.1, 1.1} {
g := provider.Group{ID: "bad", Name: "Bad", Members: []string{"a/small", "b/big"}, Classifier: "c/cls",
Rules: []provider.Rule{{Use: "a/small", Intent: "debugging"}}}
sure := x
g.IntentSure = &sure
if err := provider.SaveGroup(g); err == nil {
t.Fatalf("%v saved", x)
}
}
}
// Levels are another scale (every message at one of them): the torn keep
// the turn before's level, IntentSure or no IntentSure (#5101 leaves them
// as they are).
func TestGroupIntentSureLeavesLevels(t *testing.T) {
s, _, _, j := jevved(t, provider.EffortAuto, provider.Rule{Use: "a/small", Intent: "简单任务"}, provider.Rule{Use: "b/big", Intent: "复杂任务"})
j.levels, j.sure = 0.9, 0.09
g, _, _ := provider.FindGroup("group/r")
sure := 0.0
g.IntentSure = &sure
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
// torn over the level, the turn before's is kept, as ever
_, r := postOK(t, s, "l1", chat("写个纸牌游戏", nil, 0, ""))
if r.Rule.N != 0 || r.Rule.Classified.Intent != "" || r.Rule.Classified.Sure != 0.09 {
t.Fatalf("torn level, none before: %+v", r.Rule.Classified)
}
}
+18 -4
View File
@@ -606,14 +606,28 @@ func TestJevTornLevel(t *testing.T) {
if v, _ := readJev(sure, in, true, before{Intent: "复杂任务"}); v.Intent != "简单任务" {
t.Fatalf("sure: %+v", v)
}
// topics still need Jev sure, and may be none
if v, _ := readJev(b, in, false, before{Intent: "复杂任务"}); v.Intent != "复杂任务" {
t.Fatalf("topic sure enough: %+v", v)
// topics: the sure needed is the group's own now (#5101), readJev
// keeping Jev's pick and saying how sure it was — intentOf applies the
// group's own at the group
if v, _ := readJev(b, in, false, before{Intent: "复杂任务"}); v.Intent != "复杂任务" || v.Sure != 0.43 || !v.Topic {
t.Fatalf("topic: %+v", v)
}
unsure := []byte(`{"answers":{"intent":{"type":"choice","choice":"复杂任务","confidence":0.2}}}`)
if v, _ := readJev(unsure, in, false, before{Intent: "复杂任务"}); v.Intent != "" {
if v, _ := readJev(unsure, in, false, before{Intent: "复杂任务"}); v.Intent != "复杂任务" || v.Sure != 0.2 {
t.Fatalf("topic unsure: %+v", v)
}
// a group's own sure: the default 0.4 keeps an unsure pick from
// matching, 0.25 lets a surer one, "none of these" never counts
g0 := provider.Group{}
if got := intentOf(verdict{Topic: true, Intent: "复杂任务", Said: "复杂任务", Sure: 0.2}, g0); got != "" {
t.Fatalf("default 0.4: %+v", got)
}
if got := intentOf(verdict{Topic: true, Intent: "复杂任务", Said: "复杂任务", Sure: 0.3}, provider.Group{IntentSure: ptrSure(0.25)}); got != "复杂任务" {
t.Fatalf("0.25: %+v", got)
}
if got := intentOf(verdict{Topic: true, Intent: "", Said: noIntent, Sure: 0.9}, provider.Group{IntentSure: ptrSure(0)}); got != "" {
t.Fatalf("none of these at 0: %+v", got)
}
}
// jevAt is ruled's group with the Jev a decision API at decide serves as
+1
View File
@@ -337,6 +337,7 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a
t0 := time.Now()
v, cached, err := classify(ask, g.Classifier, intents, prev, effort, text)
classifiedFor(g.ID, g.Classifier, err)
v.Intent = intentOf(v, g) // the group's own sure of an intent (#5101)
c.Intent, c.Said, c.Cached, c.Ms = v.Intent, v.Said, cached, int(time.Since(t0).Milliseconds())
if effort {
c.Effort, c.Score = v.Effort, v.Score
@@ -5711,7 +5711,7 @@ function routingPage(part) {
// 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 || [])], weights: { ...(g.weights || {}) }, accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, 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, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], 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 || [])], weights: { ...(g.weights || {}) }, accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
renderGroups();
return true;
};
@@ -6456,7 +6456,7 @@ function routingPage(part) {
closeProtoMenu();
if (v === cur || (groupDirty() && !(await confirmDiscard()))) return b.focus({ preventScroll: true });
const n = opts.find(([id]) => id === v)?.[1] || v;
await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists },
await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists },
t("{name}: {routing}", { name: g.name, routing: t(n) }));
// the rows were drawn anew: the keyboard stays on this one's routing
gList.querySelector(`.rt-group[data-id="${CSS.escape(g.id)}"] .rt-groute`)?.focus({ preventScroll: true });
@@ -6589,7 +6589,7 @@ function routingPage(part) {
b.onclick = (e) => {
e.stopPropagation(); // the card opens the editor; this picks
if (on) return;
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists },
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists },
t("{name}: every request to {model}", { name: g.name, model: memberName(id) }));
};
box.append(b);
@@ -7894,7 +7894,7 @@ function routingPage(part) {
if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn");
saveBtn.classList.add("busy");
// refused, Add can be pressed again (busy, it takes no clicks)
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
.then(() => saveBtn.classList.remove("busy"));
};
// what goes wrong is said where it is seen, never a click that does nothing
@@ -0,0 +1,95 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A group may ask Jev to be surer, or less sure, of an intent than 0.4
// before a rule follows it (#5101): `magpie group set <id> intent-sure=0.25`.
// The Routing page has no field for it yet, so every save it makes of the
// group carries the value back as it was: the editor's Save and a pick in
// the card's routing menu. A group without one saves none. In English and
// Chinese, Chromium and WebKit.
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: "oa/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "OpenAI", icon: "generic" },
{ id: "rl/glm-5", name: "glm-5", providerName: "Relay", icon: "generic" },
];
const members = ["oa/gpt-6.1-sol", "rl/glm-5"];
const group = (id, name, extra) => ({ id, name, members, routing: "order", ready: true, classifier: "jev",
rules: [{ intent: "code", to: "oa/gpt-6.1-sol" }], memberInfo: members.map((m) => ({ id: m, ready: true })), ...extra });
const groups = () => ({ models, pools: [], groups: [group("sure", "Sure", { intentSure: 0.25 }), group("plain", "Plain", {})] });
const words = { en: { edit: "Edit", save: "Save" }, zh: { edit: "编辑", save: "保存" } };
function serve(lang, posts) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], 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/plugins") return json({ plugins: [] });
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: 1, totals: { requests: 0, 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 });
};
}
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}: the Routing page keeps a group's intent sureness`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width: 1100, height: 2000 }, reducedMotion: "reduce" })).newPage();
t.after(() => browser.close());
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
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 last = () => posts.filter((p) => p.path === "/api/groups/save").at(-1)?.body;
const save = async (id) => {
const card = page.locator(`.rt-group[data-id="${id}"]`);
await card.locator("button", { hasText: w.edit }).click();
const ed = page.locator(".rt-gedit");
await ed.locator("button.primary", { hasText: w.save }).click();
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
return last();
};
const pick = async (id) => {
const n = posts.length;
await page.locator(`.rt-group[data-id="${id}"] button.rt-groute`).click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
await menu.locator('.pm-item[aria-checked="false"]').first().click();
for (let i = 0; i < 100 && posts.length === n; i++) await page.waitForTimeout(20); // the post is the state waited for
return last();
};
await page.locator('.rt-group[data-id="sure"]').waitFor();
assert.equal((await save("sure")).intentSure, 0.25, "the editor's Save keeps it");
assert.equal((await save("plain")).intentSure ?? null, null, "a group without one saves none");
const picked = await pick("sure");
assert.notEqual(picked.routing, "order", "the menu's pick was saved");
assert.equal(picked.intentSure, 0.25, "a routing pick keeps it");
assert.deepEqual(errors, []);
});
}
}
+13
View File
@@ -223,6 +223,12 @@ type Group struct {
// Rules with an intent need one; a small, fast model without reasoning
// does.
Classifier string `json:"classifier,omitempty"`
// IntentSure is how confident a decision model (Jev, from TypeSafe's
// decision API) must be of an intent of this group's for it to count:
// from 0, its likeliest intent taken however unsure it is ("none of
// these" never counting), to 1, certain. nil asks 0.4, as groups have
// always asked (#5101).
IntentSure *float64 `json:"intentSure,omitempty"`
// Effort "auto" has the classifier — Jev, from TypeSafe's decision API,
// or any model, asked in words — judge how hard each turn is to think
// about as it begins, and the turn asks its model for that much
@@ -435,6 +441,10 @@ func cloneGroups(gs []Group) []Group {
g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast)
g.Accounts, g.Seen = slices.Clone(g.Accounts), slices.Clone(g.Seen)
g.Weights = maps.Clone(g.Weights)
if g.IntentSure != nil {
v := *g.IntentSure
g.IntentSure = &v
}
if g.Rules != nil {
rs := make([]Rule, len(g.Rules))
for j, r := range g.Rules {
@@ -1627,6 +1637,9 @@ func SaveGroup(g Group) error {
return fmt.Errorf("magpie knows no model %q to classify with", g.Classifier)
}
}
if g.IntentSure != nil && !(*g.IntentSure >= 0 && *g.IntentSure <= 1) { // NaN too
return fmt.Errorf("a group's intent sure is from 0 to 1, not %g", *g.IntentSure)
}
g.Auto, g.Hidden = false, false
g.Members = own // what the patterns match is found again as it is read
// a found group changed keeps following its model: what magpie had
@@ -0,0 +1,34 @@
package provider
import (
"math"
"path/filepath"
"strings"
"testing"
)
// A group's intentSure (#5101) is kept from 0 to 1 and nil, and refused
// outside that, NaN among it, with nothing saved.
func TestGroupIntentSureRange(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
f := func(v float64) *float64 { return &v }
for _, v := range []*float64{nil, f(0), f(0.25), f(1)} {
if err := SaveGroup(Group{ID: "g", Name: "g", Members: []string{"a/m1", "b/m2"}, IntentSure: v}); err != nil {
t.Fatalf("%v: %v", v, err)
}
}
for _, v := range []float64{-0.01, 1.01, math.NaN(), math.Inf(1)} {
err := SaveGroup(Group{ID: "g", Name: "g", Members: []string{"a/m1", "b/m2"}, IntentSure: f(v)})
if err == nil || !strings.Contains(err.Error(), "from 0 to 1") {
t.Errorf("%g: %v, want refused", v, err)
}
}
for _, g := range Groups() {
if g.ID == "g" && (g.IntentSure == nil || *g.IntentSure != 1) {
t.Errorf("saved %v, want the last good 1", g.IntentSure)
}
}
}