agy takes magpie's gateway, key (GEMINI_API_KEY, GOOGLE_GEMINI_BASE_URL)
and --model only from how it is started, so a user on magpie had to copy
the launch command at every start (bestony on Discord). Now:
- magpie agy run [args…] execs the real agy with the env and --model when
agy's settings.json is on magpie's model (a --model/-model the user
gives wins), and runs agy untouched otherwise. On Windows agy is a child
through proc and its exit code is passed through. It refuses when "agy"
on PATH resolves to magpie itself. magpie agy env prints what run adds
(PowerShell's function reads it, since the desktop exe has no console).
- update.ShellFunction puts a function named agy in a marked block
(# >>> magpie agy >>> … # <<< magpie agy <<<) of each shell profile
cliShells finds: .zshrc (ZDOTDIR), the bash profile a terminal reads
(.bash_profile, or .bash_login/.profile on macOS when that is missing),
config.fish once its folder exists, and the PowerShell 7 / Windows
PowerShell profiles where the execution policy runs them. Only the block
is written, in place, temp-and-rename, CRLF and BOM kept; a profile that
can't be read is not written; only files inside the home are. The
function falls back to `command agy` when the magpie it names is gone.
- Set to a magpie model writes the block, stepping out takes it out (the
file comes back byte for byte), and Sync at start writes it for users
already wired.
- Notice, Launch tooltip and the connect panel say plain agy works in a
new terminal, with the command for a terminal open now. Strings in
i18n.js for zh, zh-TW, ja, de. docs/reference.md and
docs/subsystems/agent-wiring.md updated.
Run at this head (base a3d4f8c5c, origin/main just fetched):
- go test -tags nogui -count=1 -timeout 45m ./internal/agent/...
./internal/cli/... ./internal/update/... ./internal/gui/...
./internal/proc/... : all ok.
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./... : clean. gofmt -l on the changed files: none.
- GUI (node --test, chromium + webkit): agy-launch, cursor-local-launch,
agent-connect, agent-connect-no-models, agent-connect-all-hidden,
agent-connected-unfolded, connect-address-kept, connect-snippet-shell,
agent-notice-lang, agent-leave-magpie, agent-disconnect, copy-command,
i18n-keys, gui-de, gui-ja, gui-zh-tw: 0 fail. Not the whole GUI suite.
- Real try, sandbox HOME under the scratchpad, nogui build, fake agy on
PATH printing its args and the two env vars, env -i:
magpie provider add deepseek + magpie agy deepseek/deepseek-chat wrote
the block after the user's two .zshrc lines; `zsh -i -c 'agy -p hi'` got
--model magpie/deepseek/deepseek-chat, GEMINI_API_KEY=magpie-agy and
GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:38712; `agy --model x` kept x;
wiring again left .zshrc's mtime alone and added .bash_profile once it
existed, and `bash -l -i -c 'agy -p hi'` got the same; `magpie agy env x`
refused; magpie agy default took both blocks out, .zshrc equal to the
original, and plain agy ran with no env and no --model.
Broken by hand, each red, then restored:
- no fnInHome check: TestShellFunction, TestShellProfiles red.
- block appended instead of replaced in place: TestShellFunction red.
- unreadable profile treated as empty: TestShellFunction red.
- blank line before the block left on removal: TestShellFunction,
TestWithFnBlock red.
- --model always added: TestAgyRun red.
- Sync without agyShell: TestAgyShell red. Stepping out without
agyShell(false): TestAgyShell red.
- app.js typed row off, typed tooltip off: agy-launch 4 of 10 red each.
Not tried: PowerShell on Windows for real (vet only); WSL; a user's own
`alias agy` (an alias beats the function); a terminal already open needs
the copied command; macOS bash started non-login reads .bashrc, which
isn't written; a Documents folder redirected outside the profile isn't
written.
233 lines
6.4 KiB
Go
233 lines
6.4 KiB
Go
package update
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/yetone/magpie/internal/edit"
|
|
)
|
|
|
|
// A command an agent is typed by, given to it by magpie: agy takes
|
|
// magpie's gateway, its key and the model only from how it is started
|
|
// (agent/agy.go), so magpie puts a function named agy in the profile of
|
|
// each shell the user has, which starts it through this magpie (bestony on
|
|
// Discord: no command to copy at each start). The function sits in a
|
|
// block of its own between two marked lines, which is all magpie ever
|
|
// writes or takes out of the profile; the rest of the file is the user's.
|
|
//
|
|
// The shells are those ReadCLI asks about: zsh (its .zshrc in ZDOTDIR when
|
|
// that is set), bash (the file a terminal's bash reads) and fish
|
|
// (config.fish) on macOS and Linux, PowerShell 7 and Windows PowerShell on
|
|
// Windows, each only where its execution policy runs a profile. A profile
|
|
// that isn't there yet is made only for the shell a terminal opens, and
|
|
// only a profile inside the home is written, so a test's temporary home
|
|
// keeps it from the real one.
|
|
|
|
// ShellBody is a function's text for one shell: "posix" (zsh, bash),
|
|
// "fish" or "powershell"; prog is this magpie, by a path that stays put.
|
|
type ShellBody func(kind, prog string) string
|
|
|
|
// fnProfile is one shell's profile a function goes in.
|
|
type fnProfile struct {
|
|
Kind string // posix, fish, powershell
|
|
Path string
|
|
Create bool // made when it isn't there: the shell a terminal opens
|
|
}
|
|
|
|
// What the shell functions ask the system; tests set them.
|
|
var (
|
|
fnProfiles = shellProfiles
|
|
fnHome = func() string {
|
|
if runtime.GOOS == "windows" {
|
|
return os.Getenv("USERPROFILE")
|
|
}
|
|
return os.Getenv("HOME")
|
|
}
|
|
)
|
|
|
|
var fnMu sync.Mutex
|
|
|
|
func fnOpen(name string) string { return "# >>> magpie " + name + " >>>" }
|
|
func fnClose(name string) string { return "# <<< magpie " + name + " <<<" }
|
|
|
|
// ShellFunction puts the function name, as body gives it for each shell,
|
|
// in the profile of every shell the user has, or brings one there up to
|
|
// date. It says the profiles that have it now. A profile that can't be
|
|
// read is left as it is: what it holds is unknown.
|
|
func ShellFunction(name string, body ShellBody) ([]string, error) {
|
|
prog, err := cliExe()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
fnMu.Lock()
|
|
defer fnMu.Unlock()
|
|
var in []string
|
|
var errs []error
|
|
for _, p := range fnProfiles() {
|
|
if !fnInHome(p.Path) {
|
|
continue
|
|
}
|
|
ok, err := setFnBlock(p, name, strings.TrimRight(body(p.Kind, prog), "\n"))
|
|
if err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
if ok {
|
|
in = append(in, p.Path)
|
|
}
|
|
}
|
|
return in, errors.Join(errs...)
|
|
}
|
|
|
|
// DropShellFunction takes the function name out of every profile magpie
|
|
// put it in.
|
|
func DropShellFunction(name string) error {
|
|
fnMu.Lock()
|
|
defer fnMu.Unlock()
|
|
var errs []error
|
|
for _, p := range fnProfiles() {
|
|
if !fnInHome(p.Path) {
|
|
continue
|
|
}
|
|
if _, err := setFnBlock(p, name, ""); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// ShellFunctionIn says the profiles that hold the function name.
|
|
func ShellFunctionIn(name string) []string {
|
|
var in []string
|
|
for _, p := range fnProfiles() {
|
|
if !fnInHome(p.Path) {
|
|
continue
|
|
}
|
|
b, err := os.ReadFile(p.Path)
|
|
if err == nil && fnFind(lines(string(edit.TrimBOM(b))), name) >= 0 {
|
|
in = append(in, p.Path)
|
|
}
|
|
}
|
|
return in
|
|
}
|
|
|
|
// fnInHome says p is a file in the user's home.
|
|
func fnInHome(p string) bool {
|
|
h := fnHome()
|
|
if h == "" || !filepath.IsAbs(h) || !filepath.IsAbs(p) {
|
|
return false
|
|
}
|
|
rel, err := filepath.Rel(h, p)
|
|
return err == nil && rel != "." && !strings.HasPrefix(rel, "..")
|
|
}
|
|
|
|
// setFnBlock writes the function name's block in the profile p as body,
|
|
// or takes it out for ""; it says whether the block is there after.
|
|
func setFnBlock(p fnProfile, name, body string) (bool, error) {
|
|
b, err := os.ReadFile(p.Path)
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
if body == "" || !p.Create {
|
|
return false, nil
|
|
}
|
|
b, err = nil, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
text := string(edit.TrimBOM(b))
|
|
out := withFnBlock(text, name, body, p.Kind == "powershell")
|
|
if out == text {
|
|
return body != "", nil
|
|
}
|
|
if b == nil {
|
|
if err := os.MkdirAll(filepath.Dir(p.Path), 0o755); err != nil {
|
|
return false, err
|
|
}
|
|
// Windows PowerShell reads a profile without a byte order mark
|
|
// in the system's code page, which a path of the user's name
|
|
// outside ASCII would be garbled in
|
|
if p.Kind == "powershell" {
|
|
out = "\xef\xbb\xbf" + out
|
|
}
|
|
}
|
|
if err := edit.WriteAtomic(p.Path, []byte(out)); err != nil {
|
|
return false, err
|
|
}
|
|
return body != "", nil
|
|
}
|
|
|
|
func lines(text string) []string { return strings.Split(text, "\n") }
|
|
|
|
// fnFind is the line the function name's block opens on, -1 none.
|
|
func fnFind(ls []string, name string) int {
|
|
for i, l := range ls {
|
|
if strings.TrimRight(l, "\r") == fnOpen(name) {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// withFnBlock is the profile text with the function name's block as body,
|
|
// in place of the one it has or after the rest; body "" takes the block
|
|
// out, and the blank line put before it. The file's own line endings are
|
|
// kept; a new file gets CRLF for PowerShell.
|
|
func withFnBlock(text, name, body string, crlf bool) string {
|
|
nl := "\n"
|
|
if strings.Contains(text, "\r\n") || text == "" && crlf {
|
|
nl = "\r\n"
|
|
}
|
|
var block []string
|
|
if body != "" {
|
|
block = append(append([]string{fnOpen(name)}, lines(strings.ReplaceAll(body, "\r\n", "\n"))...), fnClose(name))
|
|
}
|
|
ls := lines(strings.ReplaceAll(text, "\r\n", "\n"))
|
|
if i := fnFind(ls, name); i >= 0 {
|
|
end := -1
|
|
for j := i + 1; j < len(ls); j++ {
|
|
if ls[j] == fnClose(name) {
|
|
end = j
|
|
break
|
|
}
|
|
}
|
|
if end < 0 {
|
|
// opened and never closed: someone cut it; the open line alone
|
|
// is magpie's
|
|
end = i
|
|
}
|
|
if body != "" {
|
|
out := append(append(clone(ls[:i]), block...), ls[end+1:]...)
|
|
return strings.Join(out, nl)
|
|
}
|
|
// out, with the blank line put before it
|
|
from := i
|
|
if i > 0 && ls[i-1] == "" {
|
|
from = i - 1
|
|
}
|
|
return strings.Join(append(clone(ls[:from]), ls[end+1:]...), nl)
|
|
}
|
|
if body == "" {
|
|
return text
|
|
}
|
|
var buf bytes.Buffer
|
|
buf.WriteString(text)
|
|
if text != "" {
|
|
if !strings.HasSuffix(text, "\n") {
|
|
buf.WriteString(nl)
|
|
}
|
|
buf.WriteString(nl)
|
|
}
|
|
buf.WriteString(strings.Join(block, nl) + nl)
|
|
return buf.String()
|
|
}
|
|
|
|
func clone(s []string) []string { return append([]string(nil), s...) }
|
|
|
|
// TildeHome is p with the home as ~, for a message.
|
|
func TildeHome(p string) string { return tildeHome(p) }
|