Files
magpie/internal/agent/vscode.go
T
yetoneandClaude Opus 5.5 a370877ca4 agents: VS Code's built-in chat (Copilot Chat) — switched on, magpie's models join Chat's model picker as a Custom Endpoint group in chatLanguageModels.json, with no key to enter and no Copilot sign-in needed (wani on Discord: 可以添加vscode自带的agent的配置吗)
VS Code Stable takes other vendors' models through its Custom Endpoint provider since 1.122 (customoai, the older OpenAI Compatible one, is Insiders only), signed in to GitHub or not. The provider groups live in chatLanguageModels.json beside settings.json in the default profile's User folder (~/Library/Application Support/Code/User, ~/.config/Code/User, %APPDATA%\Code\User), a JSONC array VS Code watches. magpie adds {"vendor":"customendpoint","name":"magpie","apiType":"chat-completions","models":[...]} with each catalog model at the gateway's /v1/chat/completions, toolCalling true (agent mode lists only tool-calling models), vision, contextWindow and maxOutputTokens (capped at a quarter of the window, as VS Code keeps the output budget out of the prompt's), and the model's efforts as supportsReasoningEffort. A group's apiKey is a secret property that VS Code reads from its secret storage only (languageModels.ts _resolveConfiguration), so it can't be written to the file; each model instead sends Authorization: Bearer magpie in requestHeaders, which CustomEndpointOAIEndpoint lets through and which stops it sending its own key header. The model a new chat starts on is chat.defaultModel in settings.json (matched by model id, so the catalog id); its old value is stashed and put back. The group is the agent's Joined: picking one of VS Code's own (auto) keeps magpie's models listed, and switching off (Unwire) takes the group out and puts chat.defaultModel back. Sync rewrites the group as the catalog changes, Check says when its url or header no longer reach the gateway, the Notice says where the models are and to reload the window if they don't show, and requests are credited to it by GitHubCopilotChat/<version>, a User-Agent a model's headers can't change.

internal/edit: SetJSONItem/GetJSONItem/DelJSONItem edit one element of a JSONC file's top-level array, found by its members, keeping comments, trailing commas and the other elements; SetJSON/DelJSON take a backslash-escaped dot as part of a key, as gjson does, for VS Code's flat "chat.defaultModel".

