agents: Copilot CLI reaches magpie's models through its providers.json (BYOK)
tony9759 on Discord asked for Copilot CLI to be wired to magpie, since its
docs say it takes a custom model provider URL.
What Copilot does (1.0.105, @github/copilot-darwin-arm64's cli-main.js,
`copilot help providers` / `help environment`; GitHub docs
docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/use-byok-models):
env BYOK (COPILOT_PROVIDER_BASE_URL, _TYPE openai|azure|anthropic, _API_KEY,
_WIRE_API completions|responses) and a providers.json at
$COPILOT_PROVIDERS_CONFIG, else <COPILOT_HOME or ~/.copilot>/providers.json:
{providers:[{name,type,baseUrl,apiKey}], models:[{id,provider,name,
maxPromptTokens,maxOutputTokens,...}]}, picked as <provider>/<id> in
settings.json "model". Neither needs a GitHub sign-in. The multi-provider
file is marked experimental in the SDK types. The version BYOK started in is
not verified (github/gh-aw#25014 says 1.0.19; GitHub's changelog of
2026-04-07 announces it).
magpie writes the persistent file, not the environment: provider "magpie"
(openai chat completions, the gateway's /v1, the agent-named key) and one
models entry per catalog model, then model = magpie/<ref>. Only entries
naming magpie are magpie's; the user's providers, models and other keys stay
through connect, Sync and Disconnect (which also restores the model they were
on); a file that does not parse is never written over. COPILOT_HOME and
COPILOT_PROVIDERS_CONFIG are honoured (the latter added to agentenv.Vars).
Copilot's own models stay in the field's list.
Run at this head (a4fb75bfd's tree on 47b7ba303, mote): go test -timeout 45m
-count=1 ./internal/agent ./internal/agentenv ok; gofmt -l clean; GOOS=linux
and GOOS=windows go vet ./internal/agent ./internal/agentenv ok. Before the
rebase also ./internal/gui (only TestMainWindowCorners, red on origin/main
47b7ba303 too, #3949) and ./internal/library ok. TestModelReadersShareTheList
caught a first draft ranging over magpieModels; it uses sharedModels.
Real e2e: magpie's own Pick wrote the files into a sandbox COPILOT_HOME, the
real copilot 1.0.105 binary (no GitHub account) ran `-p "say hi"` against a
fake OpenAI server and sent POST /v1/chat/completions, model deepseek/pro,
Bearer magpie-copilot. The interactive TUI was also started earlier on a hand-written
providers.json and answered from it.
Broken by hand, each red: user providers dropped on write, Disconnect's
unwrite a no-op, an unparseable file treated as empty, Sync a no-op.
Not tried: a real magpie gateway behind it (the fake stood in), Copilot's
`anthropic`/`responses` wire types, Windows/WSL Copilot, an org with
forceLoginOrgs, tools/streaming against a real vendor model, the GUI suite
(no Agents-row layout change).
This commit is contained in:
@@ -74,6 +74,7 @@ something else shows up as drift.
|
||||
- Each model magpie writes into ZCode's `providerModelRules` has native web search (`properties.supportsNativeWebSearch`, "原生联网搜索") on while the provider's format is Anthropic Messages, the only format ZCode sends it on (`zcodeWebSearch`). The models magpie turned it on for are kept in the stash under `zcode.web_search`, so a model the user unticked in ZCode (which takes the key out of the rule) stays off, a value in the rule stays, a manual rule is left alone, and a stash that can't be read turns nothing on. On another format magpie's own on is taken out. Disconnect forgets the list.
|
||||
- The YAML ones go through `yamlKept` and `mergeKept` in [`sync.go`](../../internal/agent/sync.go). Each is tested by a `Test<Agent>KeepsTheUsersSettings`.
|
||||
- Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it.
|
||||
- The Copilot CLI (1.0.105 tried) takes its own model providers from `providers.json` (BYOK; `copilot help providers`, [GitHub's docs](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/use-byok-models)): `$COPILOT_PROVIDERS_CONFIG`, else beside `settings.json` in `$COPILOT_HOME` or `~/.copilot`. It needs no GitHub sign-in, and a model is picked as `<provider>/<id>` in settings.json's `model`. Picking a magpie model writes the provider `magpie` (type `openai`, chat completions, the gateway's `/v1`, the agent's own key) and one `models` entry per model of magpie's, each with its name and limits (`copilotWrite` in [`copilot_byok.go`](../../internal/agent/copilot_byok.go)), then `model` as `magpie/<model>`. Only the entries naming `magpie` are magpie's: the user's providers, models and any other key stay through connect, `Sync` (which follows the catalog while the file has the provider) and Disconnect, and a file that doesn't parse is left as it is with an error (`TestCopilotKeepsTheUsersOwn`, `TestCopilotUnreadableProvidersJSONIsNotWrittenOver`). Copilot's own models stay in the field's list beside magpie's. `COPILOT_PROVIDER_BASE_URL` in the environment, or an organization policy that forces a GitHub sign-in (`forceLoginOrgs`), takes over from the file; magpie sets neither. The multi-provider file is marked experimental in Copilot's SDK types (tony9759 on Discord).
|
||||
- dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking` or `AdaptiveWithEffort`, so Max reaches GLM-5.3 as max) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. For a custom provider with more than one URL that is the API its Base URL was given as (`BaseAPI`), after the vendor rules (an OpenAI model on OpenAI's API, a Claude where Messages is served): a relay set to Responses whose Chat URL Detect found beside it had its GPTs on dsh's Chat route (nb5p on Discord, `TestDshCustomResponsesProvider`). dsh's bundled pi-ai (`@earendil-works/pi-ai`, dsh 0.2.1-rc.2) takes `openai-responses` as a route's `api`. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. A model of a route whose api stands as `openai-responses` carries `compat.supportsStrictMode` (#3055): OpenAI's Responses API takes a function tool whose `strict` is left out as a strict-mode one, every property required, so a tool's optional parameters come back filled; pi-ai says `strict: false` on an ordinary tool only when the compat says so, by the api the route has, not by its name. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. A start on a model by an id magpie lists it by no longer, a found group's `group/auto-<slug>` (now `auto/<model>`, `provider.PublicRef`) or a renamed provider's (`provider.RenamedRef`), moves onto the id its route lists, in every profile and the home layer: dsh finds the start by that id, and the desktop app showed no model picked while its patch list held every route (zyh6036 on X, `TestDshStartOnAFoundGroupsOldIdMovesOntoItsId`). `renameFoundGroups` moves only a value applied.json records, and the start dsh read was not one (none on the owner's install either), nor is a pick made in dsh. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id.
|
||||
- The names every agent's model list gets are `provider.Labels`' ([`modelprefs.go`](../../internal/provider/modelprefs.go)). With Provider in model names off (or own, for names the user gave), a name stands alone unless another model in the same list reads the same, when both keep their provider's after it. A routing group named as anything else in the list keeps "· routing group", and the model it shares the name with stays plain: the group found for a model served by two providers, one of them hidden from the agent, had the shown model read "GPT-6.1 Terra · MyGateway" beside its provider's plain "GPT-6.1 Sol" (nb5p on Discord; `TestPlainNames`, `TestSuffixMode`, `TestPlainOwnNamesGroups`).
|
||||
- dsh takes a model's listed `maxTokens` as every request's output and reserves it, with 65536 of headroom, out of `contextWindow` before deciding when to compact (compaction-basic's `resolveCompactSpec`: the smaller of 80% of the window and window − maxTokens − 65536). A vendor's reply limit near its window had dsh compact at 41248 of a 500000 group (#2823) or fail with no budget (524288/524288, LoKi on Discord; 131072/65536), so magpie lists it held to what leaves dsh half the window to compact in (window/2 − 65536), or to a quarter of the window where that is more (every window under 262144, as VS Code and Copilot in JetBrains hold it), on every route and in the older `llm-deepseek` entry (`dshMaxTokens`). A quarter alone cut DeepSeek's 393216 on its 1000000 window to 250000 (#3298); now it keeps all of it and dsh compacts at 541248, while 500000/393216 is held to 184464 and compacts at 250000. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`.
|
||||
|
||||
+49
-10
@@ -1673,7 +1673,29 @@ func cursor(home string) *Agent {
|
||||
|
||||
func copilot(home string) *Agent {
|
||||
dir := filepath.Join(home, ".copilot")
|
||||
// COPILOT_HOME moves the whole folder, settings.json and providers.json
|
||||
// with it (Copilot's `copilot help environment`)
|
||||
if d := appdir.Getenv("COPILOT_HOME"); d != "" {
|
||||
dir = d
|
||||
}
|
||||
path := filepath.Join(dir, "settings.json")
|
||||
// Copilot CLI's own multi-provider file (BYOK): $COPILOT_PROVIDERS_CONFIG,
|
||||
// else providers.json beside settings.json. It needs no GitHub sign-in.
|
||||
provs := filepath.Join(dir, "providers.json")
|
||||
if p := appdir.Getenv("COPILOT_PROVIDERS_CONFIG"); p != "" {
|
||||
provs = p
|
||||
}
|
||||
own := func() []Option {
|
||||
// "auto" is Copilot's own choice, not a model it lists; the rest
|
||||
// come from the list magpie last fetched from Copilot.
|
||||
out := []Option{{Value: "auto", Note: "let Copilot pick", Icon: "githubcopilot"}}
|
||||
if live, _, ok := catalog.Live("copilot"); ok {
|
||||
// magpie's list has Auto too, offered above
|
||||
live = slices.DeleteFunc(slices.Clone(live), func(m catalog.Model) bool { return m.ID == "auto" })
|
||||
out = append(out, options(live, "")...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
return &Agent{
|
||||
ID: "copilot", Name: "Copilot CLI", Icon: "githubcopilot", Aliases: []string{"gh-copilot"},
|
||||
UA: []string{"copilot", "github-copilot"},
|
||||
@@ -1688,20 +1710,37 @@ func copilot(home string) *Agent {
|
||||
// PATH, and running it only asks for the CLI to be installed
|
||||
// (#3269): a command of the editor's is not the CLI
|
||||
binNot: editorLauncher,
|
||||
// magpie/<model> is a model of the provider named magpie in providers.json
|
||||
Spelled: prefixed,
|
||||
ListOnly: true,
|
||||
Check: func() string {
|
||||
if v, _ := edit.GetJSON(path, "model"); !prefixed(v) {
|
||||
return ""
|
||||
}
|
||||
p := copilotProvider(provs)
|
||||
return wiringOff("Copilot CLI", provs, func(k string) (string, bool) { v, ok := p[k].(string); return v, ok },
|
||||
"baseUrl", gateway.URL()+"/v1", "apiKey", agentKey("copilot"))
|
||||
},
|
||||
Sync: func() error { return copilotSync(provs, gateway.URL()+"/v1", agentKey("copilot")) },
|
||||
Fields: []Field{{
|
||||
Key: "model", Label: "model",
|
||||
Get: jsonGet(path, "model"),
|
||||
Set: jsonSet(path, "model"),
|
||||
Options: func(map[string]string) []Option {
|
||||
// "auto" is Copilot's own choice, not a model it lists; the rest
|
||||
// come from the list magpie last fetched from Copilot.
|
||||
out := []Option{{Value: "auto", Note: "let Copilot pick", Icon: "githubcopilot"}}
|
||||
if live, _, ok := catalog.Live("copilot"); ok {
|
||||
// magpie's list has Auto too, offered above
|
||||
live = slices.DeleteFunc(slices.Clone(live), func(m catalog.Model) bool { return m.ID == "auto" })
|
||||
out = append(out, options(live, "")...)
|
||||
Set: func(v string) error {
|
||||
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
|
||||
if err := copilotWrite(provs, gateway.URL()+"/v1", agentKey("copilot")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return out
|
||||
if v == "" {
|
||||
if err := edit.DelJSON(path, "model"); err != nil {
|
||||
return err
|
||||
}
|
||||
return copilotUnwrite(provs)
|
||||
}
|
||||
return edit.SetJSON(path, edit.KV{Path: "model", Value: v})
|
||||
},
|
||||
Options: func(cur map[string]string) []Option {
|
||||
return withVia(own(), "copilot", magpieID+"/")
|
||||
},
|
||||
}, {
|
||||
// effortLevel, which Copilot saves beside the model and clears
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
)
|
||||
|
||||
// Copilot CLI takes its own model providers from providers.json (BYOK, `copilot
|
||||
// help providers`; docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/use-byok-models):
|
||||
//
|
||||
// {"providers": [{"name", "type", "baseUrl", "apiKey", "wireApi"}],
|
||||
// "models": [{"id", "provider", "name", "maxPromptTokens", "maxOutputTokens", ...}]}
|
||||
//
|
||||
// and a model is picked as <provider>/<id> (settings.json "model"). It needs
|
||||
// no GitHub sign-in. magpie owns the entry named magpie in providers and the
|
||||
// entries of models that name it; every other entry, and any other key the
|
||||
// file has, is the user's and stays.
|
||||
|
||||
// copilotFile is providers.json at path, read as it is: its top-level keys
|
||||
// as they are, "providers" and "models" as lists. A file that does not parse
|
||||
// is an error, never an empty file to write over.
|
||||
func copilotFile(path string) (map[string]json.RawMessage, error) {
|
||||
b, err := edit.Read(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
top := map[string]json.RawMessage{}
|
||||
if len(bytes.TrimSpace(b)) == 0 {
|
||||
return top, nil
|
||||
}
|
||||
if err := json.Unmarshal(b, &top); err != nil || top == nil {
|
||||
return nil, fmt.Errorf("%s isn't a JSON object, so magpie leaves it as it is", path)
|
||||
}
|
||||
return top, nil
|
||||
}
|
||||
|
||||
func copilotList(top map[string]json.RawMessage, key string) ([]json.RawMessage, error) {
|
||||
raw, ok := top[key]
|
||||
if !ok || string(bytes.TrimSpace(raw)) == "null" {
|
||||
return nil, nil
|
||||
}
|
||||
var l []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &l); err != nil {
|
||||
return nil, fmt.Errorf("providers.json's %s isn't a list, so magpie leaves it as it is", key)
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// ofMagpie reports whether entry (a provider, or a model by its provider
|
||||
// key) is magpie's.
|
||||
func copilotOwn(entry json.RawMessage, key string) bool {
|
||||
var e map[string]any
|
||||
if json.Unmarshal(entry, &e) != nil {
|
||||
return false
|
||||
}
|
||||
n, _ := e[key].(string)
|
||||
return n == magpieID
|
||||
}
|
||||
|
||||
// copilotProvider is magpie's provider entry in the file at path, empty
|
||||
// when there is none.
|
||||
func copilotProvider(path string) map[string]any {
|
||||
top, err := copilotFile(path)
|
||||
if err != nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
l, _ := copilotList(top, "providers")
|
||||
for _, e := range l {
|
||||
if copilotOwn(e, "name") {
|
||||
var m map[string]any
|
||||
if json.Unmarshal(e, &m) == nil {
|
||||
return m
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
// copilotBlock is magpie's provider and its models for the gateway at url
|
||||
// (ending in /v1), as the catalog lists them for Copilot. The wire is
|
||||
// OpenAI's chat completions, which the gateway translates for every model.
|
||||
func copilotBlock(url, key string) (map[string]any, []map[string]any) {
|
||||
prov := map[string]any{"name": magpieID, "type": "openai", "baseUrl": url, "apiKey": key}
|
||||
ms := []map[string]any{}
|
||||
for _, m := range sharedModels("copilot") {
|
||||
e := map[string]any{"id": m.ID, "provider": magpieID}
|
||||
if m.Name != "" {
|
||||
e["name"] = m.Name
|
||||
}
|
||||
if out := maxTokens(m); out > 0 {
|
||||
e["maxOutputTokens"] = out
|
||||
}
|
||||
if m.Context > 0 {
|
||||
e["maxContextWindowTokens"] = m.Context
|
||||
prompt := m.Context
|
||||
if out := maxTokens(m); out > 0 && out < prompt {
|
||||
prompt -= out
|
||||
}
|
||||
e["maxPromptTokens"] = prompt
|
||||
}
|
||||
ms = append(ms, e)
|
||||
}
|
||||
return prov, ms
|
||||
}
|
||||
|
||||
// copilotWrite puts magpie's provider and models into providers.json,
|
||||
// everything else in the file as it was. What the file already holds in
|
||||
// magpie's own provider entry under a key magpie doesn't write stays.
|
||||
func copilotWrite(path, url, key string) error {
|
||||
top, err := copilotFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
provs, err := copilotList(top, "providers")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
models, err := copilotList(top, "models")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prov, ms := copilotBlock(url, key)
|
||||
want, _ := json.Marshal(prov)
|
||||
var wm map[string]json.RawMessage
|
||||
json.Unmarshal(want, &wm)
|
||||
placed := false
|
||||
var outP []json.RawMessage
|
||||
for _, e := range provs {
|
||||
if !copilotOwn(e, "name") {
|
||||
outP = append(outP, e)
|
||||
continue
|
||||
}
|
||||
if placed {
|
||||
continue
|
||||
}
|
||||
placed = true
|
||||
var have map[string]json.RawMessage
|
||||
merged := wm
|
||||
if json.Unmarshal(e, &have) == nil && have != nil {
|
||||
merged = mergeTheirs(have, wm, nil)
|
||||
}
|
||||
b, _ := json.Marshal(merged)
|
||||
outP = append(outP, b)
|
||||
}
|
||||
if !placed {
|
||||
outP = append(outP, want)
|
||||
}
|
||||
var outM []json.RawMessage
|
||||
first := -1
|
||||
for _, e := range models {
|
||||
if copilotOwn(e, "provider") {
|
||||
if first < 0 {
|
||||
first = len(outM)
|
||||
}
|
||||
continue
|
||||
}
|
||||
outM = append(outM, e)
|
||||
}
|
||||
if first < 0 {
|
||||
first = len(outM)
|
||||
}
|
||||
var mine []json.RawMessage
|
||||
for _, m := range ms {
|
||||
b, _ := json.Marshal(m)
|
||||
mine = append(mine, b)
|
||||
}
|
||||
outM = append(outM[:first], append(mine, outM[first:]...)...)
|
||||
top["providers"], _ = json.Marshal(outP)
|
||||
top["models"], _ = json.Marshal(outM)
|
||||
return copilotSave(path, top)
|
||||
}
|
||||
|
||||
// copilotUnwrite takes magpie's provider and models out of providers.json,
|
||||
// leaving the rest; a file left with nothing in it that magpie made is not
|
||||
// deleted, as it may be the user's.
|
||||
func copilotUnwrite(path string) error {
|
||||
top, err := copilotFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(top) == 0 {
|
||||
return nil
|
||||
}
|
||||
provs, err := copilotList(top, "providers")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
models, err := copilotList(top, "models")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keep := func(l []json.RawMessage, key string) []json.RawMessage {
|
||||
out := []json.RawMessage{}
|
||||
for _, e := range l {
|
||||
if !copilotOwn(e, key) {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
np, nm := keep(provs, "name"), keep(models, "provider")
|
||||
if len(np) == len(provs) && len(nm) == len(models) {
|
||||
return nil
|
||||
}
|
||||
top["providers"], _ = json.Marshal(np)
|
||||
top["models"], _ = json.Marshal(nm)
|
||||
return copilotSave(path, top)
|
||||
}
|
||||
|
||||
// copilotSync brings magpie's entries up to the catalog as it is now, when
|
||||
// the file has them; one that already says the same is not written.
|
||||
func copilotSync(path, url, key string) error {
|
||||
top, err := copilotFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
provs, _ := copilotList(top, "providers")
|
||||
has := false
|
||||
for _, e := range provs {
|
||||
has = has || copilotOwn(e, "name")
|
||||
}
|
||||
if !has {
|
||||
return nil
|
||||
}
|
||||
return copilotWrite(path, url, key)
|
||||
}
|
||||
|
||||
func copilotSave(path string, top map[string]json.RawMessage) error {
|
||||
b, err := json.MarshalIndent(top, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return edit.WriteAtomic(path, append(b, '\n'))
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// providers is providers.json at path, parsed.
|
||||
func copilotParsed(t *testing.T, path string) (provs, models []map[string]any, top map[string]any) {
|
||||
t.Helper()
|
||||
if err := json.Unmarshal([]byte(readFile(path)), &top); err != nil {
|
||||
t.Fatalf("%s: %v\n%s", path, err, readFile(path))
|
||||
}
|
||||
for _, k := range []struct {
|
||||
key string
|
||||
to *[]map[string]any
|
||||
}{{"providers", &provs}, {"models", &models}} {
|
||||
if l, ok := top[k.key].([]any); ok {
|
||||
for _, e := range l {
|
||||
*k.to = append(*k.to, e.(map[string]any))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func copilotSandbox(t *testing.T) (*Agent, string) {
|
||||
t.Helper()
|
||||
home := effortHome(t)
|
||||
t.Setenv("COPILOT_HOME", "")
|
||||
t.Setenv("COPILOT_PROVIDERS_CONFIG", "")
|
||||
return copilot(home), filepath.Join(home, ".copilot", "providers.json")
|
||||
}
|
||||
|
||||
// Connecting Copilot CLI to magpie's model writes the provider Copilot reads
|
||||
// from providers.json (BYOK, no GitHub sign-in) and picks it in settings.json
|
||||
// as <provider>/<model>, the way Copilot's /model does (tony9759 on Discord).
|
||||
func TestCopilotModelWritesProvidersJSON(t *testing.T) {
|
||||
cp, provs := copilotSandbox(t)
|
||||
if err := cp.Pick("model", "magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := cp.Field("model").Get(); got != "magpie/deepseek/pro" {
|
||||
t.Fatalf("model reads %q", got)
|
||||
}
|
||||
ps, ms, _ := copilotParsed(t, provs)
|
||||
if len(ps) != 1 || ps[0]["name"] != "magpie" || ps[0]["type"] != "openai" ||
|
||||
ps[0]["baseUrl"] != gateway.URL()+"/v1" || ps[0]["apiKey"] != agentKey("copilot") {
|
||||
t.Fatalf("provider: %v", ps)
|
||||
}
|
||||
found := map[string]bool{}
|
||||
for _, m := range ms {
|
||||
if m["provider"] != "magpie" {
|
||||
t.Fatalf("model of another provider: %v", m)
|
||||
}
|
||||
found[m["id"].(string)] = true
|
||||
}
|
||||
if !found["deepseek/pro"] || !found["deepseek/flash"] {
|
||||
t.Fatalf("models: %v", found)
|
||||
}
|
||||
if !cp.Wired() {
|
||||
t.Fatal("not wired")
|
||||
}
|
||||
if msg := cp.Check(); msg != "" {
|
||||
t.Fatalf("check: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// What the user keeps in providers.json, a provider of theirs, a model of
|
||||
// theirs, a key magpie doesn't know, is left as it was by connect, by sync
|
||||
// and by disconnect; their own model in settings.json is not touched until
|
||||
// magpie's is picked, and Disconnect puts it back.
|
||||
func TestCopilotKeepsTheUsersOwn(t *testing.T) {
|
||||
cp, provs := copilotSandbox(t)
|
||||
writeFile(t, provs, `{"theme":"x","providers":[{"name":"mine","type":"openai","baseUrl":"https://mine.example/v1","apiKey":"K"}],`+
|
||||
`"models":[{"id":"m1","provider":"mine","name":"Mine"}]}`)
|
||||
writeFile(t, cp.Path, `{"model":"mine/m1","effortLevel":"high"}`)
|
||||
if err := cp.Connect(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := cp.Field("model").Get(); !strings.HasPrefix(v, "magpie/") {
|
||||
t.Fatalf("connect left the model on %q", v)
|
||||
}
|
||||
ps, ms, top := copilotParsed(t, provs)
|
||||
if top["theme"] != "x" || len(ps) != 2 || ps[0]["name"] != "mine" || ps[0]["apiKey"] != "K" {
|
||||
t.Fatalf("the user's own is lost:\n%s", readFile(provs))
|
||||
}
|
||||
if ms[0]["id"] != "m1" || ms[0]["provider"] != "mine" {
|
||||
t.Fatalf("the user's model is lost:\n%s", readFile(provs))
|
||||
}
|
||||
if v, _ := edit.GetJSON(cp.Path, "effortLevel"); v != "high" {
|
||||
t.Fatalf("effortLevel %q", v)
|
||||
}
|
||||
if err := cp.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cp.Disconnect(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := cp.Field("model").Get(); v != "mine/m1" {
|
||||
t.Fatalf("disconnect left the model on %q, not the one before", v)
|
||||
}
|
||||
ps, ms, top = copilotParsed(t, provs)
|
||||
if top["theme"] != "x" || len(ps) != 1 || ps[0]["name"] != "mine" || len(ms) != 1 || ms[0]["id"] != "m1" {
|
||||
t.Fatalf("after disconnect:\n%s", readFile(provs))
|
||||
}
|
||||
if cp.Wired() {
|
||||
t.Fatal("still wired")
|
||||
}
|
||||
}
|
||||
|
||||
// A providers.json that isn't JSON is the user's, however it got that way:
|
||||
// magpie says so and writes nothing.
|
||||
func TestCopilotUnreadableProvidersJSONIsNotWrittenOver(t *testing.T) {
|
||||
cp, provs := copilotSandbox(t)
|
||||
writeFile(t, provs, `{"providers": [oops`)
|
||||
if err := cp.Field("model").Set("magpie/deepseek/pro"); err == nil {
|
||||
t.Fatal("no error for a file that does not parse")
|
||||
}
|
||||
if got := readFile(provs); got != `{"providers": [oops` {
|
||||
t.Fatalf("the file was written over:\n%s", got)
|
||||
}
|
||||
if v, _ := edit.GetJSON(cp.Path, "model"); v != "" {
|
||||
t.Fatalf("settings.json picked %q for a provider that was not written", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Sync follows the catalog, drift is told, and COPILOT_PROVIDERS_CONFIG /
|
||||
// COPILOT_HOME move the files as they move Copilot's.
|
||||
func TestCopilotSyncCheckAndEnv(t *testing.T) {
|
||||
cp, provs := copilotSandbox(t)
|
||||
cp.Field("model").Set("magpie/deepseek/pro")
|
||||
// a model dropped by hand comes back with the sync; the user's pick stays
|
||||
edit.WriteAtomic(provs, []byte(`{"providers":[{"name":"magpie","type":"openai","baseUrl":"http://127.0.0.1:1/v1","apiKey":"x"}],"models":[]}`))
|
||||
if cp.Check() == "" {
|
||||
t.Fatal("a provider pointing elsewhere is not told")
|
||||
}
|
||||
if err := cp.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, ms, _ := copilotParsed(t, provs)
|
||||
if len(ms) < 2 || cp.Check() != "" {
|
||||
t.Fatalf("sync left %d models, check %q", len(ms), cp.Check())
|
||||
}
|
||||
|
||||
other := filepath.Join(t.TempDir(), "mine.json")
|
||||
t.Setenv("COPILOT_PROVIDERS_CONFIG", other)
|
||||
home := t.TempDir()
|
||||
cp2 := copilot(home)
|
||||
if err := cp2.Field("model").Set("magpie/deepseek/flash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ms, _ := copilotParsed(t, other); len(ms) < 2 {
|
||||
t.Fatalf("COPILOT_PROVIDERS_CONFIG not written: %s", readFile(other))
|
||||
}
|
||||
t.Setenv("COPILOT_PROVIDERS_CONFIG", "")
|
||||
t.Setenv("COPILOT_HOME", filepath.Join(home, "ch"))
|
||||
if got := copilot(home).Path; got != filepath.Join(home, "ch", "settings.json") {
|
||||
t.Fatalf("COPILOT_HOME ignored: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ package agentenv
|
||||
// of them, and sets back the ones its own fixtures need.
|
||||
var Vars = []string{
|
||||
// Claude Code, Codex and Copilot CLI
|
||||
"CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME",
|
||||
"CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "COPILOT_PROVIDERS_CONFIG",
|
||||
// Claude Code's temp folder, the images its sessions were given
|
||||
"CLAUDE_CODE_TMPDIR",
|
||||
// Zed, or a fork of it that keeps its settings (ZedG)
|
||||
|
||||
Reference in New Issue
Block a user