Files
magpie/internal/provider/copilot_cli.go
T
yetone 73a12e8bf6 wsl: a distro's agent folder that is a link is opened where it leads (#4502)
On Windows, adding a skill or switching RTK on for an agent in WSL failed
with `mkdir \\wsl.localhost\<distro>\root\.codex: Cannot create a file
when that file already exists` (linusxiong). In the distro ~/.codex is a
link to /mnt/c/Users/<user>/.codex. Through \\wsl.localhost Windows can't
follow a link the distro has: a mkdir of it says it exists, and nothing
below it can be made, written, read or listed. ggbdpq found and explained
the link (thanks); their patch, which takes that EEXIST as "there", wasn't
used: the writes below the link fail next (its test passed because a
symlink here is followed).

The fix, for every agent folder and every writer through \\wsl.localhost:
- The WSL probe asks `readlink -f` in the distro where each agent folder,
  its skills folder and the folders beside them lead (wslLinkPaths ->
  distro.Links; a $HOME that is itself through a link is left alone), and
  which drive each Windows mount is (win:/mnt/c C: -> distro.Drives).
- distro.open opens a path at or below a link where it leads: on a Windows
  drive, the drive's own path (C:\Users\<user>\.codex); elsewhere in the
  distro, through \\wsl.localhost again. native spells it back through
  the link, so the agent is told its own path.
- A link readlink couldn't resolve is never guessed at: distro.open
  errors, and the agent is unreached (Agent.Unreached: its notice says
  why; every field Set and Sync returns it).
- Writers: the agents' own files (place.join/place.open, every
  filepath.Join(at.home, ...) in internal/agent), the library's WSL
  targets (wslOpen/wslOpened; one "wsl" problem per agent and nothing
  written), RTK (rtkAt, rtkInstall checks agent.WSLOpen before its mkdir),
  the Sessions page's WSL reads (sessions.WSLHome.Open) and the Copilot
  CLI sign-in read (provider.CopilotWSLHomes -> CopilotWSLDirs).
- Not changed: magpie's image MCP server opens arbitrary paths an agent
  in WSL gives it the same way; filed as #4578. Links deeper than the
  probed paths (other than <agent dir>/skills) aren't resolved. A distro
  probed by an older magpie has no Links until probed again (each run).

Run:
- Real Windows box (xiaomi-gpu, distro magpie-desktop, sandbox
  /tmp/x4502/home with .codex -> /mnt/c/Users/yeton/runs/x4502-target/.codex,
  .claude -> /tmp/x4502/data/claude, .pi -> a missing folder), a throwaway
  Windows test running the real probe with that HOME: probe said
  link:.codex /mnt/c/..., link:.claude /tmp/x4502/data/claude, link:.pi,
  win:/mnt/c C:, win:/mnt/d D:. The old way, MkdirAll(\\wsl.localhost\
  magpie-desktop\tmp\x4502\home\.codex\skills\pdf) = "Cannot create a file
  when that file already exists" (the report's error). distro.open wrote
  SKILL.md to C:\Users\yeton\runs\x4502-target\.codex\skills\pdf and to
  \\wsl.localhost\magpie-desktop\tmp\x4502\data\claude\skills\pdf, both
  read back with cat in the distro through the links; .pi said "~/.pi in
  WSL magpie-desktop is a link magpie couldn't follow". Sandbox and target
  removed after.
- New tests with a fake distro whose ~/.codex and ~/.claude are links to
  /mnt/c/... that don't exist here, so, as through \\wsl.localhost,
  nothing below them can be made: TestWSLFolderIsALinkToC,
  TestWSLFolderLinkUnresolved, TestRTKWSLFolderIsALink,
  TestRTKWSLFolderLinkUnresolved (library); TestWSLProbeLinks (runs the
  probe script), TestWSLOpenThroughLinks, TestWSLAgentFolderIsALink
  (config and a Claude session read on C:), TestWSLAgentFolderLinkUnresolved
  (agent).
