JasonLeeForOnly moved magpie to a new server with magpie backup / magpie
restore and lost every call's usage history: a backup file held the setup
only.
- backup.WithUsage puts usage.jsonl's whole lines (gzipped, usage.LogBackup)
and the quota history (gzipped) in Bundle.Usage. magpie backup and
Settings -> Sync -> Export add it unless --no-usage / the tick says no.
Collect never does, so sync, join and automatic backups are unchanged.
- Restore (Parts.Usage, on in All; magpie restore --no-usage and the Import
tick turn it off) merges: usage.MergeLog appends the lines the log here
doesn't have, compared byte for byte as a multiset, so restoring the same
file twice adds nothing and two equal calls both arrive. It reads most
of the log before the gateway's log lock, the rest under it, and appends
with O_APPEND in 4MB chunks, after a newline when the log ends in an
unfinished line. Quota points merge with provider.MergeQuotaHistory.
A file without usage (older magpie, or --no-usage) restores as before.
- Result.Usage is the calls added; the CLI and the Import form say it.
- Docs: sync-backup.md, reference.md, site sync pages (en, zh, ja) and the
search index/llms-full.txt rebuilt with node docs-index.mjs.
Not changed: where usage is also shared by sync, the old computer's calls
are in usage-others and, after a restore, in this log too: filed #6987.
Run on mote at this head (26f69e85e rebased on origin/main 4a1ac8442):
- gofmt -l clean; go vet (darwin), GOOS=linux go vet -tags nogui,
GOOS=windows go vet for backup, usage, cli, gui; GOOS=linux go build
-tags nogui and GOOS=windows go build of the app.
- go test -count=1 -timeout 45m ./internal/backup/ ./internal/usage/
./internal/cli/ ./internal/davsync/ ./internal/provider/ ./internal/gui/:
all ok.
- GUI (Chromium and WebKit, 5 languages, 1100/420px): sync-*.test.cjs,
i18n-*.test.cjs, auto-backup.test.cjs: 245 pass, 1 fail, i18n-keys'
"a plugin's words are its own" over claude_image_budget_test.go, red on
origin/main and filed as #6877.
- Real use: a built magpie on mote, two sandbox HOMEs, a copy of a real
105,815-line usage.jsonl (47MB): magpie backup wrote a 9.1MB file in
1.9s (364 bytes with --no-usage); magpie restore on a home holding the
last 1000 of those calls added 104,815 in 0.5s, the sorted log then equal
to the old one; a second restore added 0; the --no-usage file changed
nothing; magpie usage read the merged log.
Broken by hand, each red: MergeLog without the multiset skip
(TestBackupCarriesUsageHistory); no newline before the
first appended line (TestUsageMergeKeepsLinesWhole); WithUsage not setting
Bundle.Usage (both tests). The Import form's tick check first sat after
the Import click and went red in WebKit; it now runs before the click.
Not tried: the GUI's export and import against a real gateway (the GUI
tests use a fixture API); the full go test ./... and the whole GUI suite,
since mote and mica were each running other sessions' full suites.
253 lines
7.6 KiB
Go
253 lines
7.6 KiB
Go
package cli
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
|
|
"golang.org/x/term"
|
|
|
|
"github.com/yetone/magpie/internal/backup"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
)
|
|
|
|
// backupCmd writes every provider, setting, profile and agent model, and
|
|
// the library, and the usage history, to one file sealed with a passphrase:
|
|
// magpie backup [--no-keys] [--no-library] [--no-usage] [--sign-ins] [file].
|
|
func backupCmd(args []string) error {
|
|
keys, lib, use, signIns, file := true, true, true, false, ""
|
|
for _, a := range args {
|
|
switch {
|
|
case a == "--no-keys":
|
|
keys = false
|
|
case a == "--no-library":
|
|
lib = false
|
|
case a == "--no-usage":
|
|
use = false
|
|
case a == "--sign-ins":
|
|
signIns = true
|
|
case strings.HasPrefix(a, "-"):
|
|
return fmt.Errorf("unknown flag %s (magpie backup [--no-keys] [--no-library] [--no-usage] [--sign-ins] [file])", a)
|
|
case file == "":
|
|
file = a
|
|
default:
|
|
return errors.New("usage: magpie backup [--no-keys] [--no-library] [--no-usage] [--sign-ins] [file]")
|
|
}
|
|
}
|
|
if file == "" {
|
|
file = "magpie" + backup.Ext
|
|
}
|
|
b, err := backup.Collect(keys, version)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !lib {
|
|
b.Library = nil
|
|
}
|
|
if use {
|
|
if err := backup.WithUsage(&b); err != nil {
|
|
return fmt.Errorf("the usage history couldn't be read, so no backup was made (magpie backup --no-usage leaves it out): %w", err)
|
|
}
|
|
}
|
|
if signIns {
|
|
if err := backup.WithSignIns(&b); err != nil {
|
|
return fmt.Errorf("the sign-ins couldn't be read, so no backup was made: %w", err)
|
|
}
|
|
}
|
|
pass, err := passphrase("Passphrase for the backup: ", true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
data, err := backup.Seal(b, pass)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := edit.WriteAtomic(file, data); err != nil {
|
|
return err
|
|
}
|
|
os.Chmod(file, 0o600)
|
|
what := "with their keys"
|
|
if !keys {
|
|
what = "without keys"
|
|
}
|
|
fmt.Printf("%s %s: %d providers %s, %d profiles, %d agent settings",
|
|
green.Render("saved"), file, len(b.Providers), what, len(b.Profiles), len(b.Agents))
|
|
if l := b.Library; l != nil {
|
|
fmt.Printf("; library: %d MCP servers, %d skills", len(l.MCP), len(l.Skills))
|
|
if l.Subagents != nil && len(*l.Subagents) > 0 {
|
|
fmt.Printf(", %d subagents", len(*l.Subagents))
|
|
}
|
|
if l.Commands != nil && len(*l.Commands) > 0 {
|
|
fmt.Printf(", %d slash commands", len(*l.Commands))
|
|
}
|
|
if l.Hooks != nil && len(*l.Hooks) > 0 {
|
|
fmt.Printf(", %d hooks", len(*l.Hooks))
|
|
}
|
|
}
|
|
if u := b.Usage; u != nil {
|
|
fmt.Printf("; usage history: %d calls", u.Calls)
|
|
}
|
|
if s := b.SignIns; s != nil {
|
|
fmt.Printf("; %d sign-ins", len(s.Logins)+len(s.Plugins))
|
|
}
|
|
fmt.Println()
|
|
if b.SignIns != nil {
|
|
fmt.Println(muted.Render("The subscriptions' and plugins' sign-ins are in it, sealed with the passphrase: anyone with the file and the passphrase can use those accounts. Keep the passphrase: without it the file can't be opened."))
|
|
} else {
|
|
fmt.Println(muted.Render("Subscriptions are not in it: sign in to them on the other machine (or back up with --sign-ins). Keep the passphrase: without it the file can't be opened."))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// restoreCmd puts a backup in: magpie restore [--no-agents] [--no-library] [--no-usage] [--no-sign-ins] <file>.
|
|
func restoreCmd(args []string) error {
|
|
parts, file := backup.All, ""
|
|
for _, a := range args {
|
|
switch {
|
|
case a == "--no-agents":
|
|
parts.Agents = false
|
|
case a == "--no-library":
|
|
parts.Library = false
|
|
case a == "--no-usage":
|
|
parts.Usage = false
|
|
case a == "--no-sign-ins":
|
|
parts.SignIns = false
|
|
case strings.HasPrefix(a, "-"):
|
|
return fmt.Errorf("unknown flag %s (magpie restore [--no-agents] [--no-library] [--no-usage] [--no-sign-ins] <file>)", a)
|
|
case file == "":
|
|
file = a
|
|
default:
|
|
return errors.New("usage: magpie restore [--no-agents] [--no-library] [--no-usage] [--no-sign-ins] <file>")
|
|
}
|
|
}
|
|
if file == "" {
|
|
return errors.New("usage: magpie restore [--no-agents] [--no-library] [--no-usage] [--no-sign-ins] <file>")
|
|
}
|
|
data, err := os.ReadFile(file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pass, err := passphrase("Passphrase: ", false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b, err := backup.Open(data, pass)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r, err := backup.Restore(b, parts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("%s providers: %d added, %d replaced", green.Render("restored"), r.Added, r.Replaced)
|
|
if r.Settings {
|
|
fmt.Print("; settings")
|
|
}
|
|
fmt.Printf("; %d profiles; %d agent settings changed", r.Profiles, r.Agents)
|
|
if r.Library {
|
|
fmt.Print("; library")
|
|
}
|
|
if r.Usage != nil {
|
|
fmt.Printf("; usage history: %d calls added", *r.Usage)
|
|
}
|
|
if s := r.SignIns; s != nil {
|
|
fmt.Printf("; sign-ins: %d added, %d updated, %d kept as they are here", s.Added, s.Updated, s.Kept)
|
|
if s.Codex {
|
|
fmt.Print(" (Codex signed in)")
|
|
}
|
|
}
|
|
fmt.Println()
|
|
if len(r.NeedKey) > 0 {
|
|
fmt.Println(muted.Render("Needs a key (magpie provider key <id>): " + strings.Join(r.NeedKey, ", ")))
|
|
}
|
|
if len(r.SignIn) > 0 {
|
|
fmt.Println(muted.Render("The backup's settings use these, not signed in on this computer (a backup carries settings, not sign-ins; to use one here: magpie accounts add <id>): " + strings.Join(r.SignIn, ", ")))
|
|
}
|
|
if len(r.Plugins) > 0 {
|
|
fmt.Println(muted.Render("Plugins added: " + strings.Join(r.Plugins, ", ")))
|
|
}
|
|
for _, spec := range slices.Sorted(maps.Keys(r.PluginErrors)) {
|
|
fmt.Println(muted.Render(fmt.Sprintf("Couldn't add the plugin %s: %s", spec, r.PluginErrors[spec])))
|
|
}
|
|
for _, p := range r.LibraryProblems {
|
|
fmt.Println(muted.Render(fmt.Sprintf("Library: %s couldn't get %s: %s", p.Agent, p.What, p.Error)))
|
|
}
|
|
if len(r.Skipped) > 0 {
|
|
fmt.Println(muted.Render("Left as they are (agent not here, or its model can't be reached yet): " + strings.Join(r.Skipped, ", ")))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// passphrase reads one from the terminal without echo, asked twice when
|
|
// it is being set; piped in, it is the next line of stdin.
|
|
func passphrase(prompt string, confirm bool) (string, error) {
|
|
return secret("passphrase", prompt, confirm)
|
|
}
|
|
|
|
// stdin is read through one reader, so a second secret piped in is the
|
|
// second line and not lost to the first one's buffer. The reader is made
|
|
// over os.Stdin as it is when first read, never at package init: package
|
|
// variables are set before any init runs, and on Windows the desktop
|
|
// build's init (console_windows.go) only then swaps in the terminal's
|
|
// CONIN$. A reader made earlier keeps the invalid handle, and every
|
|
// prompt fails with "read /dev/stdin: The handle is invalid".
|
|
var (
|
|
stdinMu sync.Mutex
|
|
stdinFile *os.File
|
|
stdinBuf *bufio.Reader
|
|
)
|
|
|
|
func stdin() *bufio.Reader {
|
|
stdinMu.Lock()
|
|
defer stdinMu.Unlock()
|
|
if stdinBuf == nil || stdinFile != os.Stdin {
|
|
stdinFile, stdinBuf = os.Stdin, bufio.NewReader(os.Stdin)
|
|
}
|
|
return stdinBuf
|
|
}
|
|
|
|
// secret reads what (a passphrase, a password) as passphrase does; piped
|
|
// in, it is the next line of stdin.
|
|
func secret(what, prompt string, confirm bool) (string, error) {
|
|
fd := int(os.Stdin.Fd())
|
|
if !term.IsTerminal(fd) {
|
|
line, err := stdin().ReadString('\n')
|
|
line = strings.TrimRight(line, "\r\n")
|
|
if line == "" {
|
|
if err != nil {
|
|
return "", fmt.Errorf("no %s on stdin: %w", what, err)
|
|
}
|
|
return "", fmt.Errorf("the %s is empty", what)
|
|
}
|
|
return line, nil
|
|
}
|
|
read := func(p string) (string, error) {
|
|
fmt.Fprint(os.Stderr, p)
|
|
b, err := term.ReadPassword(fd)
|
|
fmt.Fprintln(os.Stderr)
|
|
return string(b), err
|
|
}
|
|
pass, err := read(prompt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if pass == "" {
|
|
return "", fmt.Errorf("the %s is empty", what)
|
|
}
|
|
if confirm {
|
|
again, err := read("Again: ")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if again != pass {
|
|
return "", fmt.Errorf("the %ss differ", what)
|
|
}
|
|
}
|
|
return pass, nil
|
|
}
|