audie on Discord: on 10-21 Codex Desktop, routed to WorkBuddy's deepseek-v4-pro, ran the same read-code tool call 308 times between 13:24 and 13:52 (316 requests, 212.65 credits). That evening it did it 340 more times between 19:58 and 20:22 (343 requests, 324.52 credits). loopGuard only catches a loop inside one streamed reply. Here every reply was a short, valid call. The loop runs across turns, so it shows in the request's own history. stoppedToolLoop (internal/gateway/tool_loop.go) runs in serveAgent after the session is recorded and before hooks, middleware and routing. It also runs in the Codex backend's passthrough on Codex's own ChatGPT sign-in. It needs the last 8 turns to be the same exchange: - the same calls: name plus arguments, key order ignored, call ids ignored; - answered with the same results: text, error flag and images, with Codex's "Wall time", "Chunk ID" and "duration_seconds" taken out (runNoise); - with nothing else said on the user's side. When it finds one, it answers the turn in the agent's own protocol, streamed or whole (Responses, Chat, Anthropic, Gemini through relayStatus), with a notice that names the call. Nothing goes upstream, and no prompt, base_instructions or identity text sent to a vendor changes. A different result, or any word from the user, starts the count again. The notice is a turn without calls, so the user's next message carries on. The check keeps no state, so it is per conversation, and a retried request doesn't count twice. The turn is recorded the way Codex's title turns are. sentNowhere's body becomes answeredHere (from-protocol aware): the Routing trace shows "Tool loop stopped", and a usage row has provider magpie, rejected, the conversation's session and native session, and an error starting "tool loop:". So Usage and Sessions both show why. Cost: a body with fewer than 8 tool results isn't parsed (a bytes.Count). For a longer one, only the newest 64 items are parsed, found with gjson (tailOf). For a 1.5MB Codex turn that is 1.1ms and 2.5MB, against 30ms and 20MB for a full parse (BenchmarkToolLoopCheck). There is no new setting. Settings › Models › Replies › Stop looping replies (noLoopGuard, on by default) turns this off together with the reply guard, and the notice says so. The GUI sub-text is unchanged. docs/subsystems/gateway-routing.md has a bullet on it. Run at this commit (vet/build/race at parent bf2e067ef; the full suite after the rebase onto50f52b540, at 558b21b7e): - gofmt -l clean. - go vet ./... on darwin, GOOS=linux go vet -tags nogui ./..., and GOOS=windows go vet ./.... - go build on darwin, linux (-tags nogui) and windows. - TestToolLoop* and the Codex title/description/prediction tests under -race (TestToolLoop* -count=3). - The tests, in a sandbox HOME against fake vendors: - TestToolLoopIsStoppedOnEveryProtocol: 60 poll turns then 8 Codex reads with a varying chunk id and wall time, on Responses (stream and whole), Codex's backend path, Chat (stream and whole), Anthropic (stream and whole) and Gemini. The vendor is asked 0 times, the notice and the protocol's done marker reach the agent, and the usage row is magpie, rejected, "tool loop", with the session. - TestToolLoopStoppedOnCodexsOwnSignIn: gpt-5.5 on the passthrough, with a fake CodexBase. - TestToolLoopShortOrOffGoesOn: 7 turns, and 40 with the setting off. - TestToolLoopLetsProgressBy: 200 polls whose answer moves, and a loop followed by the notice and a word from the user. Neither is stopped. - TestToolLoopSums. - Broken by hand, each red, each restored: - The guard skipped: every protocol subtest and the Codex sign-in test fail ("the agent wasn't told of the loop"). - runNoise removed: the same tests fail, plus TestToolLoopSums. - Results left out of the sum: every progress subtest fails ("a poll whose answer moves was stopped"). - Full suite: set -o pipefail; go test -tags nogui -timeout 45m ./... through suite-lock, in a sandbox HOME, at 558b21b7e on50f52b540: exit 0, 69 packages ok, no FAIL (internal/gateway 854s, internal/agent 812s, internal/provider 393s, internal/gui 291s). - No GUI file changed, so the GUI suite wasn't run. Not tried: - A real Codex Desktop or WorkBuddy loop, or any real account. The fixture's shape is Codex's exec_command output; audie's literal bytes weren't available. - The Windows box. - Codex over websocket (magpie answers it 426). - Responses conversations that use previous_response_id. They carry only the newest turn, so they are never stopped. - Loops with more parallel calls a turn than fit in 64 items. - A poll that gets the same answer 8 times in a row is stopped too. The user's next word, or the setting, carries on. - dsh's two ~1M-token requests to DeepSeek on 10-23 are a different problem, not addressed here.
136 lines
4.6 KiB
Go
136 lines
4.6 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"slices"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/gwmw"
|
|
"github.com/yetone/magpie/internal/middleware"
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// serveAgent is serve for a request an agent sent: the agent middleware
|
|
// of the gateway's middleware point (gwmw.Agents: the JS gateway middleware
|
|
// plugins, internal/middleware, while plugins/middleware is on) see its
|
|
// body first, and its reply on the way back, in the agent's own API.
|
|
// magpie's own requests through serve (titles, the router's classifier,
|
|
// search and vision stand-ins) go without them, as their replies are
|
|
// magpie's to read.
|
|
func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) {
|
|
withGatewaySession(w, r)
|
|
w, recorded := recordConversation(w, r, from, body)
|
|
defer recorded()
|
|
// a conversation going round one tool call is answered here, before
|
|
// anything of it is asked of a hook, a middleware or a provider
|
|
if s.stoppedToolLoop(w, r, from, body) {
|
|
return
|
|
}
|
|
w, body, hooked := gatewayHooks(w, r, from, body)
|
|
defer hooked()
|
|
agents := gwmw.AgentsWanted(middlewareWanted)
|
|
if len(agents) == 0 {
|
|
s.serve(w, r, from, body)
|
|
return
|
|
}
|
|
info := gwmw.Info{Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r)}
|
|
var tried []gwmw.Tried
|
|
for _, a := range agents {
|
|
run := a.Begin(info)
|
|
if run == nil {
|
|
continue
|
|
}
|
|
defer run.End()
|
|
if t, ok := run.(gwmw.Tried); ok {
|
|
tried = append(tried, t)
|
|
}
|
|
var turned *gwmw.Reject
|
|
body, turned = run.Request(body)
|
|
if turned != nil {
|
|
writeError(w, from, turned.Status, turned.Message)
|
|
return
|
|
}
|
|
var done func()
|
|
w, done = run.Wrap(w)
|
|
defer done()
|
|
}
|
|
if len(tried) > 0 {
|
|
r = r.WithContext(context.WithValue(r.Context(), triedKey{}, tried))
|
|
}
|
|
s.serve(w, r, from, body)
|
|
}
|
|
|
|
type triedKey struct{}
|
|
|
|
// triedOn is body as it goes to model on p, in the agent's API: what each
|
|
// middleware of the request that is also gwmw.Tried (the JS chain's
|
|
// onProvider) made of it for that provider. Each try starts from the body
|
|
// it is given, so a change for one provider never reaches another's.
|
|
func triedOn(ctx context.Context, p provider.Provider, model string, body []byte) []byte {
|
|
tried, _ := ctx.Value(triedKey{}).([]gwmw.Tried)
|
|
if len(tried) == 0 {
|
|
return body
|
|
}
|
|
to := gwmw.To{ID: p.ID, Name: p.Name, Account: accountAgent(p), Model: model}
|
|
for _, t := range tried {
|
|
body = t.Tried(body, to)
|
|
}
|
|
return body
|
|
}
|
|
|
|
// middlewareWanted: plugins.json has a JS middleware on, so plugins/middleware
|
|
// is in use.
|
|
func middlewareWanted() bool { return middleware.On() > 0 }
|
|
|
|
// gatewayHooks runs the asynchronous request hooks (OpenCode plugins'
|
|
// gateway entries, in the plugin host) on an agent's request: the body they
|
|
// leave is the one served, and they see the reply the agent got once it is
|
|
// whole. Its writer wraps the middleware's, so what they see is what the
|
|
// agent was given. With no hook it is the request as it came.
|
|
func gatewayHooks(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) (http.ResponseWriter, []byte, func()) {
|
|
if !plugin.HasGateway() {
|
|
return w, body, func() {}
|
|
}
|
|
info := plugin.GatewayContext{Origin: gatewayOrigin(r), Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r), Session: sessionOf(r.Header)}
|
|
if req, err := parse(from, body); err == nil {
|
|
info.Cwd = workDir(req)
|
|
info.Query = gatewayQuery(req)
|
|
}
|
|
run := plugin.GatewayBegin(r.Context(), body, info)
|
|
if run == nil {
|
|
return w, body, func() {}
|
|
}
|
|
w, done := gatewayResponse(w, r, from, run.Body, run)
|
|
return w, run.Body, func() { done(); run.Close() }
|
|
}
|
|
|
|
// gatewayQuery uses the same user-authored words as routing, excluding
|
|
// agent context, tool results and images. Tool-only increments have none.
|
|
func gatewayQuery(req *Request) string {
|
|
for i := len(req.Messages) - 1; i >= 0; i-- {
|
|
m := req.Messages[i]
|
|
if m.Role != "user" {
|
|
continue
|
|
}
|
|
if query := userSaid(m); query != "" {
|
|
return query
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// gatewayOrigin exposes provenance, never credentials or peer addresses.
|
|
// Forwarded traffic remains remote even when the administrator trusts its
|
|
// proxy for authentication: that trust does not establish conversation ownership.
|
|
func gatewayOrigin(r *http.Request) string {
|
|
if access.Caller(r.Context()).KeyID != "" || managedKey(r) {
|
|
return "gateway-key"
|
|
}
|
|
if local(r) && !slices.ContainsFunc(forwardHeaders, func(h string) bool { return r.Header.Get(h) != "" }) {
|
|
return "local"
|
|
}
|
|
return "remote"
|
|
}
|