TestVSCode (connect keeps the user's settings and groups with their comments, the group's url/header/toolCalling/window and no apiKey or discovery url, Sync, Check, an own model keeping the group, disconnect back to the user's last own model), TestVSCodeRoundTrip (on and off leaves both files byte for byte; no files at all) and TestVSCodeUA; TestJSONItem, TestDelJSONItemAmongOthers and TestJSONEscapedDot. go vet ./internal/..., go build -tags nogui ./..., GOOS=windows and GOOS=linux builds pass; go test of internal/agent, edit, usage and gateway (each sandboxes HOME in TestMain) and internal/gui's page and agent connect tests pass; the full go test under a temp HOME was not run (the sandbox refused the HOME override). No GUI code changed (the generic connected wording fits), so no webkit test. VS Code itself is not installed here: not tried against a real VS Code.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:23:38 +08:00

203 lines
6.9 KiB
Go

package agent
// VS Code's own chat (GitHub Copilot Chat, built into VS Code) takes models
// of other vendors through its Custom Endpoint provider, in VS Code Stable
// since 1.122, with no GitHub sign-in or Copilot plan needed: groups of
// models in chatLanguageModels.json beside its settings.json (the default
// profile's, in its User folder), a JSONC array VS Code watches and reads
// again when it changes. magpie adds a group of its own there,
// {"vendor": "customendpoint", "name": "magpie"}, listing the catalog: each
// model at the gateway's /v1/chat/completions with tool calling on (agent
// mode lists only models that call tools). A group's apiKey can't be
// written in the file: VS Code reads it from its secret storage alone, so
// each model sends magpie's token in requestHeaders' Authorization, which a
// Custom Endpoint model may set and which then stands in for the key; the
// user is asked for none. The model a new chat starts on is the
// chat.defaultModel setting (a model id: the catalog id here); picked in
// Chat's model picker, a model is kept in VS Code's storage, not here.
import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
)
// vscodeDefault is chat.defaultModel, a key with a dot in it, escaped for
// edit's key paths.
const vscodeDefault = `chat\.defaultModel`
// vscodeUA is how VS Code's chat names itself to a Custom Endpoint: its
// fetcher's GitHubCopilotChat/<version>, which a model's requestHeaders
// can't change.
const vscodeUA = "githubcopilotchat"
// vscodeGroup is how magpie's group is found among the user's.
var vscodeGroup = map[string]string{"vendor": "customendpoint", "name": magpieID}
// VS Code keeps its User folder under Application Support on macOS, Roaming
// AppData on Windows and XDG on Linux.
func vscode(home, cfg string) *Agent {
switch runtime.GOOS {
case "darwin":
cfg = filepath.Join(home, "Library", "Application Support")
case "windows":
cfg = os.Getenv("APPDATA")
if cfg == "" {
cfg = filepath.Join(home, "AppData", "Roaming")
}
}
return vscodeAt(filepath.Join(cfg, "Code", "User"))
}
func vscodeAt(dir string) *Agent {
path := filepath.Join(dir, "settings.json")
models := filepath.Join(dir, "chatLanguageModels.json")
key := "vscode:" + path + ":"
get := func() string { v, _ := edit.GetJSON(path, vscodeDefault); return v }
ours := func() (string, bool) { return edit.GetJSONItem(models, vscodeGroup) }
joined := func() bool { _, ok := ours(); return ok }
// inGroup: a model id is one of those magpie's group lists
inGroup := func(id string) bool {
g, ok := ours()
if !ok || id == "" {
return false
}
for _, m := range gjson.Get(g, "models").Array() {
if strings.EqualFold(m.Get("id").String(), id) {
return true
}
}
return false
}
model := func() string {
v := get()
if inGroup(v) {
return magpieID + "/" + v
}
return v
}
// restore puts back the chat.defaultModel the user had before magpie's
restore := func() error {
if was := unstash(key + "model"); was != "" {
return edit.SetJSON(path, edit.KV{Path: vscodeDefault, Value: was})
}
return edit.DelJSON(path, vscodeDefault)
}
return atomic(&Agent{
ID: "vscode", Name: "VS Code", Icon: "vscode", Aliases: []string{"vs-code", "copilot-chat", "vscode-chat"},
Bin: "code", Dir: dir, Path: path,
UA: []string{vscodeUA},
Notice: func() string {
if joined() {
return "magpie's models are in VS Code's Chat model picker, under magpie (VS Code 1.122 or later). If they don't show, run Developer: Reload Window in VS Code."
}
return ""
},
// magpie's group joins the user's own models: picking one of VS
// Code's in magpie keeps it, and only switching off takes it out
Joined: joined,
Unwire: func() error {
if inGroup(get()) {
if err := restore(); err != nil {
return err
}
}
forget(key + "model")
return edit.DelJSONItem(models, vscodeGroup)
},
Sync: func() error {
cur, ok := ours()
if !ok {
return nil
}
v := vscodeGroupJSON()
if sameJSON(cur, v) {
return nil
}
return edit.SetJSONItem(models, vscodeGroup, v)
},
Check: func() string {
g, ok := ours()
if !ok || !gjson.Get(g, "models.0").Exists() {
return ""
}
return wiringOff("VS Code", models, func(k string) (string, bool) {
r := gjson.Get(g, "models.0."+k)
return r.String(), r.Exists()
}, "url", vscodeURL(), "requestHeaders.Authorization", "Bearer "+gateway.Token)
},
Fields: []Field{{
Key: "model", Label: "model", Get: model,
Set: func(v string) error {
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
if !inGroup(get()) {
stash(map[string]string{key + "model": get()})
}
if err := edit.SetJSONItem(models, vscodeGroup, vscodeGroupJSON()); err != nil {
return err
}
return edit.SetJSON(path, edit.KV{Path: vscodeDefault, Value: ref})
}
// VS Code's own: its default, where magpie's group stays
if v == "" {
if inGroup(get()) {
return restore()
}
return edit.DelJSON(path, vscodeDefault)
}
forget(key + "model")
return edit.SetJSON(path, edit.KV{Path: vscodeDefault, Value: v})
},
Options: func(cur map[string]string) []Option {
// auto: Copilot's Auto, for one signed in to it
own := []Option{{Value: "auto", Label: "Auto"}}
if v := cur["model"]; v != "" && v != "auto" && !usesMagpie(v) {
own = append(own, Option{Value: v, Icon: modelIcon("", v)})
}
return append(group("VS Code", own), viaMagpie("vscode", magpieID+"/")...)
},
}},
}, path, models, stashPath())
}
// vscodeURL is the gateway's Chat Completions URL: a Custom Endpoint model's
// url that ends in /chat/completions is asked as it is.
func vscodeURL() string { return gatewayV1() + "/chat/completions" }
// vscodeGroupJSON is magpie's group in chatLanguageModels.json: the catalog
// as VS Code's chat is shown it.
func vscodeGroupJSON() map[string]any {
list := []any{}
for _, m := range magpieModels("vscode") {
context := m.Context
if context == 0 {
context = 128000 // what VS Code takes a model of unknown window for
}
// VS Code keeps the output budget out of the window it fills with
// the prompt, so a model whose output limit is near its window
// would leave the prompt next to no room
output := maxTokens(m)
if output <= 0 {
output = 8192
}
output = min(output, context/4)
entry := map[string]any{
"id": m.ID, "name": m.Name, "url": vscodeURL(),
"toolCalling": true, "vision": m.Images,
"contextWindow": context, "maxOutputTokens": output,
"requestHeaders": map[string]string{"Authorization": "Bearer " + gateway.Token},
}
if len(m.Efforts) > 0 {
entry["supportsReasoningEffort"] = m.Efforts
entry["reasoningEffortFormat"] = "chat-completions"
}
list = append(list, entry)
}
return map[string]any{"name": magpieID, "vendor": "customendpoint", "apiType": "chat-completions", "models": list}
}