gui, gateway: auto mode's classifier and other side calls in a Claude Code session are no compaction on the Context tab (Player on Discord)
Player (magpie 0.1.1234 in docker, Claude Code in auto mode on glm-5.3)
saw "137 requests · 45 compactions" on Usage → Context for a session
that never compacted (peak ~116K of 1M). Claude Code's auto mode
classifier ("You are a security monitor…", a transcript, no tools,
34–48K) goes under the conversation's own session id, so every one
after a 60–115K turn passed compacted()'s 60% drop. Title, quota
check and a subagent's turns share the id too, and the latest one of
any of them became the session's "latest request".
contextOf now keeps a session's line to its own turns:
- in a session whose turns carry tool definitions, a request without
any is a side call (classifier, title, quota check) and is left out
of the session and the agent's stats, as a Kind'd call already was
(toolSessions, read from the routes on disk, so existing history
reads right too);
- a Claude Code subagent's request is left out of the session's line
(still in the agent's stats). The route now records it: Route.Sub,
from x-claude-code-agent-id (subagentOf), set in serve's beginFor.
An agent that sends no tools at all keeps every request.
Tests:
- TestContextSideCallsAreNoCompaction: an interleaved session like the
reporter's (title, quota check, 7 turns 60K→120K each followed by two
classifier calls 34–48K, two subagent turns, then a real compaction
120K→33K). On origin/main's context.go it fails "compactions: session
10 agent 10, want the one real one"; with only the subagent check
removed it fails with 2. Passes now: 1 compaction, 10 points, latest
is the last turn, peak 120K, baseline 24K.
- TestContextToollessAgentKeepsItsTurns: a no-tools chat app's 70K→20K
still counts.
- TestRouteSaysItsSubagent (gateway, through Handler with a fake
upstream): fails "map[:2]" without the gateway line, passes with it.
Run at this head (go1.26.8, darwin): gofmt -l clean; go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; go build,
GOOS=linux go build -tags nogui, GOOS=windows go build; go test -tags
nogui -count=1 ./... under a scratchpad HOME with caches pinned. With the
machine at load ~180-260 the first full run timed out (10m default) in
agent, gateway, library, plugin and provider with no test FAIL; those
five were rerun with -p 2 -timeout 45m and all passed. Everything else
passed in the full run. No GUI asset changed (context.js reads the same
JSON), so the Playwright suite wasn't run. Not tried against the
reporter's own usage.jsonl or a live Claude Code auto-mode session.
This commit is contained in:
@@ -27,7 +27,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |
|
||||
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) |
|
||||
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). | [`prompt.go`](../../internal/gateway/prompt.go) |
|
||||
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |
|
||||
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
|
||||
|
||||
## Codex titles, descriptions and predictions
|
||||
|
||||
@@ -2029,7 +2029,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
capture.tools = tools
|
||||
}
|
||||
tierAsked := bodyTier(from, body) // the service tier the client asked for (#1784)
|
||||
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, Affinity: shown, Order: pl.order, Left: pl.left})
|
||||
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, Sub: subOf(r.Header), Affinity: shown, Order: pl.order, Left: pl.left})
|
||||
if telemetry != nil {
|
||||
telemetry.routeID = tr.ID
|
||||
}
|
||||
@@ -5678,6 +5678,12 @@ func subagentOf(in http.Header) (agent, parent string) {
|
||||
return agent[:min(len(agent), 128)], parent[:min(len(parent), 128)]
|
||||
}
|
||||
|
||||
// subOf is the subagent a request is of, as subagentOf has it.
|
||||
func subOf(in http.Header) string {
|
||||
sub, _ := subagentOf(in)
|
||||
return sub
|
||||
}
|
||||
|
||||
// nativeSessionOf keeps the client session even when magpie's header overrides it.
|
||||
func nativeSessionOf(in http.Header) string {
|
||||
for _, h := range sessionHeaders {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A Claude Code subagent's request goes under its conversation's session
|
||||
// id; its route says whose it is (x-claude-code-agent-id), so the Context
|
||||
// page doesn't take its smaller prompt for the conversation compacting.
|
||||
// The conversation's own turns name none.
|
||||
func TestRouteSaysItsSubagent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, `data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"}}]}`+"\n\n")
|
||||
io.WriteString(w, `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\n")
|
||||
io.WriteString(w, "data: [DONE]\n\n")
|
||||
}))
|
||||
defer srv.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Chat: srv.URL + "/v1", Models: []string{"m1"}, Key: "k"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
body := `{"model":"plan/m1","stream":true,"max_tokens":100,"system":"You are Claude Code.","tools":[{"name":"Bash","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`
|
||||
for _, sub := range []string{"", "agent-a1b2c3"} {
|
||||
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
req.Header.Set("User-Agent", "claude-cli/2.1.295 (external, cli)")
|
||||
req.Header.Set("x-claude-code-session-id", "cc-1")
|
||||
if sub != "" {
|
||||
req.Header.Set("x-claude-code-agent-id", sub)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
got := map[string]int{}
|
||||
for _, r := range s.Trace(t.Context(), 0, 0).Routes {
|
||||
if r.Session != "cc-1" {
|
||||
t.Fatalf("route %d session %q", r.ID, r.Session)
|
||||
}
|
||||
got[r.Sub]++
|
||||
}
|
||||
if got[""] != 1 || got["agent-a1b2c3"] != 1 {
|
||||
t.Fatalf("routes by subagent %v, want one of the conversation's and one of agent-a1b2c3's", got)
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,9 @@ type Route struct {
|
||||
// Subagent is a Codex or Claude Desktop subagent's request put on
|
||||
// the model set for its subagents, or kept on the one asked for and why
|
||||
Subagent *SubagentPick `json:"subagent,omitempty"`
|
||||
// Sub: the Claude Code subagent the request is of (subagentOf), whose
|
||||
// session header is its conversation's; "" for the conversation's own
|
||||
Sub string `json:"sub,omitempty"`
|
||||
// Nested: the rules of the groups in the group, down the way to the
|
||||
// one that went first, each as it decided
|
||||
Nested []NestedRule `json:"nested,omitempty"`
|
||||
|
||||
+35
-2
@@ -165,6 +165,36 @@ func sessionOfRoute(r gateway.Route) string {
|
||||
// of a prompt of some size.
|
||||
func compacted(prev, next int) bool { return prev >= 20000 && next < prev*6/10 }
|
||||
|
||||
// ctxKey is the agent's session a route is in, "" when it names none.
|
||||
func ctxKey(r gateway.Route) string {
|
||||
if key := sessionOfRoute(r); key != "" {
|
||||
return r.Agent + "\x00" + key
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// withTools says a prompt carries tool definitions.
|
||||
func withTools(p *gateway.Prompt) bool { return partTokens(p, gateway.PartTools) > 0 }
|
||||
|
||||
// toolSessions are the sessions whose own turns carry tool definitions.
|
||||
// In one of them a request without any is a call the agent makes on the
|
||||
// side under the conversation's session id — Claude Code's auto mode
|
||||
// classifier ("You are a security monitor…", a transcript and no tools),
|
||||
// its title and its quota check — not a turn of the conversation, whose
|
||||
// prompt can't stand for it: a classifier's 40K after a 100K turn is no
|
||||
// compaction (Player on Discord: 45 in a session that never compacted).
|
||||
func toolSessions(routes []gateway.Route) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, r := range routes {
|
||||
if r.Kind == "" && r.Sub == "" && r.Prompt != nil && withTools(r.Prompt) {
|
||||
if sk := ctxKey(r); sk != "" {
|
||||
out[sk] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// contextOf works the agents and their sessions out of their routes.
|
||||
func contextOf(routes []gateway.Route, days int) ctxJSON {
|
||||
sort.SliceStable(routes, func(i, j int) bool { return routes[i].Time.Before(routes[j].Time) })
|
||||
@@ -181,6 +211,7 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
|
||||
}
|
||||
agents := map[string]*agentAcc{}
|
||||
sess := map[string]*ctxSession{}
|
||||
tooled := toolSessions(routes)
|
||||
var order []string
|
||||
for _, r := range routes {
|
||||
if !r.Done || r.Agent == "" {
|
||||
@@ -197,7 +228,7 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
|
||||
continue
|
||||
}
|
||||
p := r.Prompt
|
||||
if p == nil || p.Tokens <= 0 || r.Kind != "" {
|
||||
if p == nil || p.Tokens <= 0 || r.Kind != "" || !withTools(p) && tooled[ctxKey(r)] {
|
||||
// a title or another side call is neither the conversation's
|
||||
// nor what the agent's prompts are like
|
||||
continue
|
||||
@@ -223,7 +254,9 @@ func contextOf(routes []gateway.Route, days int) ctxJSON {
|
||||
}
|
||||
acc.a.Window = max(acc.a.Window, window)
|
||||
key := sessionOfRoute(r)
|
||||
if key == "" {
|
||||
if key == "" || r.Sub != "" {
|
||||
// a subagent's prompt is its own conversation's, not the
|
||||
// one whose session id it goes under
|
||||
continue
|
||||
}
|
||||
acc.sessions[key] = true
|
||||
|
||||
@@ -77,6 +77,91 @@ func TestContextOfALeanAgent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code's auto mode asks its classifier about each action under the
|
||||
// conversation's own session id: a security monitor's system prompt and
|
||||
// the transcript, no tools, 34–48K. Interleaved with turns of 60–116K, as
|
||||
// Player's glm-5.3 session on Discord was, those drops are no compaction,
|
||||
// nor are its title, quota check or a subagent's turns; the
|
||||
// conversation's line, latest request and peak are its own turns', and a
|
||||
// real compaction of them still counts.
|
||||
func TestContextSideCallsAreNoCompaction(t *testing.T) {
|
||||
const window = 1_000_000
|
||||
var routes []gateway.Route
|
||||
id := int64(0)
|
||||
turn := func(chat int) {
|
||||
id++
|
||||
routes = append(routes, ctxRoute(id, "claude", "cc-1", 24000, chat, window, 24000+chat*9/10))
|
||||
}
|
||||
// a request with no tool definitions, as the classifier, the title and
|
||||
// the quota check send
|
||||
side := func(system, chat int) {
|
||||
id++
|
||||
r := ctxRoute(id, "claude", "cc-1", 0, chat, window, 0)
|
||||
r.Prompt.Tokens = system + chat
|
||||
r.Prompt.Parts = []gateway.PromptPart{{Kind: gateway.PartSystem, Tokens: system}, {Kind: gateway.PartChat, Tokens: chat}}
|
||||
routes = append(routes, r)
|
||||
}
|
||||
side(60, 900) // the title, before the first turn has an answer
|
||||
side(0, 8) // the quota check
|
||||
chats := []int{36000, 48000, 60000, 72000, 80000, 86000, 92000}
|
||||
for i, chat := range chats {
|
||||
turn(chat)
|
||||
// the classifier on the turn's actions: its transcript grows as the
|
||||
// conversation does, well under its turns
|
||||
side(6000, 28000+i*2000)
|
||||
side(6000, 28000+i*2000+500)
|
||||
}
|
||||
// a subagent's turns, with tools of their own, under the same session
|
||||
for _, chat := range []int{4000, 9000} {
|
||||
id++
|
||||
r := ctxRoute(id, "claude", "cc-1", 18000, chat, window, 0)
|
||||
r.Sub = "agent-a1b2"
|
||||
routes = append(routes, r)
|
||||
}
|
||||
turn(chats[len(chats)-1] + 4000)
|
||||
side(6000, 42000)
|
||||
// a real compaction: the next turn starts over from the summary
|
||||
turn(9000)
|
||||
side(6000, 12000)
|
||||
turn(14000)
|
||||
last := id
|
||||
|
||||
out := contextOf(routes, 7)
|
||||
if len(out.Agents) != 1 || len(out.Sessions) != 1 {
|
||||
t.Fatalf("agents %d sessions %d", len(out.Agents), len(out.Sessions))
|
||||
}
|
||||
s, a := out.Sessions[0], out.Agents[0]
|
||||
if s.Compacts != 1 || a.Compacts != 1 {
|
||||
t.Fatalf("compactions: session %d agent %d, want the one real one", s.Compacts, a.Compacts)
|
||||
}
|
||||
if want := len(chats) + 3; s.Requests != want || len(s.Points) != want {
|
||||
t.Fatalf("session requests %d points %d, want its %d turns", s.Requests, len(s.Points), want)
|
||||
}
|
||||
if s.LatestID != last || s.Latest.Tokens != 24000+14000 {
|
||||
t.Fatalf("latest %d (%d tokens), want turn %d", s.LatestID, s.Latest.Tokens, last)
|
||||
}
|
||||
if s.Peak != 24000+96000 {
|
||||
t.Fatalf("peak %d", s.Peak)
|
||||
}
|
||||
if a.Baseline != 24000 {
|
||||
t.Fatalf("baseline %d: side calls are no part of what its turns start with", a.Baseline)
|
||||
}
|
||||
}
|
||||
|
||||
// An agent that sends no tools at all keeps every request on its line.
|
||||
func TestContextToollessAgentKeepsItsTurns(t *testing.T) {
|
||||
var routes []gateway.Route
|
||||
for i, chat := range []int{30000, 50000, 70000, 20000} {
|
||||
r := ctxRoute(int64(i+1), "chatbox", "c1", 0, chat, 128000, 0)
|
||||
r.Prompt.Parts = []gateway.PromptPart{{Kind: gateway.PartChat, Tokens: chat}}
|
||||
routes = append(routes, r)
|
||||
}
|
||||
s := contextOf(routes, 7).Sessions[0]
|
||||
if s.Requests != 4 || s.Compacts != 1 {
|
||||
t.Fatalf("requests %d compacts %d", s.Requests, s.Compacts)
|
||||
}
|
||||
}
|
||||
|
||||
// One that starts with most of a window of MCP tools, misses the cache,
|
||||
// compacts and fails often scores low and is told so.
|
||||
func TestContextOfAHeavyAgent(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user