devin: served straight through Devin's API, not the CLI over ACP — each request goes to the GetChatMessage RPC the devin CLI itself uses, with its sign-in: the conversation as it is, the caller's tools, images and all, and the reply streamed back text, thinking and tool calls as they come. A family's name is sent as its variant at the effort asked for; Adaptive and Fusion, which the API doesn't serve, are no longer listed. The instructions go at the head of the first message, as Kiro's do, since Devin turns away Claude Code's own in its system field. Tested live from a sandbox: Claude Code and OpenCode on Opus 5.5, SWE-2 and GPT-6 Sol list, read and write files through several tool rounds; images and a tool round trip answered on Claude, SWE, GPT and Gemini models

This commit is contained in:
yetone
2026-09-27 15:30:24 +08:00
parent 1d4930dd8e
commit ce8d0e065c
7 changed files with 933 additions and 760 deletions
+4 -4
View File
@@ -181,10 +181,10 @@ Code process; Pi, OpenCode and every other agent use this path automatically.
The generated harness stays out of Anthropic's system-prompt classifier while
its instructions remain part of the user context. This requires Claude Code
to be installed and signed in.
Cursor, Grok (SuperGrok, through Grok Build) and Devin subscriptions likewise run through their own CLIs —
none of them has an endpoint a borrowed key can be sent to — with Devin
driven over ACP (`devin acp`) in a home of magpie's own that keeps only the
caller's MCP tools and shares just the sign-in.
Cursor and Grok (SuperGrok, through Grok Build) subscriptions likewise run
through their own CLIs — neither has an endpoint a borrowed key can be sent
to. A Devin subscription talks straight to the API the devin CLI uses, with
the CLI's sign-in, the caller's tools passed through as they are.
Google sign-ins — Gemini CLI's and Antigravity's — talk to Google's Code
Assist API directly: magpie reads Gemini CLI's own login from `~/.gemini` or
signs one in itself, and refreshes the token in memory. Google no longer
+575
View File
@@ -0,0 +1,575 @@
package gateway
// A Devin subscription is served through the API the devin CLI talks to —
// Windsurf's GetChatMessage, a Connect RPC in protobuf — the way a Kiro one
// is (kiro.go): each request goes whole, the conversation with the caller's
// tools, and the reply streams back as Connect frames, decoded here into
// events. The sign-in is the CLI's credentials.toml (provider/devin.go).
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/binary"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"runtime"
"slices"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// devinAuth and devinVariant are the sign-in and the model the API is
// asked for; vars so tests can stand in for them.
var (
devinAuth = provider.DevinAuth
devinVariant = provider.DevinVariant
)
// devinCLIVersion is the CLI the requests say they come from.
const devinCLIVersion = "3000.11.3"
// serveDevin answers a request through Devin's API.
func (s *Server) serveDevin(w http.ResponseWriter, r *http.Request, from provider.Protocol, model string, body []byte, usage *Usage) (int, string) {
req, err := parse(from, body)
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
req.Model = model
ask := s.askDevin(model)
if req.WebSearch && !searching(r.Context()) {
if _, _, ok := searcher(); ok {
return s.searchReply(w, r, from, "Devin", req, usage, ask)
}
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
events, status, msg := ask(ctx, req)
if events == nil {
return writeError(w, from, status, msg), msg
}
return relay(w, r, from, "Devin", req, events, usage, cancel, func(string, string, bool) {})
}
// askDevin is a round for Devin's API.
func (s *Server) askDevin(model string) round {
return func(ctx context.Context, req *Request) (<-chan Event, int, string) {
key, server, err := devinAuth()
if err != nil {
return nil, 401, "Devin: " + err.Error()
}
uid := devinVariant(ctx, model, req.Effort)
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, server+"/exa.api_server_pb.ApiServerService/GetChatMessage",
bytes.NewReader(connectFrame(buildDevin(req, uid, key))))
if err != nil {
return nil, 500, "Devin: " + err.Error()
}
hr.Header.Set("Content-Type", "application/connect+proto")
hr.Header.Set("Connect-Protocol-Version", "1")
hr.Header.Set("Authorization", "Basic "+key)
res, err := s.client.Do(hr)
if err != nil {
return nil, 502, "Devin: " + err.Error()
}
if res.StatusCode/100 != 2 {
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
status, msg := devinFailure(res.StatusCode, b)
return nil, status, "Devin: " + msg
}
// an error comes as the stream's end, before anything else: read
// that far so it is answered with its own status
br := bufio.NewReaderSize(res.Body, 64<<10)
first, err := readConnectFrame(br)
if err != nil {
res.Body.Close()
return nil, 502, "Devin: the reply broke off: " + err.Error()
}
if first.end {
res.Body.Close()
status, msg := devinFailure(200, first.data)
if status/100 == 2 {
status, msg = 502, "an empty reply"
}
return nil, status, "Devin: " + msg
}
events := make(chan Event, 16)
go func() {
defer res.Body.Close()
decodeDevin(ctx, first, br, events, model)
}()
return events, 0, ""
}
}
// devinFailure is the status and message for a Connect error:
// {"code": "...", "message": "..."}, or at a stream's end
// {"error": {"code": "...", "message": "..."}}.
func devinFailure(status int, body []byte) (int, string) {
var e struct {
Code string `json:"code"`
Message string `json:"message"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
msg := strings.TrimSpace(string(body))
code := ""
if json.Unmarshal(body, &e) == nil {
if e.Error != nil {
code, msg = e.Error.Code, e.Error.Message
} else if e.Code != "" {
code, msg = e.Code, e.Message
}
if msg == "" {
msg = code
}
}
if msg == "" {
msg = http.StatusText(status)
}
lower := strings.ToLower(msg)
switch {
case code == "unauthenticated":
return 401, msg + " — sign in to Devin again"
case code == "resource_exhausted" || strings.Contains(lower, "quota") || strings.Contains(lower, "rate limit"):
return 429, "usage limit reached: " + msg
case strings.Contains(lower, "content policy"):
// Devin turns away some system prompts outright; sent again, the
// same one is turned away again
return 400, msg
case strings.Contains(lower, "too long") || strings.Contains(lower, "context length") || strings.Contains(lower, "too many tokens"):
return 400, "input is too long for the model's context: " + msg
case code == "invalid_argument":
return 400, msg
case code == "unavailable":
return 503, msg
case code != "":
return 502, msg
}
return status, msg
}
// ---- protobuf, by hand ---------------------------------------------------
// pb builds a protobuf message field by field.
type pb []byte
func (b pb) tag(num, wire int) pb { return binary.AppendUvarint(b, uint64(num<<3|wire)) }
func (b pb) varint(num int, v uint64) pb { return binary.AppendUvarint(b.tag(num, 0), v) }
func (b pb) bytes(num int, v []byte) pb {
return append(binary.AppendUvarint(b.tag(num, 2), uint64(len(v))), v...)
}
func (b pb) str(num int, v string) pb { return b.bytes(num, []byte(v)) }
func (b pb) double(num int, v float64) pb {
return binary.LittleEndian.AppendUint64(b.tag(num, 1), math.Float64bits(v))
}
// pbField is one field of a message being read.
type pbField struct {
num int
wire int
n uint64 // a varint or fixed value
data []byte // a length-delimited one
}
// pbFields reads a message's fields; a malformed tail is dropped.
func pbFields(b []byte) []pbField {
var out []pbField
for len(b) > 0 {
key, n := binary.Uvarint(b)
if n <= 0 {
break
}
b = b[n:]
f := pbField{num: int(key >> 3), wire: int(key & 7)}
switch f.wire {
case 0:
v, n := binary.Uvarint(b)
if n <= 0 {
return out
}
f.n, b = v, b[n:]
case 1:
if len(b) < 8 {
return out
}
f.n, b = binary.LittleEndian.Uint64(b), b[8:]
case 2:
l, n := binary.Uvarint(b)
if n <= 0 || uint64(len(b)-n) < l {
return out
}
f.data, b = b[n:n+int(l)], b[n+int(l):]
case 5:
if len(b) < 4 {
return out
}
f.n, b = uint64(binary.LittleEndian.Uint32(b)), b[4:]
default:
return out
}
out = append(out, f)
}
return out
}
// connectFrame wraps a message as the one frame of a Connect stream.
func connectFrame(msg []byte) []byte {
out := make([]byte, 5, 5+len(msg))
binary.BigEndian.PutUint32(out[1:], uint32(len(msg)))
return append(out, msg...)
}
// connectMsg is one frame of a Connect stream: a message, or the stream's
// end with its JSON.
type connectMsg struct {
end bool
data []byte
}
func readConnectFrame(r *bufio.Reader) (connectMsg, error) {
var head [5]byte
if _, err := io.ReadFull(r, head[:]); err != nil {
return connectMsg{}, err
}
n := binary.BigEndian.Uint32(head[1:])
if n > 64<<20 {
return connectMsg{}, errors.New("a malformed stream")
}
data := make([]byte, n)
if _, err := io.ReadFull(r, data); err != nil {
return connectMsg{}, err
}
if head[0]&1 != 0 {
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return connectMsg{}, err
}
if data, err = io.ReadAll(io.LimitReader(zr, 64<<20)); err != nil {
return connectMsg{}, err
}
}
return connectMsg{end: head[0]&2 != 0, data: data}, nil
}
// ---- the request ---------------------------------------------------------
// Devin's roles for a message.
const (
devinUser = 1
devinAssistant = 2
devinTool = 4
)
// devinNoResult answers a call the conversation never answered.
const devinNoResult = "Tool use was interrupted and did not produce a result."
// devinMsg is a message of the conversation, before it is encoded.
type devinMsg struct {
role int
text string
calls []Part
callID string // what a tool result answers
images []Part
thinking []Part // with Devin's own signatures
}
// buildDevin is the GetChatMessage request for r, to the model uid.
func buildDevin(r *Request, uid, key string) []byte {
var msgs []devinMsg
var pending []Part // calls the last reply made, not yet answered
answer := func() {
for _, c := range pending {
msgs = append(msgs, devinMsg{role: devinTool, callID: c.ID, text: devinNoResult})
}
pending = nil
}
for _, m := range r.Messages {
if m.Role == "assistant" {
a := devinMsg{role: devinAssistant}
var texts []string
for _, p := range m.Parts {
switch p.Kind {
case Text:
if p.Text != "" {
texts = append(texts, p.Text)
}
case ToolCall:
a.calls = append(a.calls, p)
case Thinking:
if strings.HasPrefix(p.Signature, "sealed.") {
a.thinking = append(a.thinking, p)
}
}
}
a.text = strings.Join(texts, "\n\n")
if a.text == "" && len(a.calls) == 0 {
continue // a turn that only thought, or failed
}
answer()
msgs = append(msgs, a)
pending = a.calls
continue
}
u := devinMsg{role: devinUser}
var texts []string
for _, p := range m.Parts {
switch p.Kind {
case Text:
if p.Text != "" {
texts = append(texts, p.Text)
}
case File:
texts = append(texts, attachmentText(p))
case Image:
if p.Data != "" {
u.images = append(u.images, p)
}
case ToolResult:
// only a call just made is answered, and only once
for i, c := range pending {
if c.ID != p.CallID {
continue
}
out := p.Text
if out == "" {
out = "(no output)"
}
if p.IsError {
out = "Error: " + out
}
msgs = append(msgs, devinMsg{role: devinTool, callID: c.ID, text: out})
pending = append(pending[:i:i], pending[i+1:]...)
break
}
}
}
u.text = strings.Join(texts, "\n\n")
if u.text == "" && len(u.images) == 0 {
continue
}
answer()
msgs = append(msgs, u)
}
answer()
if len(msgs) == 0 || msgs[len(msgs)-1].role == devinAssistant && len(msgs[len(msgs)-1].calls) == 0 {
msgs = append(msgs, devinMsg{role: devinUser, text: "Please proceed with the task."})
}
// the instructions go at the head of the first message, as Kiro's do:
// Devin turns away some agents' own in its system field (Claude Code's
// "You are a Claude agent, built on Anthropic's Claude Agent SDK")
if r.System != "" {
at := slices.IndexFunc(msgs, func(m devinMsg) bool { return m.role == devinUser })
if at < 0 {
msgs = slices.Insert(msgs, 0, devinMsg{role: devinUser})
at = 0
}
msgs[at].text = joinNonEmpty(r.System, msgs[at].text)
}
meta := pb{}.str(1, "devin-cli").str(2, devinCLIVersion).str(3, key).str(4, "en").
str(5, runtime.GOOS).str(7, devinCLIVersion).str(12, "chisel").str(28, "chisel")
out := pb{}.bytes(1, meta)
for _, m := range msgs {
out = out.bytes(3, encodeDevinMsg(m))
}
out = out.varint(7, 5)
max := r.MaxTokens
if max <= 0 {
max = 128000 // the server holds it to the model's own
}
topP := 0.95
if r.TopP != nil {
topP = *r.TopP
}
temp := 1.0
if r.Temp != nil {
temp = *r.Temp
}
out = out.bytes(8, pb{}.varint(1, 1).varint(2, uint64(max)).varint(3, 400).double(5, temp).varint(7, 40).double(8, topP))
// the caller's tools, and any the conversation used that it no longer
// offers
offered := map[string]bool{}
tool := func(name, desc string, schema json.RawMessage) {
if len(bytes.TrimSpace(schema)) == 0 || string(bytes.TrimSpace(schema)) == "null" {
schema = json.RawMessage(`{"type":"object","properties":{}}`)
}
if desc == "" {
desc = name
}
offered[name] = true
out = out.bytes(10, pb{}.str(1, name).str(2, desc).bytes(3, schema))
}
if r.ToolChoice != "none" {
for _, t := range r.Tools {
tool(t.Name, t.Description, t.Schema)
}
}
for _, m := range msgs {
for _, c := range m.calls {
if !offered[c.Name] {
tool(c.Name, "Tool", nil)
}
}
}
return out.str(21, uid)
}
func encodeDevinMsg(m devinMsg) []byte {
b := pb{}.str(1, newUUID()).varint(2, uint64(m.role))
if m.text != "" {
b = b.str(3, m.text)
}
for _, c := range m.calls {
b = b.bytes(6, pb{}.str(1, c.ID).str(2, c.Name).bytes(3, argsOf(c)))
}
if m.callID != "" {
b = b.str(7, m.callID)
}
for _, p := range m.images {
mt := p.MediaType
if mt == "" {
mt = "image/png"
}
b = b.bytes(10, pb{}.str(1, p.Data).str(2, mt))
}
for _, t := range m.thinking {
b = b.str(11, t.Text).str(12, t.Signature).str(18, "sealed")
}
return b
}
// ---- the reply -----------------------------------------------------------
// decodeDevin turns Devin's reply, from its first frame on, into events.
func decodeDevin(ctx context.Context, first connectMsg, br *bufio.Reader, out chan<- Event, model string) {
defer close(out)
send := func(ev Event) bool {
select {
case out <- ev:
return true
case <-ctx.Done():
return false
}
}
if !send(Event{Kind: KStart, MsgID: "msg_" + randomToken()[:24], Model: model}) {
return
}
var d devinDecoder
var failed string
for f := first; ; {
if f.end {
if status, msg := devinFailure(200, f.data); status/100 != 2 {
failed = msg
}
break
}
for _, ev := range d.frame(f.data) {
if !send(ev) {
return
}
}
var err error
if f, err = readConnectFrame(br); err != nil {
if !errors.Is(err, io.EOF) && ctx.Err() == nil {
failed = "the reply broke off: " + err.Error()
}
break
}
}
if failed != "" {
send(Event{Kind: KError, Text: failed})
return
}
u := d.usage
if u.Output == 0 {
u.Output = (d.said + 3) / 4
}
send(Event{Kind: KUsage, Usage: u})
stop := "stop"
switch {
case d.tools > 0 || d.stop == 10:
stop = "tool"
case d.stop == 3:
stop = "length"
}
send(Event{Kind: KStop, Stop: stop})
}
// devinDecoder follows a reply: its text and thinking in pieces, its tool
// calls — each opened with its id and name, the arguments in pieces after
// — why it stopped, and what it used.
type devinDecoder struct {
tools int
stop uint64
usage Usage
said int
}
func (d *devinDecoder) frame(b []byte) []Event {
var evs []Event
for _, f := range pbFields(b) {
switch {
case f.num == 3 && f.wire == 2 && len(f.data) > 0:
d.said += len(f.data)
evs = append(evs, Event{Kind: KText, Text: string(f.data)})
case f.num == 9 && f.wire == 2 && len(f.data) > 0:
d.said += len(f.data)
evs = append(evs, Event{Kind: KThink, Text: string(f.data)})
case f.num == 6 && f.wire == 2:
var id, name, args string
for _, g := range pbFields(f.data) {
switch g.num {
case 1:
id = string(g.data)
case 2:
name = string(g.data)
case 3:
args += string(g.data)
}
}
if name != "" {
d.tools++
if id == "" {
id = "call_" + randomToken()[:24]
}
evs = append(evs, Event{Kind: KToolStart, ID: id, Name: name})
}
if args != "" {
evs = append(evs, Event{Kind: KToolArgs, Text: args})
}
case f.num == 5 && f.wire == 0:
d.stop = f.n
case f.num == 7 && f.wire == 2:
for _, g := range pbFields(f.data) {
if g.wire != 0 || g.n == 0 {
continue
}
switch g.num {
case 2:
d.usage.Input = int(g.n)
case 3:
d.usage.Output = int(g.n)
case 4:
d.usage.CacheWrite = int(g.n)
case 5:
d.usage.CacheRead = int(g.n)
}
}
}
}
return evs
}
-558
View File
@@ -1,558 +0,0 @@
package gateway
// A Devin subscription runs through the genuine devin CLI in ACP mode, the
// way a Cursor one runs through cursor-agent (cursor_subscription.go): the
// caller's tools are an MCP server named in session/new, whose calls park in
// the stdio helper until the caller sends results.
//
// devin acp speaks JSON-RPC over stdio: initialize, session/new (which takes
// the magpie MCP server), session/set_mode, then session/prompt. The answer
// streams back as session/update notifications; the prompt call itself
// returns the stop reason and usage.
//
// It runs in a home of magpie's own. The user's ~/.config/devin has their
// rules, skills and MCP servers, which are theirs and not the caller's; the
// home's own config denies every built-in tool and allows only the magpie
// server's. Only the sign-in is shared: credentials.toml is linked into it.
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
)
// devinPatience stays under the minute devin's MCP client waits on a call.
var devinPatience = 45 * time.Second
// devinHandshake bounds initialize/session/new: a devin that does not answer
// is a dead devin.
var devinHandshake = 60 * time.Second
func (b *subscriptionBridge) startDevin(ctx context.Context, req *Request, model string) (*subscriptionRun, <-chan Event, error) {
binary := provider.DevinExecutable()
if binary == "" {
return nil, nil, errors.New("Devin's CLI is not installed; install it (https://docs.devin.ai/cli) and run `devin auth login`")
}
exe, err := os.Executable()
if err != nil {
return nil, nil, err
}
home, err := devinHome()
if err != nil {
return nil, nil, err
}
tmp, err := os.MkdirTemp("", "magpie-devin-")
if err != nil {
return nil, nil, err
}
cleanup := func() { _ = os.RemoveAll(tmp) }
tools := bridgeTools(req)
if len(tools) > 0 {
tools = append(tools, bridgeTool{Name: waitTool,
Description: "Wait for a tool call that is still running in the user's environment, and get its result. Only for a call whose result said it is still running.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"call":{"type":"string","description":"the id the still-running result gave"}},"required":["call"]}`)})
}
toolsPath := filepath.Join(tmp, "tools.json")
toolBytes, _ := json.Marshal(tools)
if err := os.WriteFile(toolsPath, toolBytes, 0o600); err != nil {
cleanup()
return nil, nil, err
}
token := randomToken()
callback := callbackBaseURL() + "/_magpie/claude-mcp/" + token
ws := filepath.Join(tmp, "workspace")
if err := os.MkdirAll(ws, 0o700); err != nil {
cleanup()
return nil, nil, err
}
cmd := proc.CommandContext(context.Background(), binary, "acp", "--model", model)
cmd.Dir = ws
cmd.Env = netproxy.Env(devinEnv(os.Environ(), home))
stdin, err := cmd.StdinPipe()
if err != nil {
cleanup()
return nil, nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
cleanup()
return nil, nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
cleanup()
return nil, nil, err
}
run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, pending: map[string]chan mcpToolResult{},
patience: devinPatience, late: map[string]chan mcpToolResult{}}
c := &cursorTurn{run: run}
run.onCall = c.called
run.resume = c.resumed
run.begin = func() Event { return Event{Kind: KStart, MsgID: "msg_" + randomToken()[:24], Model: model} }
run.timer = time.AfterFunc(30*time.Minute, run.abort)
segment := run.attach()
run.emit(run.begin())
b.mu.Lock()
b.runs[token] = run
b.mu.Unlock()
if err := cmd.Start(); err != nil {
b.removeRun(run)
return nil, nil, err
}
go func() {
_, _ = io.Copy(&lockedWriter{run: run}, io.LimitReader(stderr, 1<<20))
}()
conn := &devinConn{stdin: stdin, pending: map[int64]chan devinReply{}, run: run}
go conn.read(stdout)
go func() {
_ = cmd.Wait()
run.finish()
}()
shake, cancel := context.WithTimeout(ctx, devinHandshake)
defer cancel()
fail := func(err error) (*subscriptionRun, <-chan Event, error) {
run.abort()
return nil, nil, err
}
if _, err := conn.call(shake, "initialize", map[string]any{
"protocolVersion": 1,
"clientInfo": map[string]any{"name": "magpie", "version": "0"},
"clientCapabilities": map[string]any{},
}); err != nil {
return fail(fmt.Errorf("devin acp initialize: %w", err))
}
mcpServers := []any{}
if len(tools) > 0 {
mcpServers = append(mcpServers, map[string]any{
"name": "magpie",
"command": exe,
"args": []string{"claude-mcp-helper", callback, toolsPath},
"env": []any{},
})
}
res, err := conn.call(shake, "session/new", map[string]any{"cwd": ws, "mcpServers": mcpServers})
if err != nil {
return fail(fmt.Errorf("devin acp session/new: %w", err))
}
var sess struct {
SessionID string `json:"sessionId"`
}
if json.Unmarshal(res, &sess) != nil || sess.SessionID == "" {
return fail(errors.New("devin acp session/new: no session id"))
}
// bypass approves the magpie tools without a prompt; the home's deny
// rules still hold, so nothing of devin's own runs. A session that
// knows no bypass keeps its default mode and the allow rule instead.
_, _ = conn.call(shake, "session/set_mode", map[string]any{"sessionId": sess.SessionID, "modeId": "bypass"})
prompt, err := renderDevinPrompt(req, len(tools) > 0)
if err != nil {
return fail(err)
}
_, reply, err := conn.send("session/prompt", map[string]any{"sessionId": sess.SessionID, "prompt": prompt})
if err != nil {
return fail(err)
}
go func() {
defer func() {
run.endSegment()
time.AfterFunc(2*time.Second, run.abort)
}()
for nudges := 0; ; nudges++ {
res, err := conn.await(context.Background(), reply)
if err != nil {
run.emit(Event{Kind: KError, Text: "devin: " + err.Error()})
return
}
var done struct {
StopReason string `json:"stopReason"`
Usage struct {
Input int `json:"inputTokens"`
Output int `json:"outputTokens"`
CacheRead int `json:"cachedReadTokens"`
} `json:"usage"`
}
_ = json.Unmarshal(res, &done)
run.emit(Event{Kind: KUsage, Usage: Usage{Input: done.Usage.Input, Output: done.Usage.Output, CacheRead: done.Usage.CacheRead}})
// Devin ends its turn as soon as one of its own tools is
// refused (agent_stopped, tool_rejected) — reaching for its grep
// or shell midway would leave the caller with half an answer
// and no error, so the model is told to go on with the magpie
// tools instead, a few times at most.
if conn.rejected.Swap(false) && done.StopReason == "end_turn" && nudges < devinNudges {
_, reply, err = conn.send("session/prompt", map[string]any{"sessionId": sess.SessionID,
"prompt": []map[string]any{{"type": "text", "text": devinNudge}}})
if err == nil {
continue
}
}
run.emit(Event{Kind: KStop, Stop: stopFromACP(done.StopReason)})
return
}
}()
return run, segment, nil
}
// devinNudge is what a turn Devin ended on a refused tool of its own goes
// on with, at most devinNudges times.
const devinNudge = "<external_system_instructions>\nThat tool is one of Devin's own, which are turned off here, so it could not run. Carry on with the task where you left off, using only the magpie tools — call them directly by name, without listing them or reading any file to look them up.\n</external_system_instructions>"
const devinNudges = 3
// errACPEnded is what waits on an ACP agent get when its process ends or
// its stream breaks before answering.
var errACPEnded = errors.New("ended without an answer")
func stopFromACP(s string) string {
switch s {
case "max_tokens", "max_turn_requests":
return "length"
case "refusal":
return "filter"
}
return "stop"
}
// devinConn is the JSON-RPC side of a devin acp process: calls out over
// stdin, and from stdout — responses, session/update notifications, and the
// odd request devin asks of its client (permission prompts, which are
// declined, and anything else, which is unsupported).
type devinConn struct {
stdin io.Writer
run *subscriptionRun
wmu sync.Mutex
seq atomic.Int64
mu sync.Mutex
pending map[int64]chan devinReply
// rejected is set when devin stops a turn because one of its own
// tools was refused
rejected atomic.Bool
}
type devinReply struct {
result json.RawMessage
err error
}
type devinRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
// Error is the message, and the data with it when that says more, as an
// agent may put the reason there under a bare "Internal error".
func (e *devinRPCError) Error() string {
var data string
if json.Unmarshal(e.Data, &data) != nil {
data = ""
}
data = strings.TrimSpace(data)
if data == "" || data == e.Message {
return e.Message
}
return e.Message + ": " + data
}
func (c *devinConn) send(method string, params any) (int64, <-chan devinReply, error) {
id := c.seq.Add(1)
b, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})
if err != nil {
return 0, nil, err
}
ch := make(chan devinReply, 1)
c.mu.Lock()
c.pending[id] = ch
c.mu.Unlock()
c.wmu.Lock()
_, err = c.stdin.Write(append(b, '\n'))
c.wmu.Unlock()
if err != nil {
c.mu.Lock()
delete(c.pending, id)
c.mu.Unlock()
return 0, nil, err
}
return id, ch, nil
}
func (c *devinConn) await(ctx context.Context, ch <-chan devinReply) (json.RawMessage, error) {
select {
case r := <-ch:
return r.result, r.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (c *devinConn) call(ctx context.Context, method string, params any) (json.RawMessage, error) {
_, ch, err := c.send(method, params)
if err != nil {
return nil, err
}
return c.await(ctx, ch)
}
func (c *devinConn) answer(id json.RawMessage, result any) {
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(id), "result": result})
c.wmu.Lock()
_, _ = c.stdin.Write(append(b, '\n'))
c.wmu.Unlock()
}
func (c *devinConn) refuse(id json.RawMessage, code int, msg string) {
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": json.RawMessage(id),
"error": map[string]any{"code": code, "message": msg}})
c.wmu.Lock()
_, _ = c.stdin.Write(append(b, '\n'))
c.wmu.Unlock()
}
func (c *devinConn) read(rd io.Reader) {
s := bufio.NewScanner(rd)
s.Buffer(make([]byte, 64<<10), 64<<20)
for s.Scan() {
var msg struct {
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
Result json.RawMessage `json:"result"`
Error *devinRPCError `json:"error"`
}
if json.Unmarshal(s.Bytes(), &msg) != nil {
continue
}
switch {
case msg.Method != "" && len(msg.ID) > 0:
// a request devin asks of its client: permission prompts are
// declined, the rest (fs, terminal, …) unimplemented
if msg.Method == "session/request_permission" {
c.answer(msg.ID, map[string]any{"outcome": map[string]any{"outcome": "cancelled"}})
} else {
c.refuse(msg.ID, -32601, "magpie does not implement "+msg.Method)
}
case msg.Method == "_cognition.ai/agent_stopped":
var p struct {
Cause string `json:"cause"`
}
if json.Unmarshal(msg.Params, &p) == nil && p.Cause == "tool_rejected" {
c.rejected.Store(true)
}
case msg.Method == "session/update":
var p struct {
Update struct {
Kind string `json:"sessionUpdate"`
Content struct {
Text string `json:"text"`
} `json:"content"`
Usage struct {
Input int `json:"inputTokens"`
Output int `json:"outputTokens"`
CacheRead int `json:"cachedReadTokens"`
} `json:"usage"`
} `json:"update"`
}
if json.Unmarshal(msg.Params, &p) != nil {
continue
}
switch p.Update.Kind {
case "agent_message_chunk":
if p.Update.Content.Text != "" {
c.run.emit(Event{Kind: KText, Text: p.Update.Content.Text})
}
case "agent_thought_chunk":
if p.Update.Content.Text != "" {
c.run.emit(Event{Kind: KThink, Text: p.Update.Content.Text})
}
case "usage":
u := p.Update.Usage
if u.Input+u.Output+u.CacheRead > 0 {
c.run.emit(Event{Kind: KUsage, Usage: Usage{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead}})
}
}
case len(msg.ID) > 0:
var rid int64
if json.Unmarshal(msg.ID, &rid) != nil {
continue
}
c.mu.Lock()
ch := c.pending[rid]
delete(c.pending, rid)
c.mu.Unlock()
if ch != nil {
if msg.Error != nil {
ch <- devinReply{err: msg.Error}
} else {
ch <- devinReply{result: msg.Result}
}
}
}
}
// the process ended or its stream broke: free whatever waits
err := s.Err()
if err == nil {
err = errACPEnded
}
c.mu.Lock()
pending := c.pending
c.pending = map[int64]chan devinReply{}
c.mu.Unlock()
for _, ch := range pending {
ch <- devinReply{err: err}
}
}
// devinHome is the home devin runs in: magpie's, kept between runs so its
// caches are, with the user's sign-in linked into it and a config that
// leaves only the magpie server's tools.
func devinHome() (string, error) {
base, err := os.UserCacheDir()
if err != nil {
base = os.TempDir()
}
home := filepath.Join(base, "magpie", "devin-home")
var cfgDir, link, src string
if runtime.GOOS == "windows" {
app := filepath.Join(home, "AppData", "Roaming")
cfgDir = filepath.Join(app, "devin")
link = filepath.Join(app, "devin", "credentials.toml")
src = provider.DevinCredentialsPath()
} else {
cfgDir = filepath.Join(home, ".config", "devin")
link = filepath.Join(home, ".local", "share", "devin", "credentials.toml")
src = provider.DevinCredentialsPath()
}
if err := os.MkdirAll(cfgDir, 0o700); err != nil {
return "", err
}
if err := os.MkdirAll(filepath.Dir(link), 0o700); err != nil {
return "", err
}
if _, err := os.Stat(src); err != nil {
return "", errors.New("Devin is not signed in; run `devin auth login`")
}
// The sign-in reaches the home through a link where the OS grants one —
// Windows gives symlinks only to developers and admins — and through a
// copy, refreshed when the source is newer, where it doesn't. Only
// freshness from the source matters: the credential is a session token
// (no exp claim, no refresh token), and devin writes the file at login
// and never during a session — observed: inode, mtime and hash unchanged
// across a run — so nothing inside the home flows back to it.
fresh := false
if cur, err := os.Readlink(link); err == nil {
fresh = cur == src // a link sees the live file
} else if lst, err := os.Lstat(link); err == nil && lst.Mode().IsRegular() {
if sst, err := os.Stat(src); err == nil {
fresh = !lst.ModTime().Before(sst.ModTime())
}
}
if !fresh {
_ = os.Remove(link)
if err := os.Symlink(src, link); err != nil {
b, err := os.ReadFile(src)
if err != nil {
return "", err
}
if err := os.WriteFile(link, b, 0o600); err != nil {
return "", err
}
}
}
// Only the caller's tools: nothing of devin's own (files, shell, web,
// other MCP servers or the settings it borrows from other agents). The
// deny names are the built-in tools' own (read/edit/grep/glob/exec), the
// scoped rules cover the same ground wherever a name doesn't reach —
// Read(**) and Write(**) are relative to the working directory, so the
// /** forms are what cover absolute paths. mcp__* is not denied — it
// would beat the magpie allow.
cfg, _ := json.Marshal(map[string]any{
"version": 1,
"permissions": map[string]any{
"deny": []string{"read", "edit", "write", "exec", "grep", "glob", "fetch",
"Read(/**)", "Read(**)", "Write(/**)", "Write(**)", "Fetch(*)", "Fetch(**)"},
"allow": []string{"mcp__magpie__*"},
},
"read_config_from": map[string]bool{"agents_standard": false, "claude": false, "codex": false, "copilot": false, "cursor": false, "opencode": false, "windsurf": false, "zed": false},
"subagents_enabled": false,
"auto_update": false,
"notify": "never",
})
if err := os.WriteFile(filepath.Join(cfgDir, "config.json"), cfg, 0o600); err != nil {
return "", err
}
return home, nil
}
func devinEnv(env []string, home string) []string {
blocked := map[string]bool{"HOME": true, "USERPROFILE": true, "APPDATA": true, "LOCALAPPDATA": true,
"XDG_CONFIG_HOME": true, "XDG_DATA_HOME": true, "XDG_CACHE_HOME": true, "NO_OPEN_BROWSER": true}
out := make([]string, 0, len(env)+6)
for _, e := range env {
k, _, _ := strings.Cut(e, "=")
up := strings.ToUpper(k)
if blocked[up] || strings.HasPrefix(up, "DEVIN_") || strings.HasPrefix(up, "WINDSURF_") ||
strings.HasPrefix(up, "CODEIUM_") || strings.HasPrefix(up, "MAGPIE_MCP_") {
continue
}
out = append(out, e)
}
out = append(out, "HOME="+home)
if runtime.GOOS == "windows" {
out = append(out, "USERPROFILE="+home,
"APPDATA="+filepath.Join(home, "AppData", "Roaming"),
"LOCALAPPDATA="+filepath.Join(home, "AppData", "Local"))
} else {
out = append(out,
"XDG_CONFIG_HOME="+filepath.Join(home, ".config"),
"XDG_DATA_HOME="+filepath.Join(home, ".local", "share"),
"XDG_CACHE_HOME="+filepath.Join(home, ".cache"))
}
return out
}
// renderDevinPrompt is the conversation as ACP content blocks: the caller's
// tools are named as they come over MCP.
func renderDevinPrompt(req *Request, tools bool) ([]map[string]any, error) {
blocks, err := renderClaudePrompt(req)
if err != nil {
return nil, err
}
out := make([]map[string]any, 0, len(blocks)+1)
if tools {
out = append(out, map[string]any{"type": "text", "text": "<external_system_instructions>\nThe only tools in this session are those of the magpie MCP server; Devin's own tools (shell, reading, editing and searching files, the web) are turned off, and this workspace is empty. They are already yours to call directly by name, so there is no need to list them, and never try to read a file to look one up. Call a magpie tool whenever the conversation needs one.\n</external_system_instructions>"})
}
for _, b := range blocks {
switch b["type"] {
case "image":
if src, ok := b["source"].(map[string]any); ok {
if src["type"] == "base64" {
out = append(out, map[string]any{"type": "image", "data": src["data"], "mimeType": src["media_type"]})
} else if u, ok := src["url"].(string); ok {
out = append(out, map[string]any{"type": "resource_link", "uri": u, "name": "image"})
}
}
default:
out = append(out, b)
}
}
return out, nil
}
-187
View File
@@ -1,187 +0,0 @@
package gateway
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"testing"
"time"
)
func TestDevinEnvRunsInMagpiesHome(t *testing.T) {
got := strings.Join(devinEnv([]string{
"PATH=/bin", "HOME=/Users/me", "XDG_CONFIG_HOME=/x", "XDG_DATA_HOME=/y",
"DEVIN_API_KEY=k", "DEVIN_MODEL=x", "WINDSURF_API_KEY=w", "KEEP=1",
}, "/cache/home"), "\n")
for _, bad := range []string{"HOME=/Users/me", "XDG_CONFIG_HOME=/x", "XDG_DATA_HOME=/y", "DEVIN_API_KEY=", "DEVIN_MODEL=", "WINDSURF_API_KEY="} {
if strings.Contains(got, bad) {
t.Fatalf("kept %s in %q", bad, got)
}
}
for _, want := range []string{"PATH=/bin", "KEEP=1", "HOME=/cache/home", "XDG_CONFIG_HOME=/cache/home/.config"} {
if !strings.Contains(got, want) {
t.Fatalf("missing %s in %q", want, got)
}
}
}
// devinPair wires a conn's stdin/stdout to pipes the test speaks ACP on. The
// conn's stdin is a kernel pipe: like a real process's, its writes don't wait
// for the test to read them.
type devinPair struct {
conn *devinConn
toConn io.WriteCloser // what the test writes, the conn reads
from *bufio.Scanner // what the conn writes, the way devin would see it
fromR *os.File
run *subscriptionRun
seg chan Event
}
func newDevinPair(t *testing.T) devinPair {
t.Helper()
toConnR, toConnW := io.Pipe() // test writes, conn reads
fromR, fromW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { fromR.Close(); fromW.Close() })
run := &subscriptionRun{pending: map[string]chan mcpToolResult{}}
from := bufio.NewScanner(fromR)
from.Buffer(make([]byte, 64<<10), 4<<20)
p := devinPair{conn: &devinConn{stdin: fromW, pending: map[int64]chan devinReply{}, run: run},
toConn: toConnW, from: from, fromR: fromR, run: run, seg: run.attach()}
go p.conn.read(toConnR)
return p
}
func (p devinPair) write(t *testing.T, line string) {
t.Helper()
if _, err := fmt.Fprintln(p.toConn, line); err != nil {
t.Fatal(err)
}
}
// next returns the conn's next outbound JSON-RPC message.
func (p devinPair) next(t *testing.T) map[string]any {
t.Helper()
_ = p.fromR.SetReadDeadline(time.Now().Add(5 * time.Second))
if !p.from.Scan() {
t.Fatal("conn went quiet")
}
_ = p.fromR.SetReadDeadline(time.Time{})
var m map[string]any
if json.Unmarshal(p.from.Bytes(), &m) != nil {
t.Fatalf("not json: %s", p.from.Text())
}
return m
}
func TestDevinConnCallsAndAnswers(t *testing.T) {
p := newDevinPair(t)
id, reply, err := p.conn.send("initialize", map[string]any{"protocolVersion": 1})
if err != nil {
t.Fatal(err)
}
sent := p.next(t)
if sent["method"] != "initialize" || sent["id"] != float64(id) {
t.Fatalf("sent %v", sent)
}
// a response resolves the call
p.write(t, fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":1}}`, id))
res, err := p.conn.await(context.Background(), reply)
if err != nil || !strings.Contains(string(res), "protocolVersion") {
t.Fatalf("await: %v %s", err, res)
}
// a permission request is declined on its own
p.write(t, `{"jsonrpc":"2.0","id":77,"method":"session/request_permission","params":{}}`)
ans := p.next(t)
if ans["id"] != float64(77) {
t.Fatalf("answer %v", ans)
}
outcome, _ := ans["result"].(map[string]any)["outcome"].(map[string]any)
if outcome["outcome"] != "cancelled" {
t.Fatalf("permission answered %v", ans)
}
// a client-capability request is refused as unimplemented
p.write(t, `{"jsonrpc":"2.0","id":78,"method":"fs/read_text_file","params":{"path":"/x"}}`)
ans = p.next(t)
if e, _ := ans["error"].(map[string]any); e == nil || e["code"] != float64(-32601) {
t.Fatalf("fs answered %v", ans)
}
// streamed text lands as events
p.write(t, `{"jsonrpc":"2.0","method":"session/update","params":{"update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"hello"}}}}`)
p.write(t, `{"jsonrpc":"2.0","method":"session/update","params":{"update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hm"}}}}`)
var kinds []EventKind
for len(kinds) < 2 {
select {
case ev := <-p.seg:
kinds = append(kinds, ev.Kind)
case <-time.After(2 * time.Second):
t.Fatalf("events: %v", kinds)
}
}
if kinds[0] != KText || kinds[1] != KThink {
t.Fatalf("events: %v", kinds)
}
// a turn stopped on a refused tool of devin's own is noted, once
p.write(t, `{"jsonrpc":"2.0","method":"_cognition.ai/agent_stopped","params":{"cause":"completed"}}`)
p.write(t, `{"jsonrpc":"2.0","method":"_cognition.ai/agent_stopped","params":{"cause":"tool_rejected"}}`)
for deadline := time.Now().Add(2 * time.Second); !p.conn.rejected.Load(); time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("tool_rejected went unnoticed")
}
}
if !p.conn.rejected.Swap(false) || p.conn.rejected.Load() {
t.Fatal("rejected is not taken once")
}
// the stream ending fails a call still open
_, reply2, _ := p.conn.send("session/prompt", map[string]any{})
p.toConn.Close()
if _, err := p.conn.await(context.Background(), reply2); err == nil {
t.Fatal("an open call survived the end of the stream")
}
}
func TestStopFromACP(t *testing.T) {
for in, want := range map[string]string{
"end_turn": "stop", "max_tokens": "length", "max_turn_requests": "length", "refusal": "filter", "": "stop",
} {
if got := stopFromACP(in); got != want {
t.Fatalf("%q → %q", in, got)
}
}
}
func TestRenderDevinPromptMapsBlocks(t *testing.T) {
blocks, err := renderDevinPrompt(&Request{
Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "look"}, {Kind: Image, MediaType: "image/png", Data: "AA=="}, {Kind: Image, URL: "https://x/y.png"}}},
},
}, true)
if err != nil {
t.Fatal(err)
}
var kinds []string
for _, b := range blocks {
kinds = append(kinds, b["type"].(string))
}
if kinds[0] != "text" || !strings.Contains(blocks[0]["text"].(string), "external_system_instructions") {
t.Fatalf("preamble: %v", blocks)
}
var img, link map[string]any
for _, b := range blocks {
if b["type"] == "image" {
img = b
}
if b["type"] == "resource_link" {
link = b
}
}
if img["data"] != "AA==" || img["mimeType"] != "image/png" || link["uri"] != "https://x/y.png" {
t.Fatalf("blocks: %v", blocks)
}
}
+285
View File
@@ -0,0 +1,285 @@
package gateway
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/binary"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// devinFrame is one frame of a Connect stream, gzipped when zip.
func devinFrame(flag byte, msg []byte, zip bool) []byte {
if zip {
var b bytes.Buffer
zw := gzip.NewWriter(&b)
zw.Write(msg)
zw.Close()
msg, flag = b.Bytes(), flag|1
}
out := []byte{flag, 0, 0, 0, 0}
binary.BigEndian.PutUint32(out[1:], uint32(len(msg)))
return append(out, msg...)
}
func devinEvents(t *testing.T, frames ...[]byte) []Event {
t.Helper()
br := bufio.NewReader(bytes.NewReader(bytes.Join(frames, nil)))
first, err := readConnectFrame(br)
if err != nil {
t.Fatal(err)
}
out := make(chan Event, 256)
decodeDevin(context.Background(), first, br, out, "swe-2")
var evs []Event
for ev := range out {
evs = append(evs, ev)
}
return evs
}
func TestDevinDecodesTextThinkingAndCalls(t *testing.T) {
evs := devinEvents(t,
devinFrame(0, pb{}.str(1, "bot-1").str(9, "Hmm."), false),
devinFrame(0, pb{}.str(3, "Let me ").varint(4, 1), true),
devinFrame(0, pb{}.str(3, "look."), false),
devinFrame(0, pb{}.bytes(6, pb{}.str(1, "toolu_1").str(2, "read")), false),
devinFrame(0, pb{}.bytes(6, pb{}.str(3, `{"pa`)), false),
devinFrame(0, pb{}.bytes(6, pb{}.str(3, `th":"a"}`)), false),
devinFrame(0, pb{}.str(10, "sealed.v1xyz").varint(5, 10), false),
devinFrame(0, pb{}.bytes(7, pb{}.varint(2, 120).varint(3, 30).varint(5, 7).varint(6, 30).str(7, "id")), false),
devinFrame(2, []byte("{}"), false),
)
if got, want := said(evs), `|think:Hmm.|text:Let me look.|call:toolu_1/read|args:{"path":"a"}|stop:tool`; got != want {
t.Fatalf("got %s\nwant %s", got, want)
}
var u Usage
for _, ev := range evs {
if ev.Kind == KUsage {
u = ev.Usage
}
}
if u.Input != 120 || u.Output != 30 || u.CacheRead != 7 {
t.Fatalf("usage = %+v", u)
}
}
func TestDevinStopsAndFails(t *testing.T) {
evs := devinEvents(t, devinFrame(0, pb{}.str(3, "abcd").varint(5, 3), false))
if got := said(evs); got != "|text:abcd|stop:length" {
t.Fatal(got)
}
evs = devinEvents(t,
devinFrame(0, pb{}.str(3, "ab"), false),
devinFrame(2, []byte(`{"error":{"code":"internal","message":"boom"}}`), false))
if got := said(evs); got != "|text:ab|error:boom" {
t.Fatal(got)
}
}
// devinDecoded is a GetChatMessage request, read back.
type devinDecoded struct {
system string
model string
msgs [][]pbField
tools []string
max uint64
}
func decodeDevinRequest(t *testing.T, b []byte) devinDecoded {
t.Helper()
var d devinDecoded
for _, f := range pbFields(b) {
switch f.num {
case 2:
d.system = string(f.data)
case 21:
d.model = string(f.data)
case 3:
d.msgs = append(d.msgs, pbFields(f.data))
case 10:
d.tools = append(d.tools, string(pbFields(f.data)[0].data))
case 8:
for _, g := range pbFields(f.data) {
if g.num == 2 {
d.max = g.n
}
}
}
}
return d
}
// devinSummary is a message as role:text[extras].
func devinSummary(m []pbField) string {
var role uint64
var text, extra string
for _, f := range m {
switch f.num {
case 2:
role = f.n
case 3:
text = string(f.data)
case 6:
fs := pbFields(f.data)
extra += " call " + string(fs[0].data) + "/" + string(fs[1].data) + " " + string(fs[2].data)
case 7:
extra += " for " + string(f.data)
case 10:
extra += " image " + string(pbFields(f.data)[1].data)
case 12:
extra += " signed"
}
}
return string(rune('0'+role)) + ":" + text + extra
}
func TestBuildDevin(t *testing.T) {
r := &Request{
System: "Be brief.",
Tools: []Tool{{Name: "read", Description: "Read a file", Schema: json.RawMessage(`{"type":"object"}`)}},
Messages: []Message{
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "orphan", Text: "x"}, {Kind: Text, Text: "look at a"}}},
{Role: "assistant", Parts: []Part{
{Kind: Thinking, Text: "ok", Signature: "sealed.v1abc"},
{Kind: Thinking, Text: "other", Signature: "EqQBCkY"},
{Kind: Text, Text: "Reading."},
{Kind: ToolCall, ID: "c1", Name: "read", Args: json.RawMessage(`{"p":"a"}`)},
{Kind: ToolCall, ID: "c2", Name: "gone", Args: nil},
}},
{Role: "user", Parts: []Part{
{Kind: ToolResult, CallID: "c1", Text: "A", IsError: true},
{Kind: ToolResult, CallID: "c1", Text: "again"},
{Kind: Image, MediaType: "image/jpeg", Data: "AAAA"},
{Kind: Text, Text: "and this"},
}},
},
}
d := decodeDevinRequest(t, buildDevin(r, "swe-2-high", "k"))
if d.system != "" || d.model != "swe-2-high" || d.max != 128000 {
t.Fatalf("%+v", d)
}
var got []string
for _, m := range d.msgs {
got = append(got, devinSummary(m))
}
want := []string{
"1:Be brief.\n\nlook at a",
`2:Reading. call c1/read {"p":"a"} call c2/gone {} signed`,
"4:Error: A for c1",
"4:" + devinNoResult + " for c2",
"1:and this image image/jpeg",
}
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
if strings.Join(d.tools, ",") != "read,gone" {
t.Fatalf("tools = %v", d.tools)
}
// a conversation ending on a reply goes on with a nudge
d = decodeDevinRequest(t, buildDevin(&Request{MaxTokens: 50, Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
{Role: "assistant", Parts: []Part{{Kind: Text, Text: "yo"}}},
}}, "m", "k"))
if n := len(d.msgs); n != 3 || devinSummary(d.msgs[2]) != "1:Please proceed with the task." || d.max != 50 {
t.Fatalf("%d %+v", n, d)
}
}
func devinUpstream(t *testing.T, reply []byte) func() {
t.Helper()
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
if r.URL.Path != "/exa.api_server_pb.ApiServerService/GetChatMessage" || r.Header.Get("Authorization") != "Basic devin-session-token$k" ||
r.Header.Get("Content-Type") != "application/connect+proto" || len(body) < 5 {
http.Error(w, `{"code":"unauthenticated","message":"no"}`, 401)
return
}
if m := decodeDevinRequest(t, body[5:]).model; m != "swe-2-high" {
t.Errorf("model = %q", m)
}
w.Header().Set("Content-Type", "application/connect+proto")
w.Write(reply)
}))
auth, variant := devinAuth, devinVariant
devinAuth = func() (string, string, error) { return "devin-session-token$k", up.URL, nil }
devinVariant = func(ctx context.Context, model, effort string) string { return model + "-high" }
return func() { up.Close(); devinAuth, devinVariant = auth, variant }
}
func serveDevinOnce(t *testing.T, from provider.Protocol, body string) *httptest.ResponseRecorder {
t.Helper()
s := New()
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/", strings.NewReader(body))
var u Usage
s.serveDevin(w, r, from, "swe-2", []byte(body), &u)
return w
}
func TestServeDevin(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
done := devinUpstream(t, bytes.Join([][]byte{
devinFrame(0, pb{}.str(3, "Hello"), false),
devinFrame(0, pb{}.bytes(6, pb{}.str(1, "t1").str(2, "read").str(3, `{"p":1}`)), false),
devinFrame(0, pb{}.varint(5, 10).bytes(7, pb{}.varint(2, 9).varint(3, 3)), false),
devinFrame(2, []byte("{}"), false),
}, nil))
defer done()
w := serveDevinOnce(t, provider.Anthropic, `{"model":"x","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`)
var msg struct {
Content []struct {
Text string `json:"text"`
ID string `json:"id"`
Input json.RawMessage `json:"input"`
} `json:"content"`
StopReason string `json:"stop_reason"`
Usage struct {
In int `json:"input_tokens"`
Out int `json:"output_tokens"`
} `json:"usage"`
}
json.Unmarshal(w.Body.Bytes(), &msg)
if w.Code != 200 || len(msg.Content) != 2 || msg.Content[0].Text != "Hello" || msg.Content[1].ID != "t1" || string(msg.Content[1].Input) != `{"p":1}` ||
msg.StopReason != "tool_use" || msg.Usage.In != 9 || msg.Usage.Out != 3 {
t.Fatalf("%d %s", w.Code, w.Body)
}
w = serveDevinOnce(t, provider.Chat, `{"model":"x","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
out := w.Body.String()
if w.Code != 200 || !strings.Contains(out, `"content":"Hello"`) || !strings.Contains(out, `"finish_reason":"tool_calls"`) {
t.Fatalf("%d %s", w.Code, out)
}
}
// An error at the stream's head is answered with its own status.
func TestServeDevinFailures(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
for _, c := range []struct {
end string
status int
}{
{`{"error":{"code":"resource_exhausted","message":"out of credits"}}`, 429},
{`{"error":{"code":"permission_denied","message":"internal error"}}`, 502},
{`{"error":{"code":"unauthenticated","message":"expired"}}`, 401},
} {
done := devinUpstream(t, devinFrame(2, []byte(c.end), false))
w := serveDevinOnce(t, provider.Anthropic, `{"model":"x","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`)
done()
if w.Code != c.status {
t.Errorf("%s: %d %s", c.end, w.Code, w.Body)
}
}
}
+2 -5
View File
@@ -794,13 +794,10 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
}
return s.serveSubscription(w, r, from, "Grok", model, body, &call.Usage, start)
}
// and Devin's, which the CLI serves over ACP
// Devin's through the API its CLI talks to, with the CLI's sign-in
if p.Account != nil && p.Account.Agent == "devin" {
call.To = from
start := func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {
return s.subscription.startDevin(ctx, req, model)
}
return s.serveSubscription(w, r, from, "Devin", model, body, &call.Usage, start)
return s.serveDevin(w, r, from, model, body, &call.Usage)
}
// Kiro's is served through its own API, with kiro-cli's or the Kiro
// IDE's sign-in, or a Kiro API key saved on the provider
+67 -6
View File
@@ -1,10 +1,9 @@
package provider
// A Devin subscription is used the way a Cursor one is: through the vendor's
// own agent. Devin has no endpoint a key can be sent to, so magpie runs the
// genuine devin CLI (gateway/devin_subscription.go drives `devin acp`) with
// the account it is signed in to; here is only who that account is, the
// models it offers, and the sign-in, which is `devin auth login`.
// A Devin subscription is served through the API the devin CLI talks to
// (gateway/devin.go), with the key the CLI signed in with; here is who that
// account is, the models it offers, and the sign-in, which is `devin auth
// login`'s.
import (
"context"
@@ -15,10 +14,13 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"time"
toml "github.com/pelletier/go-toml/v2"
"github.com/yetone/magpie/internal/catalog"
)
@@ -171,10 +173,14 @@ type DevinFamily struct {
}
// devinModelsFlatten is the family list as a flat catalog: the family's
// follow-newest id, then each of its variants.
// follow-newest id, then each of its variants. Adaptive and Fusion, which
// route between models inside Devin's own agent, aren't served by the API.
func devinModelsFlatten(families []DevinFamily) []catalog.Model {
var out []catalog.Model
for _, f := range families {
if id := strings.ToLower(f.UID); id == "adaptive" || id == "fusion" {
continue
}
out = append(out, catalog.Model{ID: f.UID, Name: f.Label, Provider: "devin"})
out = append(out, f.Models...)
}
@@ -346,3 +352,58 @@ func devinCredentials(key, server, webapp, api string) []byte {
func tomlString(s string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"`
}
// DevinAuth is the key the CLI signed in with and the server its API is
// on, read from credentials.toml; WINDSURF_API_SERVER_URL moves the server,
// as it does the CLI's.
func DevinAuth() (key, server string, err error) {
b, err := os.ReadFile(DevinCredentialsPath())
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return "", "", errors.New("Devin isn't signed in; sign in from magpie's Providers page or run `devin auth login`")
}
return "", "", err
}
var c struct {
Key string `toml:"windsurf_api_key"`
Server string `toml:"api_server_url"`
}
if err := toml.Unmarshal(b, &c); err != nil {
return "", "", fmt.Errorf("%s: %w", DevinCredentialsPath(), err)
}
if c.Key == "" {
return "", "", errors.New("Devin isn't signed in: " + DevinCredentialsPath() + " has no key")
}
server = strings.TrimRight(c.Server, "/")
if v := os.Getenv("WINDSURF_API_SERVER_URL"); v != "" {
server = strings.TrimRight(v, "/")
}
if server == "" {
server = devinAPIServer
}
return c.Key, server, nil
}
// DevinVariant is the model to ask Devin's API for: a family's name
// follows its newest model, which the API takes only as one of its
// variants — the one at the effort asked for, else the family's default.
func DevinVariant(ctx context.Context, model, effort string) string {
families, err := DevinFamilies(ctx)
if err != nil {
return model
}
for _, f := range families {
if f.UID != model && !slices.Contains(f.Aliases, model) || len(f.Models) == 0 {
continue
}
if effort != "" {
for _, m := range f.Models {
if strings.HasSuffix(strings.ToLower(m.ID), "-"+effort) || strings.HasSuffix(m.ID, "_"+strings.ToUpper(effort)) {
return m.ID
}
}
}
return f.Models[0].ID
}
return model
}