* fix(proc): end what a CLI probe started, on its timeout and when magpie exits The probes that ask an agent's CLI something (claude auth status, cursor-agent about/models/status, the --version checks) ran through proc.CommandContext, which on its timeout kills only the command itself. A CLI that is a script (a version manager's wrapper, a shim) left what it had started running, adopted by init; and a probe still asking when magpie exited (a one-shot command, an update, a restart) was left whole, with nothing to end it. With Omarchy's mise wrappers stuck in their exec loop (omacom/omarchy#7234) that was five processes holding about half a core each for up to six hours. proc.ProbeContext gives such a probe a session of its own on Unix, as StartTree does, and its context ending kills the whole group. Probes still running are listed, and proc.EndProbes kills them when magpie exits (after run in main) or puts a new version in its place (update.Reexec). On Windows a probe is killed alone, as before, a job being joined only once the command has started. TestProbeTimeoutEndsWhatItStarted and TestEndProbes fail without the change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(proc): end probes on a terminal's signals and on a Mac's quit Review of the first change: a probe leading its own session no longer gets the Ctrl+C, hang-up or SIGTERM sent to magpie's terminal or service, and magpie ending on the signal never reached EndProbes, so the probe was left to init where before it died with magpie. main now catches SIGINT, SIGTERM and SIGHUP, ends the probes and exits as the signal would have (128+n). A signal magpie was started ignoring (nohup, a background job) stays ignored. The account sign-in and plugin commands, which end themselves on Ctrl+C, go through interruptContext and are left to do so. On a Mac the desktop app's quit ([NSApp terminate:], also the restart to update) exits without returning to main, so OnShutdown ends the probes. TestProbeTimeoutEndsWhatItStarted ended its probe on a 500ms timeout, which on a Mac could come before the script had written its child's pid (6 of 10 runs failed in review). It now ends the context once that pid is read, the same Cancel path. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: let the app and the TUI quit on a signal their own way Review of the signal handling: endProbesOnSignal exited ahead of Wails and bubbletea, which quit on SIGINT and SIGTERM themselves. `magpie tray` exited 143 without OnShutdown (no downloaded update installed, and sessions.Saved skipped in main), and `magpie tui` left the terminal on its alternate screen with the cursor hidden. The app's and the TUI's entry points now hand the signals back (ownSignals): the app's OnShutdown ends the probes, and the TUI comes back to main, which ends them too. A one-shot command keeps the handler. TestOwnSignalsHandsThemBack fails without the change (magpie exited 143 before the command could quit its own way); TestSignalExits keeps the one-shot behavior. childPid waited 3s for a script just written to start its child, which a busy Mac can exceed (2 of 3 full runs failed in review). It waits 30s now and, should the probe end first, says the probe's error rather than "the script started nothing". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep SIGHUP for the app and the TUI, and die of the signal ownSignals handed SIGHUP back along with SIGINT and SIGTERM, but neither Wails nor bubbletea handles it: the terminal closing under the TUI or an app started from a shell ended magpie on the spot, and its probes, in a session of their own, out of the hang-up's reach, kept running (before this PR they were in the terminal's group and ended with it). SIGHUP now stays with endProbesOnSignal. A tray under a pty whose terminal closes left 2 processes before, none now. The handler asked whether a command was ending itself on Ctrl+C only after EndProbes, which can take up to a second; a sign-in done in the meantime got magpie ended in the middle of its own cleanup. It is asked first. It exited 128+n, which a shell takes for a child that handled the signal: a loop running magpie went on to the next run on Ctrl+C. It now dies of the signal (handling reset, the signal sent again); Windows, which can't send one, still exits with the code. agentProbe and agentCommand share withProxy; the Windows probeGroup comment no longer says EndProbes ends what a shim started. TestOwnSignalsKeepsHangUp and TestInterruptWhileEndingProbes fail without the change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: hand signals to the TUI and the app only once they listen Review: runTUI handed SIGINT and SIGTERM back before tui.Run, whose newModel asks agents' CLIs (claude auth status, up to 5s) before bubbletea listens for signals. Ctrl+C, SIGTERM or SIGINT while it loaded ended magpie by Go's default and left the probe and its child running. tui.Run now takes ready, called once the model is made, and runTUI passes ownSignals. The app had the same window: runGUI handed them back before gui.Run, which starts the backend (probes included) before Wails' Run starts listening. ownSignals is now gui.Started, called on ApplicationStarted, which Wails emits after its signal handler is set up. A tray sent SIGTERM 0.05s after starting, a probe under way, left 2 processes before and none now; one sent it once started still quits through OnShutdown (exit 0). TestTUIKeepsSignalsWhileLoading fails without the change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
681 lines
20 KiB
Go
681 lines
20 KiB
Go
package provider
|
|
|
|
// A Grok subscription (SuperGrok, X Premium+) is served straight from the
|
|
// backend xAI's Grok Build CLI talks to, OpenAI's Responses API at
|
|
// cli-chat-proxy.grok.com, with the CLI's sign-in. Here is who the CLI is
|
|
// signed in to, the models it offers, the sign-in, which is the CLI's own
|
|
// `login`, and the requests' signing.
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/netproxy"
|
|
"github.com/yetone/magpie/internal/proc"
|
|
)
|
|
|
|
// GrokExecutable finds the Grok Build CLI; a var so tests can fake it.
|
|
var GrokExecutable = func() string {
|
|
home, _ := os.UserHomeDir()
|
|
path := append(filepath.SplitList(os.Getenv("PATH")), registryPath()...)
|
|
for _, c := range grokCandidates(runtime.GOOS, home, GrokHome(), os.Getenv("GROK_BIN_DIR"), path) {
|
|
if isFile(c.path) && (c.own || isGrokBuild(c.path)) {
|
|
return c.path
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// grokCandidate is a place the CLI may be; own when only its installer
|
|
// puts a grok there.
|
|
type grokCandidate struct {
|
|
path string
|
|
own bool
|
|
}
|
|
|
|
// grokCandidates are the places to look for the CLI, first to last: the
|
|
// installer's bin (GROK_BIN_DIR, else ~/.grok/bin), each folder on PATH,
|
|
// then ~/.local/bin. On Windows it is grok.exe — looking for a bare grok
|
|
// there missed ~/.grok/bin, and a grok.cmd npm put on PATH first hid it
|
|
// (#180). path is the process' PATH and, on Windows, the registry's, which
|
|
// has what was installed since magpie started.
|
|
func grokCandidates(goos, home, grokHome, binDir string, path []string) []grokCandidate {
|
|
name := "grok"
|
|
if goos == "windows" {
|
|
name = "grok.exe"
|
|
}
|
|
var out []grokCandidate
|
|
seen := map[string]bool{}
|
|
add := func(dir string, own bool) {
|
|
if dir == "" || !filepath.IsAbs(dir) {
|
|
return
|
|
}
|
|
p := filepath.Join(dir, name)
|
|
k := p
|
|
if goos == "windows" {
|
|
k = strings.ToLower(p)
|
|
}
|
|
if !seen[k] {
|
|
seen[k] = true
|
|
out = append(out, grokCandidate{p, own})
|
|
}
|
|
}
|
|
add(binDir, true)
|
|
add(filepath.Join(grokHome, "bin"), true)
|
|
if home != "" {
|
|
// the installer puts it under ~/.grok whatever GROK_HOME says
|
|
add(filepath.Join(home, ".grok", "bin"), true)
|
|
}
|
|
for _, d := range path {
|
|
add(strings.TrimSpace(d), false)
|
|
}
|
|
if home != "" {
|
|
add(filepath.Join(home, ".local", "bin"), false)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func isFile(p string) bool {
|
|
st, err := os.Stat(p)
|
|
return err == nil && !st.IsDir()
|
|
}
|
|
|
|
// isGrokBuild tells xAI's grok from any other program by that name: its
|
|
// installer keeps it under the grok home.
|
|
func isGrokBuild(path string) bool {
|
|
real, err := filepath.EvalSymlinks(path)
|
|
if err != nil {
|
|
// Windows can't resolve some real paths (a subst drive, a folder
|
|
// OneDrive keeps); the path itself still says where it is
|
|
real = path
|
|
}
|
|
return strings.Contains(strings.ToLower(filepath.ToSlash(real)), "/.grok/")
|
|
}
|
|
|
|
// GrokHome is where the CLI keeps its sign-in and settings.
|
|
func GrokHome() string {
|
|
if h := os.Getenv("GROK_HOME"); h != "" {
|
|
return h
|
|
}
|
|
home, _ := os.UserHomeDir()
|
|
return filepath.Join(home, ".grok")
|
|
}
|
|
|
|
// grokCredential is the CLI's sign-in, as its auth.json keeps it.
|
|
type grokCredential struct {
|
|
Key string `json:"key"`
|
|
Email string `json:"email"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
Issuer string `json:"oidc_issuer"`
|
|
}
|
|
|
|
// readGrokCredential reads the sign-in the CLI keeps in its home. magpie
|
|
// only reads it: the CLI refreshes it with a token that changes each time.
|
|
func readGrokCredential(home string) (grokCredential, bool) {
|
|
var all map[string]grokCredential
|
|
if !readJSON(filepath.Join(home, "auth.json"), &all) {
|
|
return grokCredential{}, false
|
|
}
|
|
keys := make([]string, 0, len(all))
|
|
for k := range all {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
for _, k := range keys {
|
|
if c := all[k]; c.Key != "" {
|
|
return c, true
|
|
}
|
|
}
|
|
return grokCredential{}, false
|
|
}
|
|
|
|
func grokAccount() (Provider, bool) {
|
|
if GrokExecutable() == "" {
|
|
return Provider{}, false
|
|
}
|
|
ls := grokLogins()
|
|
if len(ls) == 0 {
|
|
return Provider{}, false
|
|
}
|
|
home := ls[0].Home
|
|
acct := &Account{Agent: "grok", User: ls[0].User, Plan: ls[0].Plan, Home: home}
|
|
if home == GrokHome() {
|
|
acct.Home = "" // the CLI's own, wherever it is
|
|
}
|
|
grokSigned(acct, home)
|
|
acct.body = grokBody
|
|
acct.models = func() []catalog.Model { return []catalog.Model{{ID: "grok-4.7", Name: "Grok 4.7"}} }
|
|
acct.fetch = func(ctx context.Context) ([]catalog.Model, error) {
|
|
ms, err := grokModels(ctx, acct.sign)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return ms, catalog.SaveLive("grok", GrokBase, ms)
|
|
}
|
|
return Provider{ID: "grok", Name: "Grok (SuperGrok)", Icon: "xai", Website: "https://x.ai/cli", Responses: GrokBase, Account: acct}, true
|
|
}
|
|
|
|
// grokSigned has the account's requests signed with the sign-in in home.
|
|
func grokSigned(acct *Account, home string) {
|
|
acct.sign = func(ctx context.Context, req *http.Request, body []byte) error {
|
|
c, err := grokAccessToken(home, GrokExecutable(), false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
grokHeaders(req, c.Key)
|
|
if m := bodyModel(body); m != "" {
|
|
req.Header.Set("x-grok-model-override", m)
|
|
}
|
|
var v struct {
|
|
Key string `json:"prompt_cache_key"`
|
|
}
|
|
if json.Unmarshal(body, &v) == nil && v.Key != "" {
|
|
req.Header.Set("x-grok-conv-id", v.Key)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// grokTools are the tool types Grok's backend takes; it turns the whole
|
|
// request away over another, as over Codex's freeform apply_patch (custom)
|
|
// or a namespace, which groups its sub-agent tools. A namespace's functions
|
|
// go as functions of their own (grokFlat).
|
|
var grokTools = map[string]bool{"function": true, "web_search": true, "x_search": true, "image_generation": true,
|
|
"collections_search": true, "file_search": true, "code_execution": true, "code_interpreter": true,
|
|
"mcp": true, "shell": true, "tool_search": true}
|
|
|
|
// grokBody leaves out the tools Grok's backend doesn't take, as a backend
|
|
// magpie translates for goes without them: Codex, without apply_patch,
|
|
// edits files through its shell. Codex's web_search says whether it may
|
|
// reach the live web, which Grok's doesn't take either; it searches live.
|
|
// And Codex hands reasoning back with "content": null, which the backend
|
|
// can't read the encrypted reasoning beside ("Could not decode the
|
|
// compaction blob"), so a null content goes. A namespace's functions, as
|
|
// collaboration's spawn_agent, go flat (collaboration__spawn_agent), and so
|
|
// do the calls to them handed back and a tool_choice naming one (#404).
|
|
// A tool_choice with no tools
|
|
// left goes too: the backend turns the request away over it ("A
|
|
// tool_choice was set on the request but no tools were specified"), as it
|
|
// would Codex's compaction summary, sent without tools (#378).
|
|
func grokBody(body []byte) []byte {
|
|
if !bytes.Contains(body, []byte(`"tools"`)) && !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`"tool_choice"`)) && !bytes.Contains(body, []byte(`"namespace"`)) {
|
|
return body
|
|
}
|
|
dec := json.NewDecoder(bytes.NewReader(body))
|
|
dec.UseNumber()
|
|
var m map[string]any
|
|
if dec.Decode(&m) != nil || m == nil {
|
|
return body
|
|
}
|
|
dirty := false
|
|
if tools, ok := m["tools"].([]any); ok {
|
|
kept := tools[:0:0]
|
|
for _, t := range tools {
|
|
if tm, ok := t.(map[string]any); ok {
|
|
ty, _ := tm["type"].(string)
|
|
if ty == "namespace" {
|
|
dirty = true
|
|
kept = append(kept, grokFlat(tm)...)
|
|
continue
|
|
}
|
|
if !grokTools[ty] {
|
|
dirty = true
|
|
continue
|
|
}
|
|
if _, ok := tm["external_web_access"]; ok {
|
|
delete(tm, "external_web_access")
|
|
dirty = true
|
|
}
|
|
}
|
|
kept = append(kept, t)
|
|
}
|
|
m["tools"] = kept
|
|
if tc, ok := m["tool_choice"].(map[string]any); ok {
|
|
if flatCall(tc) {
|
|
dirty = true
|
|
}
|
|
if ty, _ := tc["type"].(string); !grokTools[ty] {
|
|
delete(m, "tool_choice")
|
|
dirty = true
|
|
}
|
|
}
|
|
}
|
|
if tools, _ := m["tools"].([]any); len(tools) == 0 {
|
|
if _, ok := m["tool_choice"]; ok {
|
|
delete(m, "tool_choice")
|
|
dirty = true
|
|
}
|
|
}
|
|
input, _ := m["input"].([]any)
|
|
for _, it := range input {
|
|
if im, ok := it.(map[string]any); ok && flatCall(im) {
|
|
dirty = true
|
|
}
|
|
if im, ok := it.(map[string]any); ok && im["type"] == "reasoning" {
|
|
if c, ok := im["content"]; ok && c == nil {
|
|
delete(im, "content")
|
|
dirty = true
|
|
}
|
|
}
|
|
}
|
|
if !dirty {
|
|
return body
|
|
}
|
|
b, err := json.Marshal(m)
|
|
if err != nil {
|
|
return body
|
|
}
|
|
return b
|
|
}
|
|
|
|
// liteNamespace is the namespace Codex's Responses Lite groups its own
|
|
// functions in, which Codex reads as none at all.
|
|
const liteNamespace = "functions"
|
|
|
|
// FlatName is the name a namespaced tool is offered to a model under, which
|
|
// takes one flat name: namespace__name, as Codex names an MCP server's tools.
|
|
// A name longer than the 64 characters APIs allow is cut and made unique by
|
|
// a hash of the whole.
|
|
func FlatName(namespace, name string) string {
|
|
flat := namespace + "__" + name
|
|
if len(flat) <= 64 {
|
|
return flat
|
|
}
|
|
sum := sha256.Sum256([]byte(namespace + "\x00" + name))
|
|
return flat[:55] + "_" + hex.EncodeToString(sum[:4])
|
|
}
|
|
|
|
// grokFlat is a namespace's functions, each under its flat name; what else
|
|
// it holds, a freeform tool, Grok's backend wouldn't take either.
|
|
func grokFlat(ns map[string]any) []any {
|
|
space, _ := ns["name"].(string)
|
|
nested, _ := ns["tools"].([]any)
|
|
var out []any
|
|
for _, n := range nested {
|
|
nm, _ := n.(map[string]any)
|
|
name, _ := nm["name"].(string)
|
|
if nm == nil || nm["type"] != "function" || name == "" {
|
|
continue
|
|
}
|
|
if space != "" && space != liteNamespace {
|
|
nm["name"] = FlatName(space, name)
|
|
}
|
|
out = append(out, nm)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// flatCall names a call to a namespaced tool, or a tool_choice of one, by
|
|
// the flat name it was offered under, and reports whether it was one.
|
|
func flatCall(it map[string]any) bool {
|
|
space, ok := it["namespace"].(string)
|
|
if !ok {
|
|
return false
|
|
}
|
|
delete(it, "namespace")
|
|
if name, _ := it["name"].(string); name != "" && space != "" && space != liteNamespace {
|
|
it["name"] = FlatName(space, name)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// grokHeaders say a request comes from the Grok CLI, which the backend
|
|
// wants to know the version of: without it the CLI is "outdated".
|
|
func grokHeaders(req *http.Request, token string) {
|
|
v := grokVersion()
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
req.Header.Set("x-grok-client-version", v)
|
|
req.Header.Set("x-xai-token-auth", "xai-grok-cli")
|
|
req.Header.Set("x-grok-client-identifier", "grok-shell")
|
|
req.Header.Set("x-grok-client-mode", "headless")
|
|
goos, arch := runtime.GOOS, runtime.GOARCH
|
|
if goos == "darwin" {
|
|
goos = "macos"
|
|
}
|
|
switch arch {
|
|
case "arm64":
|
|
arch = "aarch64"
|
|
case "amd64":
|
|
arch = "x86_64"
|
|
}
|
|
req.Header.Set("User-Agent", "grok-shell/"+v+" ("+goos+"; "+arch+")")
|
|
}
|
|
|
|
// grokClientVersion is the Grok CLI version magpie says it is, unless the
|
|
// installed one is newer.
|
|
const grokClientVersion = "1.0.41"
|
|
|
|
var grokVersionCache struct {
|
|
sync.Mutex
|
|
v string
|
|
at time.Time
|
|
}
|
|
|
|
var grokSemver = regexp.MustCompile(`\d+\.\d+\.\d+`)
|
|
|
|
func grokVersion() string {
|
|
grokVersionCache.Lock()
|
|
defer grokVersionCache.Unlock()
|
|
if time.Since(grokVersionCache.at) < 10*time.Minute {
|
|
return grokVersionCache.v
|
|
}
|
|
v := grokClientVersion
|
|
if exe := GrokExecutable(); exe != "" {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
if out, err := proc.ProbeContext(ctx, exe, "--version").Output(); err == nil { // "grok 1.0.41 (4220f3b224a6)"
|
|
if c := grokSemver.FindString(string(out)); c != "" && compareClaudeVersion(c, v) > 0 {
|
|
v = c
|
|
}
|
|
}
|
|
cancel()
|
|
}
|
|
grokVersionCache.v, grokVersionCache.at = v, time.Now()
|
|
return v
|
|
}
|
|
|
|
// grokModels lists what the account can use, with each model's context
|
|
// window and efforts, as the CLI's backend lists them.
|
|
func grokModels(ctx context.Context, sign func(context.Context, *http.Request, []byte) error) ([]catalog.Model, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, GrokBase+"/models", nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := sign(ctx, req, nil); err != nil {
|
|
return nil, err
|
|
}
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, errorf("Grok models: %s", APIError(b, res.Status))
|
|
}
|
|
ms := parseGrokModels(b)
|
|
if len(ms) == 0 {
|
|
return nil, errorf("Grok listed no models")
|
|
}
|
|
return ms, nil
|
|
}
|
|
|
|
func parseGrokModels(b []byte) []catalog.Model {
|
|
var v struct {
|
|
Data []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Context int `json:"context_window"`
|
|
Backend string `json:"api_backend"`
|
|
Efforts []struct {
|
|
Value string `json:"value"`
|
|
} `json:"reasoning_efforts"`
|
|
} `json:"data"`
|
|
}
|
|
if json.Unmarshal(b, &v) != nil {
|
|
return nil
|
|
}
|
|
var ms []catalog.Model
|
|
for _, d := range v.Data {
|
|
if d.ID == "" || (d.Backend != "" && d.Backend != "responses") {
|
|
continue
|
|
}
|
|
m := catalog.Model{ID: d.ID, Name: d.Name, Context: d.Context, Images: true, APIs: []string{"responses"}}
|
|
if m.Name == "" {
|
|
m.Name = d.ID
|
|
}
|
|
// listed hardest first; kept easiest first, as the others are
|
|
for i := len(d.Efforts) - 1; i >= 0; i-- {
|
|
if e := d.Efforts[i].Value; e != "" {
|
|
m.Efforts = append(m.Efforts, e)
|
|
}
|
|
}
|
|
ms = append(ms, m)
|
|
}
|
|
return ms
|
|
}
|
|
|
|
// grokRefreshMargin is how close to its expiry a borrowed token has the CLI
|
|
// refresh it first.
|
|
const grokRefreshMargin = 5 * time.Minute
|
|
|
|
var grokRefresh sync.Mutex
|
|
|
|
// grokAccessToken is the CLI's sign-in, with a token still good. One about
|
|
// to expire is first refreshed by the CLI in its own home: a `grok models`
|
|
// there renews it the way any use of the CLI does; so is one a run has
|
|
// found expired.
|
|
func grokAccessToken(home, binary string, expired bool) (grokCredential, error) {
|
|
c, ok := readGrokCredential(home)
|
|
if ok && (expired || time.Until(c.ExpiresAt) < grokRefreshMargin) && binary != "" {
|
|
grokRefresh.Lock()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
cmd := proc.CommandContext(ctx, binary, "models")
|
|
cmd.Dir = filepath.Dir(home)
|
|
cmd.Env = netproxy.Env(grokOwnEnv(os.Environ(), home))
|
|
_ = cmd.Run()
|
|
cancel()
|
|
grokRefresh.Unlock()
|
|
c, ok = readGrokCredential(home)
|
|
}
|
|
if !ok {
|
|
return c, errorf("Grok is not signed in; run `grok login`")
|
|
}
|
|
if !c.ExpiresAt.IsZero() && time.Until(c.ExpiresAt) <= 0 {
|
|
return c, errorf("Grok's sign-in has expired; run `grok login`")
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// grokOwnEnv runs the CLI as the user runs it, in its own home.
|
|
func grokOwnEnv(env []string, home string) []string {
|
|
out := make([]string, 0, len(env)+1)
|
|
for _, e := range env {
|
|
k, _, _ := strings.Cut(e, "=")
|
|
switch strings.ToUpper(k) {
|
|
case "GROK_HOME", "GROK_AUTH_PROVIDER_COMMAND", "GROK_AUTH_EXPIRED":
|
|
continue
|
|
}
|
|
out = append(out, e)
|
|
}
|
|
return append(out, "GROK_HOME="+home)
|
|
}
|
|
|
|
// startGrokSignIn runs `grok login` with its device code, hands its link to
|
|
// the window, and finishes when the CLI says the account is in. With the
|
|
// CLI signed in already, a further account signs in in a home of magpie's,
|
|
// so the CLI's own sign-in stays as it is.
|
|
func startGrokSignIn(s *signInFlow) error {
|
|
path := GrokExecutable()
|
|
if path == "" {
|
|
c, _ := cliFor("grok")
|
|
manual := c.sh
|
|
if runtime.GOOS == "windows" {
|
|
manual = c.ps
|
|
}
|
|
return errorf("install Grok Build first: %s", manual)
|
|
}
|
|
if _, ok := readGrokCredential(GrokHome()); !ok {
|
|
return runCLISignIn(s, "grok login", nil, true, nil, func() (string, string, bool) {
|
|
c, ok := readGrokCredential(GrokHome())
|
|
return c.Email, "", ok
|
|
}, nil, path, "login", "--device-auth")
|
|
}
|
|
home, err := newGrokHome()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = runCLISignIn(s, "grok login", grokOwnEnv(os.Environ(), home), false, func() { removeGrokHome(home) }, func() (string, string, bool) {
|
|
user, err := addGrokLogin(home)
|
|
return user, "", err == nil
|
|
}, nil, path, "login", "--device-auth")
|
|
if err != nil {
|
|
removeGrokHome(home)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// agentCommand runs an agent's CLI with magpie's proxy.
|
|
func agentCommand(ctx context.Context, path string, args ...string) *exec.Cmd {
|
|
return withProxy(proc.CommandContext(ctx, path, args...))
|
|
}
|
|
|
|
// agentProbe is agentCommand for asking the CLI something (proc.ProbeContext).
|
|
func agentProbe(ctx context.Context, path string, args ...string) *exec.Cmd {
|
|
return withProxy(proc.ProbeContext(ctx, path, args...))
|
|
}
|
|
|
|
func withProxy(cmd *exec.Cmd) *exec.Cmd {
|
|
cmd.Env = netproxy.Env(nil)
|
|
return cmd
|
|
}
|
|
|
|
// runCLISignIn runs an agent's own login command, hands the first link it
|
|
// prints to the window, and finishes when the command does and identity
|
|
// says who is signed in. using says whether the agent now uses that
|
|
// account; failed, when there is one, undoes what a sign-in that did not
|
|
// finish left behind. whole, when there is one, says a link has all it
|
|
// needs: one that hasn't is the start of a link the CLI wrapped, and the
|
|
// lines after it that are nothing but more of it are joined on.
|
|
func runCLISignIn(s *signInFlow, what string, env []string, using bool, failed func(), identity func() (user, plan string, ok bool), whole func(link string) bool, path string, args ...string) error {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cmd := proc.CommandContext(ctx, path, args...)
|
|
cmd.Dir, _ = os.UserHomeDir()
|
|
cmd.Env = netproxy.Env(env)
|
|
out, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
cancel()
|
|
return err
|
|
}
|
|
cmd.Stderr = cmd.Stdout
|
|
if err := cmd.Start(); err != nil {
|
|
cancel()
|
|
return err
|
|
}
|
|
s.mu.Lock()
|
|
s.stop = cancel
|
|
s.mu.Unlock()
|
|
got := make(chan string, 1)
|
|
var partial struct {
|
|
sync.Mutex
|
|
link string
|
|
}
|
|
go func() {
|
|
rd := bufio.NewReader(out)
|
|
sent := false
|
|
link := ""
|
|
send := func() {
|
|
if !sent && link != "" {
|
|
sent = true
|
|
got <- link
|
|
}
|
|
}
|
|
var tail []string
|
|
for {
|
|
raw, rerr := rd.ReadString('\n')
|
|
line := ansi.ReplaceAllString(strings.TrimRight(raw, "\r\n"), "")
|
|
switch {
|
|
case sent:
|
|
case link == "":
|
|
link = cursorLoginURL.FindString(line)
|
|
case linkRest.MatchString(strings.TrimSpace(line)) && (!whole(link) || queryRest.MatchString(strings.TrimSpace(line))):
|
|
// a whole link takes only more of its query, not "Waiting..." printed after it
|
|
link += strings.TrimSpace(line)
|
|
default:
|
|
send() // what came after it isn't more of it
|
|
}
|
|
// a whole link is handed on once what came with it is read,
|
|
// so the rest of one wrapped after its last param joins too
|
|
if whole == nil || whole(link) && rd.Buffered() == 0 {
|
|
send()
|
|
}
|
|
if !sent {
|
|
partial.Lock()
|
|
partial.link = link
|
|
partial.Unlock()
|
|
}
|
|
if strings.TrimSpace(line) != "" {
|
|
tail = append(tail, strings.TrimSpace(line))
|
|
}
|
|
if rerr != nil {
|
|
break
|
|
}
|
|
}
|
|
send()
|
|
if !sent {
|
|
close(got)
|
|
}
|
|
err := cmd.Wait()
|
|
cancel()
|
|
forgetAccountCaches()
|
|
if err == nil {
|
|
if user, plan, ok := identity(); ok {
|
|
s.finish(SignInState{State: "done", User: user, Plan: plan, Using: using})
|
|
return
|
|
}
|
|
}
|
|
if failed != nil {
|
|
failed()
|
|
}
|
|
msg := what + " didn't finish"
|
|
if n := len(tail); n > 0 {
|
|
msg = tail[n-1]
|
|
}
|
|
s.finish(SignInState{State: "failed", Error: msg})
|
|
}()
|
|
var u string
|
|
select {
|
|
case l, ok := <-got:
|
|
if !ok {
|
|
return fmt.Errorf("%s gave no link to open", what)
|
|
}
|
|
u = l
|
|
case <-time.After(linkWait):
|
|
// a link that never came whole is still the one there is
|
|
partial.Lock()
|
|
u = partial.link
|
|
partial.Unlock()
|
|
if u == "" {
|
|
cancel()
|
|
return fmt.Errorf("%s gave no link to open", what)
|
|
}
|
|
}
|
|
s.mu.Lock()
|
|
s.st.URL = u
|
|
s.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// linkWait is how long a login command has to print its link.
|
|
var linkWait = 30 * time.Second
|
|
|
|
// linkRest is a line that is nothing but more of a link: no spaces, only
|
|
// what a URL holds.
|
|
var linkRest = regexp.MustCompile(`^[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+$`)
|
|
|
|
// queryRest is what may still follow a link that already has its challenge
|
|
// and uuid: the rest of a value, or more params.
|
|
var queryRest = regexp.MustCompile(`^[A-Za-z0-9\-_%&=]+$`)
|
|
|
|
// GrokUser is who the grok with this home is signed in to.
|
|
func GrokUser(home string) (string, bool) {
|
|
c, ok := readGrokCredential(home)
|
|
return c.Email, ok
|
|
}
|