diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 6274c5c0b..584eb47c6 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -335,6 +335,8 @@ A plugin sign-in magpie gives up on ends in the host too (#5016). The user's Can Every other call but `init` is cancellable too (#4678): a models list, a usage read or a check magpie stops waiting for (its caller left, or `listWait` ran out) gets an `abort`, and `host.js` aborts the call's signal, which the usage hook gets as `usage(..., { signal })` and the models hook as `signal`. The call stays pending in the host until its handler ends, and nothing it answers after the abort is sent, so a hook still saving a refreshed sign-in finishes before the host may exit. `TestCancelledCallKeepsTheHostTillItsHookEnds` and the other tests in [`plugin_rpc_cancel_test.go`](../../internal/plugin/plugin_rpc_cancel_test.go). +A plugin `fetch` has a bound before its head as well as between its body's bytes (`bodyIdleWait`, 30 minutes, in [`host.go`](../../internal/plugin/host.go); `headRead` for the head). A plugin whose vendor took the request and never answered (the Devin plugin returns its head only with Devin's first words; wu_chong4136 on X waited 10 to 20 minutes) is given up on with an `abort`, and the agent gets the gateway's retryable 502 (an SSE error on a stream) instead of keepalives for as long as the plugin waits. A plugin can bound its own vendor tighter: the Devin plugin gives up after 5 minutes of quiet with a 504 (0.1.45, the Devin mover's `min`). + The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSignIn`. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects. ## Verification diff --git a/internal/gateway/plugin_head_wait_test.go b/internal/gateway/plugin_head_wait_test.go new file mode 100644 index 000000000..9706b5849 --- /dev/null +++ b/internal/gateway/plugin_head_wait_test.go @@ -0,0 +1,66 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" +) + +// A plugin whose vendor took the request and never answered it (the Devin +// plugin answers its head only once Devin sends the reply's first words) +// left the agent on keepalives with no error for as long as it waited +// (wu_chong4136 on X: 10 to 20 minutes). The plugin's fetch now gives the +// head up after the reply wait, and the agent gets an error it can retry, +// on a stream and on a whole reply. Before, both requests held until the +// client's own deadline. +func TestPluginHeadNeverSentEndsInAnError(t *testing.T) { + t.Cleanup(plugin.ReplyWaitForTest(300 * time.Millisecond)) + var asked, open atomic.Int64 + up := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + open.Add(1) + defer open.Add(-1) + // read whole, so the server watches the connection and sees the + // host's abort close it + _, _ = io.Copy(io.Discard, r.Body) + <-r.Context().Done() // took the request, never answers + }) + url, model, client := pluginReplyGateway(t, up) + for _, stream := range []bool{true, false} { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url+"/v1/chat/completions", strings.NewReader(pluginReplyRequest(model, stream))) + req.Header.Set("Content-Type", "application/json") + res, err := client.Do(req) + if err != nil { + cancel() + t.Fatalf("stream=%t: %v", stream, err) + } + b, err := io.ReadAll(res.Body) + res.Body.Close() + cancel() + if err != nil { + t.Fatalf("stream=%t: the reply was held to the client's deadline: %v", stream, err) + } + if !strings.Contains(string(b), "sent no reply") { + t.Fatalf("stream=%t: status %d, body %q, want the give-up named", stream, res.StatusCode, b) + } + if res.StatusCode == http.StatusOK && !strings.Contains(string(b), "error") { + t.Fatalf("stream=%t: a 200 with no error: %q", stream, b) + } + t.Logf("stream=%t: %d %s", stream, res.StatusCode, b) + } + deadline := time.Now().Add(10 * time.Second) + for open.Load() > 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + t.Logf("asked %d, open %d", asked.Load(), open.Load()) + if n := open.Load(); n > 0 { + t.Fatalf("%d of %d vendor requests still open after the fetch was given up on", n, asked.Load()) + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index b38e045ef..2d865bffe 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -2183,9 +2183,28 @@ var errBodyClosed = errors.New("the reply's body was closed") // is not cut; a dead connection's read ends at the same bound. var bodyIdleWait = 30 * time.Minute +// ReplyWaitForTest sets bodyIdleWait, the head's and the body's wait, to d +// until restore. +func ReplyWaitForTest(d time.Duration) (restore func()) { + old := bodyIdleWait + bodyIdleWait = d + return func() { bodyIdleWait = old } +} + // headRead waits for the call's reply head, giving back the answer it read on // the way: the body has to end with that answer too, error and all. +// +// The head is waited on for bodyIdleWait at most, as the body's silence +// is: a plugin may answer only once its vendor has sent the reply's first +// words (the Devin plugin does), so a request its vendor took and never +// answered left the head unsent, and the gateway kept the agent alive +// with keepalives and nothing else, for as long as the agent waited +// (wu_chong4136 on X: 10 to 20 minutes, until the effort or the +// conversation changed). Given up, the fetch fails with an error that +// names the wait, which the next account or the agent's retry takes up. func (c *call) headRead(ctx context.Context) (head message, answer *message, err error) { + idle := time.NewTimer(bodyIdleWait) + defer idle.Stop() for { if m, ok := c.pop(); ok { return m, nil, nil @@ -2216,6 +2235,8 @@ func (c *call) headRead(ctx context.Context) (head message, answer *message, err // the host is gone: no head is coming, so the fetch gives up // rather than waiting on a context that may never end continue + case <-idle.C: + return message{}, nil, fmt.Errorf("the plugin sent no reply in %s; that fetch was given up on", bodyIdleWait) } } } diff --git a/internal/plugin/host_test.go b/internal/plugin/host_test.go index 8da10ec27..30ad4e67d 100644 --- a/internal/plugin/host_test.go +++ b/internal/plugin/host_test.go @@ -1098,6 +1098,61 @@ func TestHostBodyIdleEndsASilentStream(t *testing.T) { waitFor(t, "the silent call was given up on", func() bool { return !f.registered(id) }) } +// TestHostHeadWaitEndsAFetchNeverAnswered: a plugin that answers only once +// its vendor sends the reply's first words (the Devin plugin) leaves the +// head unsent while a vendor that took the request says nothing, and the +// gateway kept the agent waiting on keepalives for as long as it would wait +// (wu_chong4136 on X: 10 to 20 minutes). The head is waited on for +// bodyIdleWait, as the body's silence is; then the fetch fails with why and +// the plugin's fetch is aborted, as Fetch settles a failed head read. Before, +// the head read held until the client cancelled it. +func TestHostHeadWaitEndsAFetchNeverAnswered(t *testing.T) { + f := newFakeHost(t) + oldWait := bodyIdleWait + bodyIdleWait = 150 * time.Millisecond + t.Cleanup(func() { bodyIdleWait = oldWait }) + id, c := f.begin(t, true) + errs := make(chan error, 1) + go func() { + _, _, err := c.headRead(context.Background()) + if err != nil { + c.settle(err) // as Fetch does + } + errs <- err + }() + select { + case err := <-errs: + if err == nil || !strings.Contains(err.Error(), "sent no reply") { + t.Fatalf("a head never sent = %v, want the give-up", err) + } + case <-time.After(5 * time.Second): + t.Fatal("a fetch whose head never came held its reader for ever") + } + waitFor(t, "the plugin's fetch was aborted", func() bool { + for _, m := range f.methods() { + if m == "abort" { + return true + } + } + return false + }) + waitFor(t, "the call left the host", func() bool { return !f.registered(id) }) +} + +// TestHostHeadWaitSparesAHeadInTime: a head that comes inside the wait is +// read as before, and the body after it is the body's own wait. +func TestHostHeadWaitSparesAHeadInTime(t *testing.T) { + f := newFakeHost(t) + oldWait := bodyIdleWait + bodyIdleWait = 5 * time.Second + t.Cleanup(func() { bodyIdleWait = oldWait }) + id, c := f.begin(t, true) + f.head(id) + if _, _, err := c.headRead(context.Background()); err != nil { + t.Fatalf("a head in time = %v", err) + } +} + // TestHostBodyIdleSparesAFedStream: the idle wait is between bytes, not the // reply's whole length — a stream a chunk comes to every few waits goes on // however long it talks, and ends at its answer as before. diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index a840bde34..ad965b970 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -17,7 +17,7 @@ import ( func init() { movers["devin"] = &mover{ pkg: "@magpie-community/opencode-devin-auth", - min: "0.1.44", // 0.1.44: a long conversation Devin refuses with "There is an issue with this request, please try a different model" goes so it can take it: a picture as the type its bytes are, not the one it was said to be (Devin refuses a PNG labelled JPEG); no user prompt of white space alone; thinking with a signature Devin turns away sent again once without it; and past half the model's window the refusal is a 400 "input is too long for the model's context", so the agent compacts (a1pha1nthefog on X); 0.1.42: when neither Devin nor the devin CLI names the account's models, the snapshot list is marked fell back, so magpie keeps the account's last good list and the models picked from it (Archivemylife on X, agy-cli's sibling); 0.1.41: a Gemini model's reply goes back on the next request with its thought signature, signature_type "gemini" and the model that wrote it, as the devin CLI sends it, so Gemini 4 Hydrogen keeps its thoughts through a tool loop (liuzhengdong99 on X); 0.1.40: a key typed in, such as a service user's cog_… key, is a sign-in method of its own ("Devin API key (cog_…)", OpenCode 2's key method too), sent to chat and usage as a sign-in's token is; the first usage read names the account (wuxudongxd on X); 0.1.36: a model that isn't Claude gets its earlier turns' reasoning back as unsigned thinking (field 11) from chat completions' reasoning_content, OpenCode 2's reasoning parts and Messages thinking blocks, so swe-2 keeps thinking through a tool loop; Claude still gets only signed thinking (plugins #703, kamikakushi); 0.1.35: Claude's thinking keeps its signature: delta_signature and its type are read, a Messages reply's thinking block carries the signature (a signature_delta when streamed), and the next request sends the signed thinking back with signature and signature_type (plugins #665, Vigilans); 0.1.34: keepalive pings are timed from when the request before them was sent, not from its reply's end, so a long reply or a slow ping no longer puts the next past Devin's 5-minute cache (plugins #626, zelong77); the keepalive key reads the session and subagent magpie names (x-magpie-session, x-magpie-subagent), so a permission check whose merged history grew replaces its pings (plugins #620, zelong77); 0.1.33: a Claude Code Auto permission check whose history grew in its first message replaces its keepalive pings instead of adding a task beside them; the key is the session, agent, instructions and tools (plugins #620, zelong77); 0.1.32: a system notice partway through a conversation goes to Devin as a user prompt in its place, with its cache mark, and one that arrives while tool calls wait for results goes after them (plugins #599, leosocy); 0.1.31: each keepalive ping is reported through magpie.usage (a Cache keep-alive call on the conversation's model and account, with its tokens), and package.json gives the interval and ping count's defaults to the Plugins › Options editor (plugins #592, zelong77); 0.1.30: an opt-in cache keepalive, "Keep the cache warm" (off by default): after a reply that used the cache, the same request goes again every 285 s with "continue" and max_tokens 1, as the devin CLI does, until the conversation's next request, a 401, 402 or 429, two misses or 6 pings (plugins #592, zelong77); 0.1.29: a failed tool result on the Messages path says "Error: " first, as on chat completions; 0.1.28: Devin's Claude models are asked on Anthropic's Messages API, each block of the client's its own prompt with Devin's cache mark where the client put cache_control, so a grown history is read from the cache (plugins #566, zelong77); 0.1.27: SWE-2 asked with no effort goes as a free variant, never a paid -lightning one Devin lists first, and as SNAPSHOT's swe-2-high when the account's list leaves the family out, not the bare family id; a model list Devin won't give is logged and shown in usage ("Free models: unknown"), not swallowed (zws13579 on Discord, plugins #533); 0.1.26: a usage read Devin answers 401 marks the account signed out, so its rows offer Sign in again, and a clean read takes the mark off (blue12345655 on Discord); 0.1.25: an anyOf beside a type below a tool's root (what the gateway writes for a Gemini model) goes to Devin's Gemini models merged or as a oneOf, so Kimi Code's Read no longer 400s (plugins #458); 0.1.24: the CLI's sign-in keeps its "cli" mark as the string OpenCode stores, so OpenCode 1 keeps the account (plugins #396); 0.1.23: a reply with only usage or metadata is refused before the stream starts, not passed on as an empty success (plugins #297); 0.1.22: organisations under one email are kept apart, each with its own quota (plugins #296); 0.1.21: a chat request past 8 KiB goes as a gzipped Connect frame, as the devin CLI sends it, where an uncompressed large one could be refused 413 (plugins #275); 0.1.20: a tool result's images go to Devin on the tool message that answers the call, as the built-in sent them; 0.1.19: Devin answers in JSON when the request asks for it (response_format into the instructions, as the built-in); 0.1.18: a tool whose parameters have a root anyOf, oneOf or allOf goes as a plain object (#1196), a branch that is a union itself folded too (#1271); a turn's parallel calls split over two assistant messages keep their results (#1275); a temperature or top_p of 0 goes as 1e-6, which Devin takes (plugins #50); a call id with ":" or "#" goes to the agent as one Claude Code takes, and back to Devin as it was (#1304); a week used up, its share left out of GetUserStatus, is 100% and holds the account until its reset (面条); SWE-2, which Devin's quota doesn't count (its Free cost tier), is left out of the day and week and listed free, so a used-up quota no longer holds it (太陽と向日葵); a tool schema with a list type, an array with no items, or properties or an enum with no type goes to a Gemini model in a shape it takes, not "There is an issue with this request" (7eleven); each model carries the price Devin lists for it, and SWE-2 stays free beside the -lightning variants Devin now files under it (太陽と向日葵, Usage showed no cost) + min: "0.1.45", // 0.1.45: a request Devin took and then went quiet on (no head, or no frame, for 5 minutes) ends in a 504 the agent can send again, rather than waiting on keepalives for 20 minutes; 0.1.44: a long conversation Devin refuses with "There is an issue with this request, please try a different model" goes so it can take it: a picture as the type its bytes are, not the one it was said to be (Devin refuses a PNG labelled JPEG); no user prompt of white space alone; thinking with a signature Devin turns away sent again once without it; and past half the model's window the refusal is a 400 "input is too long for the model's context", so the agent compacts (a1pha1nthefog on X); 0.1.42: when neither Devin nor the devin CLI names the account's models, the snapshot list is marked fell back, so magpie keeps the account's last good list and the models picked from it (Archivemylife on X, agy-cli's sibling); 0.1.41: a Gemini model's reply goes back on the next request with its thought signature, signature_type "gemini" and the model that wrote it, as the devin CLI sends it, so Gemini 4 Hydrogen keeps its thoughts through a tool loop (liuzhengdong99 on X); 0.1.40: a key typed in, such as a service user's cog_… key, is a sign-in method of its own ("Devin API key (cog_…)", OpenCode 2's key method too), sent to chat and usage as a sign-in's token is; the first usage read names the account (wuxudongxd on X); 0.1.36: a model that isn't Claude gets its earlier turns' reasoning back as unsigned thinking (field 11) from chat completions' reasoning_content, OpenCode 2's reasoning parts and Messages thinking blocks, so swe-2 keeps thinking through a tool loop; Claude still gets only signed thinking (plugins #703, kamikakushi); 0.1.35: Claude's thinking keeps its signature: delta_signature and its type are read, a Messages reply's thinking block carries the signature (a signature_delta when streamed), and the next request sends the signed thinking back with signature and signature_type (plugins #665, Vigilans); 0.1.34: keepalive pings are timed from when the request before them was sent, not from its reply's end, so a long reply or a slow ping no longer puts the next past Devin's 5-minute cache (plugins #626, zelong77); the keepalive key reads the session and subagent magpie names (x-magpie-session, x-magpie-subagent), so a permission check whose merged history grew replaces its pings (plugins #620, zelong77); 0.1.33: a Claude Code Auto permission check whose history grew in its first message replaces its keepalive pings instead of adding a task beside them; the key is the session, agent, instructions and tools (plugins #620, zelong77); 0.1.32: a system notice partway through a conversation goes to Devin as a user prompt in its place, with its cache mark, and one that arrives while tool calls wait for results goes after them (plugins #599, leosocy); 0.1.31: each keepalive ping is reported through magpie.usage (a Cache keep-alive call on the conversation's model and account, with its tokens), and package.json gives the interval and ping count's defaults to the Plugins › Options editor (plugins #592, zelong77); 0.1.30: an opt-in cache keepalive, "Keep the cache warm" (off by default): after a reply that used the cache, the same request goes again every 285 s with "continue" and max_tokens 1, as the devin CLI does, until the conversation's next request, a 401, 402 or 429, two misses or 6 pings (plugins #592, zelong77); 0.1.29: a failed tool result on the Messages path says "Error: " first, as on chat completions; 0.1.28: Devin's Claude models are asked on Anthropic's Messages API, each block of the client's its own prompt with Devin's cache mark where the client put cache_control, so a grown history is read from the cache (plugins #566, zelong77); 0.1.27: SWE-2 asked with no effort goes as a free variant, never a paid -lightning one Devin lists first, and as SNAPSHOT's swe-2-high when the account's list leaves the family out, not the bare family id; a model list Devin won't give is logged and shown in usage ("Free models: unknown"), not swallowed (zws13579 on Discord, plugins #533); 0.1.26: a usage read Devin answers 401 marks the account signed out, so its rows offer Sign in again, and a clean read takes the mark off (blue12345655 on Discord); 0.1.25: an anyOf beside a type below a tool's root (what the gateway writes for a Gemini model) goes to Devin's Gemini models merged or as a oneOf, so Kimi Code's Read no longer 400s (plugins #458); 0.1.24: the CLI's sign-in keeps its "cli" mark as the string OpenCode stores, so OpenCode 1 keeps the account (plugins #396); 0.1.23: a reply with only usage or metadata is refused before the stream starts, not passed on as an empty success (plugins #297); 0.1.22: organisations under one email are kept apart, each with its own quota (plugins #296); 0.1.21: a chat request past 8 KiB goes as a gzipped Connect frame, as the devin CLI sends it, where an uncompressed large one could be refused 413 (plugins #275); 0.1.20: a tool result's images go to Devin on the tool message that answers the call, as the built-in sent them; 0.1.19: Devin answers in JSON when the request asks for it (response_format into the instructions, as the built-in); 0.1.18: a tool whose parameters have a root anyOf, oneOf or allOf goes as a plain object (#1196), a branch that is a union itself folded too (#1271); a turn's parallel calls split over two assistant messages keep their results (#1275); a temperature or top_p of 0 goes as 1e-6, which Devin takes (plugins #50); a call id with ":" or "#" goes to the agent as one Claude Code takes, and back to Devin as it was (#1304); a week used up, its share left out of GetUserStatus, is 100% and holds the account until its reset (面条); SWE-2, which Devin's quota doesn't count (its Free cost tier), is left out of the day and week and listed free, so a used-up quota no longer holds it (太陽と向日葵); a tool schema with a list type, an array with no items, or properties or an enum with no type goes to a Gemini model in a shape it takes, not "There is an issue with this request" (7eleven); each model carries the price Devin lists for it, and SWE-2 stays free beside the -lightning variants Devin now files under it (太陽と向日葵, Usage showed no cost) agents: []string{"devin"}, out: func() ([]Moving, error) { var out []Moving