diff --git a/README.md b/README.md index 27c89793d..1c7288f81 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ and there is a terminal version (`magpie tui`) and a plain CLI. | DeepSeek Harness (dsh) | `~/.dsh/config.yaml` (`$DSH_HOME`) | model | | Command Code | `~/.commandcode/settings.json` (+ `providers.json`) | model | | omp (oh-my-pi) | `~/.omp/agent/config.yml` (+ `models.yml`) | model | +| Devin | `~/.config/devin/config.json` (`%APPDATA%\devin\config.json` on Windows) | model | Provider-scoped agents (OpenCode, Pi, Goose, Crush, omp) take `provider/model`. Only agents that are installed or configured are shown. @@ -112,11 +113,12 @@ be overridden the same way. An agent you have signed in to is a subscription with models behind it, so magpie offers it as a provider too. Claude Code (an OAuth login in the macOS Keychain or `~/.claude/.credentials.json`), Codex (a ChatGPT login in -`~/.codex/auth.json`) and Copilot (a GitHub login in -`~/.config/github-copilot/apps.json`) appear in `magpie providers` and in the -Providers tab as *signed in as …*, with their models spelled -`claude/claude-sonnet-5`, `codex/gpt-5.5` or `copilot/claude-sonnet-4.5` in -every other agent's picker. magpie reads the agent's own credentials each +`~/.codex/auth.json`), Copilot (a GitHub login in +`~/.config/github-copilot/apps.json`) and Devin (`devin auth login`, kept in +`~/.local/share/devin/credentials.toml`) appear in `magpie providers` and in +the Providers tab as *signed in as …*, with their models spelled +`claude/claude-sonnet-5`, `codex/gpt-5.5`, `copilot/claude-sonnet-4.5` or +`devin/swe-2-max` in every other agent's picker. magpie reads the agent's own credentials each time, refreshes tokens the way the agent does — writing a rotated token back where the agent will find it — and stores nothing but your model picks; sign out of the agent and the provider is gone. The model list is @@ -132,7 +134,12 @@ bridged into that live turn over MCP, and tool results resume the same Claude 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. A Gemini CLI Google login is planned. +to be installed and signed in. +Cursor, Grok 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. A Gemini CLI Google login is +planned. ### Connecting anything else diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 109d1ff2d..69ef47ea6 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -61,6 +61,7 @@ func All() []*Agent { dsh(home), commandCode(home), omp(home), + devin(home, cfg), } } diff --git a/internal/agent/devin.go b/internal/agent/devin.go new file mode 100644 index 000000000..25a5f0a8e --- /dev/null +++ b/internal/agent/devin.go @@ -0,0 +1,80 @@ +package agent + +// Devin keeps its settings in ~/.config/devin/config.json (%APPDATA%\devin on +// Windows), the model under agent.model. Devin has no endpoint magpie can +// stand in for — its models are its own — so the options are the families +// and variants `devin models list --format json` reports, not the magpie +// catalog. A family id (swe-2, claude-opus-5-5) follows the family's newest; +// a variant id (swe-2-max) pins one. + +import ( + "context" + "os" + "path/filepath" + "runtime" + + "github.com/yetone/magpie/internal/provider" +) + +func devin(home, cfg string) *Agent { + dir := filepath.Join(cfg, "devin") + if runtime.GOOS == "windows" { + if app := os.Getenv("APPDATA"); app != "" { + dir = filepath.Join(app, "devin") + } + } + path := filepath.Join(dir, "config.json") + return &Agent{ + ID: "devin", Name: "Devin", Icon: "devin", + Bin: "devin", Dir: dir, Path: path, + Notice: func() string { + if Running(`(^|/)devin( |$)`) { + return "Devin reads its model at start-up — restart open Devin sessions to use this." + } + return "" + }, + Fields: []Field{{ + Key: "model", Label: "model", + Get: jsonGet(path, "agent.model"), + Set: jsonSet(path, "agent.model"), + Options: func(cur map[string]string) []Option { + return devinOptions(cur["model"]) + }, + }}, + } +} + +// providerDevinFamilies lists Devin's models; a var so tests can fake it. +var providerDevinFamilies = func(ctx context.Context) ([]provider.DevinFamily, error) { + return provider.DevinFamilies(ctx) +} + +// devinOptions offers the families first (a pick that follows the family's +// newest model), then every variant under its family. They are Devin's own +// models, not borrowed ones, so like every agent's own list they sit flat — +// a group each would only crowd the picker's rail with one icon per family. +func devinOptions(cur string) []Option { + families, err := providerDevinFamilies(context.Background()) + if err != nil { + if cur == "" { + return nil + } + return []Option{{Value: cur}} + } + out := make([]Option, 0, len(families)) + for _, f := range families { + out = append(out, Option{Value: f.UID, Label: f.Label, Note: "the family's newest", Icon: "devin"}) + for _, m := range f.Models { + out = append(out, Option{Value: m.ID, Label: m.Name, Icon: "devin"}) + } + } + if cur != "" { + for _, o := range out { + if o.Value == cur { + return out + } + } + out = append([]Option{{Value: cur, Note: "current"}}, out...) + } + return out +} diff --git a/internal/agent/devin_test.go b/internal/agent/devin_test.go new file mode 100644 index 000000000..3e599ed86 --- /dev/null +++ b/internal/agent/devin_test.go @@ -0,0 +1,78 @@ +package agent + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +func TestDevin(t *testing.T) { + home := t.TempDir() + cfg := filepath.Join(home, ".config") + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", cfg) + + dir := filepath.Join(cfg, "devin") + path := filepath.Join(dir, "config.json") + os.MkdirAll(dir, 0o755) + os.WriteFile(path, []byte("{\n // mine\n \"theme_mode\": \"dark\",\n \"agent\": {\"model\": \"swe-2-max\"}\n}\n"), 0o644) + + a := devin(home, cfg) + if a.Path != path { + t.Fatalf("path: %q", a.Path) + } + f := a.Field("model") + if f.Get() != "swe-2-max" { + t.Fatalf("get: %q", f.Get()) + } + if err := f.Set("claude-opus-5-5-high"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + raw := string(b) + if !strings.Contains(raw, "// mine") || !strings.Contains(raw, `"theme_mode": "dark"`) || + !strings.Contains(raw, `"model": "claude-opus-5-5-high"`) { + t.Fatalf("config:\n%s", raw) + } + if f.Get() != "claude-opus-5-5-high" { + t.Fatalf("get after set: %q", f.Get()) + } + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if f.Get() != "" { + t.Fatalf("get after reset: %q", f.Get()) + } + b, _ = os.ReadFile(path) + if strings.Contains(string(b), `"model"`) || !strings.Contains(string(b), "// mine") { + t.Fatalf("config after reset:\n%s", b) + } +} + +func TestDevinOptionsListFamiliesThenVariants(t *testing.T) { + old := providerDevinFamilies + defer func() { providerDevinFamilies = old }() + providerDevinFamilies = func(context.Context) ([]provider.DevinFamily, error) { + return []provider.DevinFamily{{ + UID: "swe-2", Label: "SWE-2", Aliases: []string{"swe"}, + Models: []catalog.Model{{ID: "swe-2-max", Name: "SWE-2 Max"}, {ID: "swe-2-min", Name: "SWE-2 Min"}}, + }}, nil + } + opts := devinOptions("") + if len(opts) != 3 || opts[0].Value != "swe-2" || opts[1].Value != "swe-2-max" { + t.Fatalf("options: %v", opts) + } + if opts[0].Group != "" || opts[2].Group != "" { + t.Fatalf("devin's own models sit flat, like every agent's own list: %v", opts) + } + // a current value Devin knows but the list predates is still offered + opts = devinOptions("gone-model") + if opts[0].Value != "gone-model" { + t.Fatalf("current missing: %v", opts) + } +} diff --git a/internal/gateway/devin_subscription.go b/internal/gateway/devin_subscription.go new file mode 100644 index 000000000..3f15469a2 --- /dev/null +++ b/internal/gateway/devin_subscription.go @@ -0,0 +1,513 @@ +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" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "time" + + "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 := exec.CommandContext(context.Background(), binary, "acp", "--model", model) + cmd.Dir = ws + cmd.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) + } + id, err := conn.send("session/prompt", map[string]any{"sessionId": sess.SessionID, "prompt": prompt}) + if err != nil { + return fail(err) + } + go func() { + res, err := conn.await(context.Background(), id) + if err != nil { + run.emit(Event{Kind: KError, Text: "devin: " + err.Error()}) + } else { + 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}}) + run.emit(Event{Kind: KStop, Stop: stopFromACP(done.StopReason)}) + } + run.endSegment() + time.AfterFunc(2*time.Second, run.abort) + }() + return run, segment, nil +} + +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 +} + +type devinReply struct { + result json.RawMessage + err error +} + +type devinRPCError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func (e *devinRPCError) Error() string { return e.Message } + +func (c *devinConn) send(method string, params any) (int64, 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, 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, err + } + return id, nil +} + +func (c *devinConn) await(ctx context.Context, id int64) (json.RawMessage, error) { + c.mu.Lock() + ch := c.pending[id] + c.mu.Unlock() + if ch == nil { + return nil, errors.New("no such call") + } + 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) { + id, err := c.send(method, params) + if err != nil { + return nil, err + } + return c.await(ctx, id) +} + +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 == "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 = errors.New("devin ended without an answer") + } + 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": "\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. Call a magpie tool whenever the conversation needs one.\n"}) + } + 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 +} diff --git a/internal/gateway/devin_subscription_test.go b/internal/gateway/devin_subscription_test.go new file mode 100644 index 000000000..480df7350 --- /dev/null +++ b/internal/gateway/devin_subscription_test.go @@ -0,0 +1,176 @@ +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, 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(), id) + 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) + } + // the stream ending fails a call still open + id2, _ := p.conn.send("session/prompt", map[string]any{}) + p.toConn.Close() + if _, err := p.conn.await(context.Background(), id2); 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) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a149f7594..ad45cfc44 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -217,7 +217,7 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { p, model, ok := provider.Resolve(modelOf(body)) // Claude Subscription generations run through the Claude Code binary. Its // OAuth token must not take a direct HTTP side path just for token counting. - if ok && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "cursor" || p.Account.Agent == "grok") { + if ok && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "cursor" || p.Account.Agent == "grok" || p.Account.Agent == "devin") { req, err := parseAnthropic(body) if err != nil { writeError(w, provider.Anthropic, 400, err.Error()) @@ -499,6 +499,14 @@ 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 + 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) + } // a backend that only streams gets a non-streaming request translated // (the provider is always streamed on that path) rather than relayed relay := slices.Contains(s.usable(p, model), from) && (p.Account == nil || !p.Account.Stream || streamOf(body)) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 0b394704d..49bda2a0b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1702,7 +1702,7 @@ const PROTOS = [["chat", "OpenAI", "Chat Completions — most agents"], ["respon // renderEditor: an existing provider (p), a new preset (presetID), or custom. function renderEditor(p, presetID) { const pr = presetID ? providers.presets.find((x) => x.id === presetID) : p?.preset ? providers.presets.find((x) => x.id === p.preset) : null; - const isNew = !p, custom = !pr; + const isNew = !p, custom = !pr && !p?.account; draft = draft || (p ? { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, catalog: p.catalog, key: "", api: p.anthropic && !p.chat ? "anthropic" : "openai", chosen: p.models.filter((m) => m.on).map((m) => m.id), extra: [], headers: headerRows(p.headers), icon: p.icon || "", fallback: [...(p.fallback || [])], balanceURL: p.balanceURL || "", balancePath: p.balancePath || "" } : pr @@ -1716,7 +1716,7 @@ function renderEditor(p, presetID) { h.append(icon(p?.icon || pr?.icon || "generic"), el("b", "", p ? p.name : pr ? pr.name : t("Custom provider"))); if (pr?.note) h.append(el("span", "note", pr.note)); h.append(el("span", "grow")); - const site = pr?.website || (p?.host ? "https://" + p.host : ""); + const site = pr?.website || p?.website || (p?.host ? "https://" + p.host : ""); if (site) { const b = el("button", "link", hostOf(site) + " ↗"); b.onclick = () => api("open", { url: site }); h.append(b); } ed.append(h); } @@ -1774,7 +1774,7 @@ function renderEditor(p, presetID) { } ed.append(...field(t("Models"), renderModels(p), "")); ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p))); - ed.append(...field(t("Endpoints"), renderEndpoints(p, p))); + if (p.chat || p.responses || p.anthropic) ed.append(...field(t("Endpoints"), renderEndpoints(p, p))); const bar = el("div", "bar"); // removing only hides it from magpie; the agent stays signed in const del = el("button", "text danger", t("Remove")); @@ -2395,6 +2395,8 @@ const SUBS = [ { agent: "grok", name: "Grok", icon: "xai", plans: "SuperGrok · X Premium+", own: true }, // signed in with GitHub's device code; the editors' own sign-in stays theirs { agent: "copilot", name: "Copilot", icon: "githubcopilot", plans: "Pro · Pro+ · Business", own: true }, + // devin's credentials.toml keeps one account too + { agent: "devin", name: "Devin", icon: "devin", plans: "Pro · Enterprise", single: true }, ]; const subOf = (agent) => SUBS.find((x) => x.agent === agent); let signing = null; // the sign-in under way: { id, agent, url, state, error } diff --git a/internal/gui/assets/icons/devin.svg b/internal/gui/assets/icons/devin.svg new file mode 100644 index 000000000..c5f9a183b --- /dev/null +++ b/internal/gui/assets/icons/devin.svg @@ -0,0 +1 @@ +Devin \ No newline at end of file diff --git a/internal/provider/account.go b/internal/provider/account.go index d15840201..933b8abe9 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -577,6 +577,9 @@ func Accounts() []Provider { if p, ok := grokAccount(); ok { out = append(out, p) } + if p, ok := devinAccount(); ok { + out = append(out, p) + } return out } diff --git a/internal/provider/devin.go b/internal/provider/devin.go new file mode 100644 index 000000000..8738def8f --- /dev/null +++ b/internal/provider/devin.go @@ -0,0 +1,342 @@ +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`. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/catalog" +) + +// DevinExecutable finds the devin CLI; a var so tests can fake it. +var DevinExecutable = func() string { + if p, err := exec.LookPath("devin"); err == nil { + return p + } + home, _ := os.UserHomeDir() + for _, p := range []string{filepath.Join(home, ".local", "bin", "devin"), "/usr/local/bin/devin", "/opt/homebrew/bin/devin"} { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p + } + } + return "" +} + +// DevinCredentialsPath is where the CLI keeps its sign-in. +func DevinCredentialsPath() string { + if runtime.GOOS == "windows" { + if app := os.Getenv("APPDATA"); app != "" { + return filepath.Join(app, "devin", "credentials.toml") + } + } + base := os.Getenv("XDG_DATA_HOME") + if base == "" { + home, _ := os.UserHomeDir() + base = filepath.Join(home, ".local", "share") + } + return filepath.Join(base, "devin", "credentials.toml") +} + +var devinStatus struct { + sync.Mutex + at time.Time + refreshing bool + user, plan string + ok bool +} + +// devinIdentity asks the CLI who is signed in. `devin auth status` takes a +// moment, so after the first answer a stale one is served while a fresh one +// is fetched behind it. +func devinIdentity() (user, plan string, ok bool) { + devinStatus.Lock() + defer devinStatus.Unlock() + if devinStatus.at.IsZero() { + devinStatus.user, devinStatus.plan, devinStatus.ok = askDevinIdentity() + devinStatus.at = time.Now() + } else if time.Since(devinStatus.at) > time.Minute && !devinStatus.refreshing { + devinStatus.refreshing = true + go func() { + u, p, ok := askDevinIdentity() + devinStatus.Lock() + devinStatus.user, devinStatus.plan, devinStatus.ok = u, p, ok + devinStatus.at, devinStatus.refreshing = time.Now(), false + devinStatus.Unlock() + }() + } + return devinStatus.user, devinStatus.plan, devinStatus.ok +} + +func forgetDevinStatus() { + devinStatus.Lock() + devinStatus.at = time.Time{} + devinStatus.Unlock() +} + +func askDevinIdentity() (user, plan string, ok bool) { + path := DevinExecutable() + if path == "" { + return "", "", false + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, path, "auth", "status").Output() + if err != nil { + return "", "", false + } + return parseDevinStatus(string(out)) +} + +// parseDevinStatus reads `devin auth status`'s report: +// +// Logged in (via Devin). +// ... +// User: +// Name: +// Email: +// Account: +// Tier: Devin Pro +// Plan: Pro +func parseDevinStatus(out string) (user, plan string, ok bool) { + if !strings.Contains(out, "Logged in") { + return "", "", false + } + field := func(key string) string { + for _, l := range strings.Split(out, "\n") { + l = strings.TrimSpace(l) + if v, found := strings.CutPrefix(l, key+":"); found { + return strings.TrimSpace(v) + } + } + return "" + } + user = field("Email") + if user == "" { + user = field("Name") + } + plan = field("Tier") + if plan == "" { + plan = field("Plan") + } + return user, plan, true +} + +func devinAccount() (Provider, bool) { + user, plan, ok := devinIdentity() + if !ok { + return Provider{}, false + } + acct := &Account{Agent: "devin", User: user, Plan: plan} + acct.models = func() []catalog.Model { + // what a fetch or a picker visit last asked the CLI — never spawn + // one here: Available() runs on every gateway request + devinFamiliesCache.Lock() + families := devinFamiliesCache.families + devinFamiliesCache.Unlock() + return devinModelsFlatten(families) + } + acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { + families, err := askDevinFamilies(ctx) + if err != nil { + return nil, err + } + ms := devinModelsFlatten(families) + devinFamiliesCached(families) + return ms, catalog.SaveLive("devin", "", ms) + } + return Provider{ID: "devin", Name: "Devin", Icon: "devin", Website: "https://devin.ai", Account: acct}, true +} + +// DevinFamily is one entry of `devin models list`: a name that follows the +// family's newest model, and the pinned variants under it. +type DevinFamily struct { + UID string + Label string + Aliases []string + Models []catalog.Model +} + +// devinModelsFlatten is the family list as a flat catalog: the family's +// follow-newest id, then each of its variants. +func devinModelsFlatten(families []DevinFamily) []catalog.Model { + var out []catalog.Model + for _, f := range families { + out = append(out, catalog.Model{ID: f.UID, Name: f.Label, Provider: "devin"}) + out = append(out, f.Models...) + } + return out +} + +var devinFamiliesCache struct { + sync.Mutex + at time.Time + families []DevinFamily +} + +// DevinFamilies is the CLI's model list, kept a few minutes: the picker and +// the provider ask for it often and `devin models list` spawns a process. +func DevinFamilies(ctx context.Context) ([]DevinFamily, error) { + devinFamiliesCache.Lock() + defer devinFamiliesCache.Unlock() + if time.Since(devinFamiliesCache.at) < 5*time.Minute && len(devinFamiliesCache.families) > 0 { + return devinFamiliesCache.families, nil + } + families, err := askDevinFamilies(ctx) + if err != nil { + return nil, err + } + devinFamiliesCache.families, devinFamiliesCache.at = families, time.Now() + return families, nil +} + +func devinFamiliesCached(families []DevinFamily) { + devinFamiliesCache.Lock() + devinFamiliesCache.families, devinFamiliesCache.at = families, time.Now() + devinFamiliesCache.Unlock() +} + +func askDevinFamilies(ctx context.Context) ([]DevinFamily, error) { + path := DevinExecutable() + if path == "" { + return nil, errors.New("devin is not installed") + } + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, path, "models", "list", "--format", "json").Output() + if err != nil { + return nil, errorf("devin models list: %v", err) + } + families := parseDevinModels(out) + if len(families) == 0 { + return nil, errors.New("devin models list: no models") + } + return families, nil +} + +// parseDevinModels reads `devin models list --format json`: +// +// {"families": [{"family_label": "…", "family_uid": "…", "slug": "…", +// "aliases": ["…"], "variants": [{"model_uid": "…", "label": "…", …}]}]} +func parseDevinModels(b []byte) []DevinFamily { + var list struct { + Families []struct { + FamilyUID string `json:"family_uid"` + FamilyLabel string `json:"family_label"` + Aliases []string `json:"aliases"` + Variants []struct { + ModelUID string `json:"model_uid"` + Label string `json:"label"` + } `json:"variants"` + } `json:"families"` + } + if json.Unmarshal(b, &list) != nil { + return nil + } + var out []DevinFamily + for _, f := range list.Families { + if f.FamilyUID == "" { + continue + } + fam := DevinFamily{UID: f.FamilyUID, Label: f.FamilyLabel, Aliases: f.Aliases} + if fam.Label == "" { + fam.Label = f.FamilyUID + } + for _, v := range f.Variants { + if v.ModelUID == "" { + continue + } + name := v.Label + if name == "" { + name = v.ModelUID + } + fam.Models = append(fam.Models, catalog.Model{ID: v.ModelUID, Name: name, Provider: "devin"}) + } + out = append(out, fam) + } + return out +} + +// devinAPIServer is where the CLI's Connect RPCs live; devinExchangeURL is +// where the callback's code trades for the credentials `devin auth login` +// would write — a var so tests can point it elsewhere. +const devinAPIServer = "https://server.codeium.com" + +var devinExchangeURL = devinAPIServer + "/exa.seat_management_pb.SeatManagementService/ExchangeDevinCLIPKCECode" + +// devinExchange trades the code for the credentials file `devin auth login` +// writes, then asks the CLI who signed in. The CLI's own login makes the same +// Connect call: the answer's sessionToken — already shaped +// "devin-session-token$" — is the windsurf_api_key the file wants. +func devinExchange(ctx context.Context, code, verifier, redirect string) (savedLogin, error) { + body, _ := json.Marshal(map[string]string{"code": code, + "code_verifier": verifier, "redirect_uri": redirect}) + var res struct { + SessionToken string `json:"sessionToken"` + SessionTokenAlt string `json:"session_token"` + DevinWebappHost string `json:"devinWebappHost"` + DevinAPIURL string `json:"devinApiUrl"` + } + if err := postToken(ctx, devinExchangeURL, "application/json", body, &res); err != nil { + return savedLogin{}, err + } + key := res.SessionToken + if key == "" { + key = res.SessionTokenAlt + } + if key == "" { + return savedLogin{}, errors.New("Devin's exchange returned no session token") + } + creds := devinCredentials(key, devinAPIServer, res.DevinWebappHost, res.DevinAPIURL) + // devin keeps the one account it is signed in to: writing the file is + // signing it in, and puts the file where `devin auth status` reads it + if err := writePrivate(DevinCredentialsPath(), creds); err != nil { + return savedLogin{}, err + } + forgetDevinStatus() + user, plan, _ := askDevinIdentity() + return savedLogin{Agent: "devin", User: user, Plan: plan}, nil +} + +// devinCredentials formats credentials.toml the way `devin auth login` +// writes it, with the hosts the exchange left out defaulted. +func devinCredentials(key, server, webapp, api string) []byte { + if server == "" { + server = "https://server.codeium.com" + } + if webapp == "" { + webapp = "app.devin.ai" + } + if api == "" { + api = "https://api.devin.ai" + } + var b strings.Builder + for _, kv := range [][2]string{ + {"windsurf_api_key", key}, + {"api_server_url", server}, + {"devin_webapp_host", webapp}, + {"devin_api_url", api}, + } { + fmt.Fprintf(&b, "%s = %s\n", kv[0], tomlString(kv[1])) + } + return []byte(b.String()) +} + +// tomlString quotes a TOML basic string; the values are plain ASCII tokens +// and URLs, so only the string's own delimiters need escaping. +func tomlString(s string) string { + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"` +} diff --git a/internal/provider/devin_test.go b/internal/provider/devin_test.go new file mode 100644 index 000000000..67ea8545f --- /dev/null +++ b/internal/provider/devin_test.go @@ -0,0 +1,168 @@ +package provider + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestParseDevinStatus(t *testing.T) { + user, plan, ok := parseDevinStatus(`Logged in (via Devin). + +Credentials: + File: /home/u/.local/share/devin/credentials.toml + API server: https://server.codeium.com + +User: + Name: someuser + Email: someuser@example.com + User ID: user-123 + +Account: + Tier: Devin Pro + Plan: Pro + Enterprise: no +`) + if !ok || user != "someuser@example.com" || plan != "Devin Pro" { + t.Fatalf("user=%q plan=%q ok=%v", user, plan, ok) + } + if _, _, ok := parseDevinStatus("Not logged in."); ok { + t.Fatal("a signed-out status parsed as signed in") + } + // no email field: the handle still identifies the account + user, _, ok = parseDevinStatus("Logged in (via Devin).\n\nUser:\n Name: handle\n") + if !ok || user != "handle" { + t.Fatalf("handle fallback: %q %v", user, ok) + } +} + +func TestParseDevinModels(t *testing.T) { + families := parseDevinModels([]byte(`{"families":[ + {"family_label":"SWE-2","family_uid":"swe-2","slug":"swe-2","aliases":["swe"], + "variants":[{"model_uid":"swe-2-max","label":"SWE-2 Max"},{"model_uid":"swe-2-min","label":"SWE-2 Min"}]}, + {"family_label":"Claude Opus 5.5","family_uid":"claude-opus-5-5","slug":"claude-opus-5.5","aliases":["opus"], + "variants":[{"model_uid":"claude-opus-5-5-high","label":"Claude Opus 5.5 High"}]} + ]}`)) + if len(families) != 2 { + t.Fatalf("families: %v", families) + } + f := families[0] + if f.UID != "swe-2" || f.Label != "SWE-2" || len(f.Models) != 2 || f.Models[0].ID != "swe-2-max" { + t.Fatalf("family: %+v", f) + } + flat := devinModelsFlatten(families) + if len(flat) != 5 || flat[0].ID != "swe-2" || flat[1].ID != "swe-2-max" || flat[4].ID != "claude-opus-5-5-high" { + t.Fatalf("flat: %v", flat) + } + for _, m := range flat { + if m.Provider != "devin" { + t.Fatalf("provider: %v", m) + } + } + if parseDevinModels([]byte("not json")) != nil || parseDevinModels([]byte(`{"families":[]}`)) != nil { + t.Fatal("bad payloads must not parse") + } +} + +func TestDevinCredentialsPath(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("XDG paths are unix") + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) + got := DevinCredentialsPath() + if got != filepath.Join(home, "data", "devin", "credentials.toml") { + t.Fatalf("path: %q", got) + } + t.Setenv("XDG_DATA_HOME", "") + if got := DevinCredentialsPath(); got != filepath.Join(home, ".local", "share", "devin", "credentials.toml") { + t.Fatalf("default path: %q", got) + } + _ = os.Getenv("HOME") +} + +func TestDevinCredentials(t *testing.T) { + b := string(devinCredentials(`k"ey`, "", "", "")) + for _, want := range []string{ + `windsurf_api_key = "k\"ey"`, + `api_server_url = "https://server.codeium.com"`, + `devin_webapp_host = "app.devin.ai"`, + `devin_api_url = "https://api.devin.ai"`, + } { + if !strings.Contains(b, want) { + t.Fatalf("credentials %s", b) + } + } +} + +func TestDevinSignIn(t *testing.T) { + home := claudeHome(t) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) + + // a CLI that answers `auth status` once the exchange wrote its file + exe := filepath.Join(home, "devin") + os.WriteFile(exe, []byte("#!/bin/sh\ncat <<'X'\nLogged in (via Devin).\n\nUser:\n Email: dev@example.com\n\nAccount:\n Tier: Devin Pro\nX\n"), 0o755) + oldExe := DevinExecutable + DevinExecutable = func() string { return exe } + t.Cleanup(func() { DevinExecutable = oldExe }) + + var gotCode, gotVerifier, gotRedirect string + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + gotCode, gotVerifier, gotRedirect = body["code"], body["code_verifier"], body["redirect_uri"] + json.NewEncoder(w).Encode(map[string]any{ + "sessionToken": "devin-session-token$sk-test", + "devinWebappHost": "app.devin.ai", "devinApiUrl": "https://api.devin.ai", + }) + })) + defer fake.Close() + oldTok := devinExchangeURL + devinExchangeURL = fake.URL + t.Cleanup(func() { devinExchangeURL = oldTok }) + + st, err := StartSignIn("devin") + if err != nil { + t.Fatal(err) + } + u, _ := url.Parse(st.URL) + if u.Host != "app.devin.ai" || u.Path != "/auth/cli/continue" { + t.Fatalf("url %s", st.URL) + } + q := u.Query() + if q.Get("prompt") != "select_account" || q.Get("code_challenge") == "" || + q.Get("code_challenge_method") != "S256" || q.Get("redirect_uri") == "" || q.Get("state") == "" { + t.Fatalf("params %s", st.URL) + } + page := finishInBrowser(t, st, "dv-code") + if !strings.Contains(page, "signed in") { + t.Fatalf("page %s", page) + } + if st = waitDone(t, st.ID); st.State != "done" || st.User != "dev@example.com" || st.Plan != "Devin Pro" || !st.Using { + t.Fatalf("state %+v", st) + } + if gotCode != "dv-code" || gotVerifier == "" || gotRedirect == "" { + t.Fatalf("exchange code=%q verifier=%q redirect=%q", gotCode, gotVerifier, gotRedirect) + } + // credentials.toml as `devin auth login` would write it + b, err := os.ReadFile(DevinCredentialsPath()) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{`windsurf_api_key = "devin-session-token$sk-test"`, `api_server_url = "https://server.codeium.com"`} { + if !strings.Contains(string(b), want) { + t.Fatalf("credentials %s", b) + } + } + // devin keeps the one account it is signed in to: nothing beside it + if ls := Logins("devin"); len(ls) != 0 { + t.Fatalf("logins %v", ls) + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 8a6b4b143..9bf358b0d 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -261,7 +261,7 @@ func Save(p Provider) error { } // accountIDs are the ids of the subscriptions magpie can list (account.go). -var accountIDs = []string{"claude", "codex", "copilot", "cursor", "grok"} +var accountIDs = []string{"claude", "codex", "copilot", "cursor", "devin", "grok"} func stored(id string) bool { for _, p := range load().Providers { diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 4bd01faa3..ce784d039 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -30,6 +30,7 @@ import ( var ( claudeAuthorizeURL = "https://claude.com/cai/oauth/authorize" codexAuthorizeURL = "https://auth.openai.com/oauth/authorize" + devinAuthorizeURL = "https://app.devin.ai/auth/cli/continue" // codexCallbackAddr is fixed: OpenAI only sends Codex's client back to // port 1455. codexCallbackAddr = "127.0.0.1:1455" @@ -131,6 +132,20 @@ func StartSignIn(agent string) (SignInState, error) { if err := startGrokSignIn(s); err != nil { return SignInState{}, err } + case "devin": + // `devin auth login` is a TUI over this same PKCE + localhost + // callback, so magpie runs the round itself + if ln, err = net.Listen("tcp", "127.0.0.1:0"); err != nil { + return SignInState{}, err + } + s.redirect = fmt.Sprintf("http://127.0.0.1:%d/callback", ln.Addr().(*net.TCPAddr).Port) + q.Set("redirect_uri", s.redirect) + q.Set("state", s.state) + q.Set("prompt", "select_account") + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + q.Set("cli_pkce_marker", "1") + s.st.URL = devinAuthorizeURL + "?" + q.Encode() case "copilot": // GitHub's device code, as Copilot's editors sign in if err := startCopilotSignIn(s); err != nil { @@ -294,6 +309,13 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() l, err := s.exchange(ctx, q.Get("code")) + if err == nil && s.st.Agent == "devin" { + // devin keeps the one account it is signed in to: the exchange + // already wrote it; there is nothing beside it to keep + s.finish(SignInState{State: "done", User: l.User, Plan: l.Plan, Using: true}) + signInPage(w, true, "You're signed in", fmt.Sprintf("%s is added to magpie. You can close this tab.", l.User)) + return + } if err == nil { var using bool if using, err = addLogin(l); err == nil { @@ -308,8 +330,11 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { // exchange trades the code for tokens and makes them into a login. func (s *signInFlow) exchange(ctx context.Context, code string) (savedLogin, error) { - if s.st.Agent == "codex" { + switch s.st.Agent { + case "codex": return codexExchange(ctx, code, s.verifier, s.redirect) + case "devin": + return devinExchange(ctx, code, s.verifier, s.redirect) } return claudeExchange(ctx, code, s.verifier, s.redirect, s.state) } @@ -331,9 +356,17 @@ func postToken(ctx context.Context, tokenURL, ctype string, body []byte, out any var e struct { Error any `json:"error"` ErrorDescription string `json:"error_description"` + Detail string `json:"detail"` + Message string `json:"message"` // Connect RPC errors } _ = json.Unmarshal(b, &e) msg := e.ErrorDescription + if msg == "" { + msg = e.Detail + } + if msg == "" { + msg = e.Message + } if msg == "" { if m, ok := e.Error.(map[string]any); ok { msg, _ = m["message"].(string) diff --git a/site/public/icons/devin.svg b/site/public/icons/devin.svg new file mode 100644 index 000000000..c5f9a183b --- /dev/null +++ b/site/public/icons/devin.svg @@ -0,0 +1 @@ +Devin \ No newline at end of file diff --git a/site/public/index.html b/site/public/index.html index 2e1d9b29c..9b508866e 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -403,6 +403,7 @@ footer a:hover { color: var(--ink); }
  • DeepSeek Harness
  • Command Code
  • omp
  • +
  • Devin
  • Every model