- Broken by hand: the library tests on the base (with a no-op
  FakeWSLDrives) fail with "mkdir .../home/me/.codex: file exists", the
  report's error; with ggbdpq's patch applied they still fail (the skill
  mkdir, and RTK's hook not written).
- mote: go build ./...; go vet of agent, library, sessions, provider for
  darwin, GOOS=windows (and linux for agent, library); gofmt -l clean;
  go test -timeout 45m ./internal/agent ./internal/library
  ./internal/sessions ./internal/provider: all ok.
- Windows (win-run): the same four packages. The new tests pass (the
  RTK ones skip: the fake distro runs sh). 32 tests are red, all already
  red at the base c63c2136b run on the same box, and filed (#4115, #2808:
  Hermes profiles, Codex keychain, Agy, desktop entries, ...); the Hermes
  ones fail alike on base and branch with -count=3.

- Rebased on origin/main 3ecc02b78 (it changed internal/agent): at this
  head on mote, go build ./..., go vet of the four packages for darwin,
  windows and linux, gofmt -l, go test ./internal/agent ./internal/library:
  ok.

Not tried: the full ./... suite; the GUI (no GUI change; the unreached
notice uses the existing Notice); a real Codex/Claude Code run against
the moved files in the distro.
2026-10-31 21:29:22 +08:00

257 lines
8.0 KiB
Go

package provider
// The standalone Copilot CLI keeps its sign-in apart from the editors: who
// is signed in in ~/.copilot/config.json, the token in the system keychain
// (service copilot-cli), or in that file when the user chose plaintext. Its
// token is not traded for a session token the way an editor's is (that
// exchange answers 403): the CLI sends it as is, under its own integration.
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/settings"
)
// copilotCLIHeaders are what the CLI sends with its token.
var copilotCLIHeaders = map[string]string{
"Editor-Version": "copilot/1.0.88",
"Copilot-Integration-Id": "copilot-developer-cli",
"X-GitHub-Api-Version": "2026-07-01",
"User-Agent": "copilot/1.0.88",
}
// CopilotUserURL says where an account's Copilot API is; a var so tests can
// point it elsewhere.
var CopilotUserURL = "https://api.github.com/copilot_internal/user"
type copilotCLIUser struct {
Host string `json:"host"`
Login string `json:"login"`
}
// copilotCLIHome is where the CLI keeps its settings.
func copilotCLIHome() string {
if h := appdir.Getenv("COPILOT_HOME"); h != "" {
return h
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".copilot")
}
// CopilotWSLDirs, set by internal/agent, are the Copilot CLI's folders
// (~/.copilot), as magpie opens them, in the WSL distros that run now:
// magpie on Windows finds a Copilot CLI signed in inside one (#723,
// jia2). Where ~/.copilot is a link the folder is where it leads (#4502).
// nil, or none, off Windows. A stopped distro isn't in it: reading its
// files would start it.
var CopilotWSLDirs func() []string
// copilotWSLAge is how long a WSL distro's Copilot CLI sign-in is kept as
// read: its files are read over WSL's file share, slower than a disk's.
var copilotWSLAge = 20 * time.Second
var copilotWSL struct {
sync.Mutex
at time.Time
app copilotApp
ok bool
}
// copilotCLILogin is the account the Copilot CLI is signed in to, with its
// token: on this machine, or, for magpie on Windows, in a WSL distro that
// runs now. A distro's token is read only from its config.json, where the
// CLI keeps it when the distro has no keyring to put it in (WSL has none
// unless one is set up): magpie can't reach a distro's keyring.
func copilotCLILogin() (copilotApp, bool) {
if settings.AccountDiscoveryOff() {
return copilotApp{}, false
}
if app, ok := copilotCLILoginIn(copilotCLIHome(), copilotCLISecret); ok {
return app, true
}
if CopilotWSLDirs == nil {
return copilotApp{}, false
}
c := &copilotWSL
c.Lock()
defer c.Unlock()
if !c.at.IsZero() && time.Since(c.at) < copilotWSLAge {
return c.app, c.ok
}
c.app, c.ok = copilotApp{}, false
for _, dir := range CopilotWSLDirs() {
if app, ok := copilotCLILoginIn(dir, nil); ok {
c.app, c.ok = app, true
break
}
}
c.at = time.Now()
return c.app, c.ok
}
// copilotCLILoginIn is the account the Copilot CLI whose settings are in
// dir is signed in to, with its token: from its config.json, else from
// secret (the keychain), when given.
func copilotCLILoginIn(dir string, secret func(string) string) (copilotApp, bool) {
raw, err := readAccountFile(filepath.Join(dir, "config.json"))
if err != nil {
return copilotApp{}, false
}
var cfg struct {
Last *copilotCLIUser `json:"lastLoggedInUser"`
Users []copilotCLIUser `json:"loggedInUsers"`
Tokens map[string]string `json:"copilotTokens"`
}
if json.Unmarshal(jsonc.ToJSON(raw), &cfg) != nil {
return copilotApp{}, false
}
users := cfg.Users
if cfg.Last != nil {
users = append([]copilotCLIUser{*cfg.Last}, users...)
}
// a github.com account first, as before; then one an enterprise's
// `copilot login --host <name>.ghe.com` signed in (#723). A GitHub
// Enterprise Server's own host is left out: its API isn't GHE.com's.
for _, ghe := range []bool{false, true} {
for _, u := range users {
host, ok := copilotHostOf(u.Host)
if u.Login == "" || !ok || (host != "") != ghe {
continue
}
key := "https://github.com:" + u.Login
if ghe {
key = strings.TrimSuffix(u.Host, "/") + ":" + u.Login
}
tok := cfg.Tokens[key]
if tok == "" && secret != nil {
tok = secret(key)
}
if tok != "" {
return copilotApp{User: u.Login, Token: tok, Host: host, cli: true}, true
}
}
}
return copilotApp{}, false
}
var copilotSecrets struct {
sync.Mutex
at map[string]time.Time
tok map[string]string
}
// copilotCLISecret reads the CLI's token from the keychain, once in a
// while: each read may ask the user to allow it.
var copilotCLISecret = func(account string) string {
if settings.AccountDiscoveryOff() {
return ""
}
c := &copilotSecrets
c.Lock()
defer c.Unlock()
if c.at == nil {
c.at, c.tok = map[string]time.Time{}, map[string]string{}
}
ttl := time.Hour
if c.tok[account] == "" {
ttl = 10 * time.Minute // denied or absent; don't ask again at once
}
if at, ok := c.at[account]; ok && time.Since(at) < ttl {
return c.tok[account]
}
var out []byte
switch runtime.GOOS {
case "darwin":
out, _ = proc.Command("security", "find-generic-password", "-s", "copilot-cli", "-a", account, "-w").Output()
case "linux":
if p, err := exec.LookPath("secret-tool"); err == nil {
out = []byte(copilotSecretTool(p, account))
}
}
c.at[account], c.tok[account] = time.Now(), string(bytes.TrimSpace(out))
return c.tok[account]
}
// copilotSecretWait bounds one secret-tool lookup: a keyring that waits on
// a prompt nobody answers would hold the sign-in that asked (#723).
var copilotSecretWait = 5 * time.Second
// copilotSecretTool is the CLI's token in the Secret Service, as
// secret-tool (at path) finds it. The CLI before 1.0 (keytar, libsecret)
// keyed it by service and account; 1.0's own keyring store
// (zbus-secret-service-keyring-store) by service and username, so both
// are asked (#723).
func copilotSecretTool(path, account string) string {
for _, attr := range []string{"account", "username"} {
ctx, cancel := context.WithTimeout(context.Background(), copilotSecretWait)
cmd := proc.CommandContext(ctx, path, "lookup", "service", "copilot-cli", attr, account)
cmd.WaitDelay = time.Second
out, _ := cmd.Output()
cancel()
if tok := strings.TrimSpace(string(out)); tok != "" {
return tok
}
}
return ""
}
// copilotDirect is the session a CLI token makes: the token itself, at the
// API its account is served from.
func copilotDirect(ctx context.Context, app copilotApp) (copilotSession, error) {
github := app.Token
copilotMu.Lock()
defer copilotMu.Unlock()
if s, ok := copilotSessions[github]; ok && time.Until(time.Unix(s.ExpiresAt, 0)) > 2*time.Minute {
return s, nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, copilotUserURL(app.Host), nil)
if err != nil {
return copilotSession{}, err
}
req.Header.Set("Authorization", "token "+github)
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return copilotSession{}, errors.New("Copilot sign-in: " + err.Error())
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
var u struct {
Endpoints struct {
API string `json:"api"`
} `json:"endpoints"`
}
if res.StatusCode != 200 || json.Unmarshal(b, &u) != nil {
// 401 is GitHub refusing the token itself; a 403 here can be an
// account without Copilot, and a 5xx is GitHub's own trouble
if res.StatusCode == http.StatusUnauthorized {
copilotRefuse(github, res.StatusCode)
}
return copilotSession{}, errors.New("the Copilot CLI's sign-in was refused (" + APIError(b, res.Status) + "); run `copilot login` again")
}
copilotRefusals.Lock()
delete(copilotRefusals.at, github)
delete(copilotRefusals.status, github)
copilotRefusals.Unlock()
s := copilotSession{Token: github, ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), direct: true}
s.Endpoints.API = u.Endpoints.API
copilotSessions[github] = s
return s, nil
}