backup: a backup file carries the usage history, and a restore merges it (JasonLeeForOnly on Discord)

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.
This commit is contained in:
yetone
2026-11-17 22:41:26 +08:00
parent 659e8850a2
commit 50c5a52dbd
19 changed files with 634 additions and 41 deletions
+6 -1
View File
@@ -4129,6 +4129,7 @@ magpie backup --no-keys ~/b.magpie-backup # the same with no API keys in it
magpie restore magpie.magpie-backup # on the other machine
magpie restore --no-agents b.magpie-backup # providers, settings, profiles; agents left as they are
magpie restore --no-library b.magpie-backup # the library here left as it is
magpie backup --no-usage ~/b.magpie-backup # no usage history in it
```
A backup holds your providers (with their keys, unless `--no-keys`), the
@@ -4156,7 +4157,11 @@ name the ones still to sign in to. The plugins added from npm or git come
along too and are installed where it is put back (one added from a folder
stays on its machine; without keys, an option whose name looks like a key
is left out); a plugin's sign-in is not carried, a plugin already there is
left as it is, and one removed on one machine stays on the others. Piped
left as it is, and one removed on one machine stays on the others. The usage history comes
along too (unless `--no-usage`): every call in `usage.jsonl`, gzipped, and
the quota cards' history. Restoring merges it with the history there: a call
already there is never added again, so restoring the same backup twice counts
nothing twice (`magpie restore --no-usage` leaves it out). Piped
in, the passphrase is the first line of stdin.
### Keeping machines in sync
+38
View File
@@ -306,6 +306,44 @@ clock.
`syncOnce` after the sign-ins, never replaced as a part; see
[Memory's backups and sync](memory.md#backups-and-sync).
## The usage history in a backup file
A backup file made by `magpie backup` or Settings → Sync → Export carries the
usage history unless `--no-usage` (or the Export form's tick) leaves it out
(JasonLeeForOnly on Discord: a server moved by backup and restore lost every
call). [`WithUsage`](../../internal/backup/backup.go) puts in `Bundle.Usage`:
usage.jsonl's whole lines, gzipped ([`LogBackup`](../../internal/usage/backup_log.go);
a line still being written is left out), their count, and the gzipped quota
history (`provider.QuotaHistoryData`). `Collect` never adds it, so a sync, a
join and an automatic backup carry no usage: sync shares usage by day files
(`usage.go`), and an automatic backup would hold the whole log every day.
Routing history (debug data) and `usage-others` (the other computers' days)
are never in a backup file.
`Restore` with `Parts.Usage` (on in `All`; `magpie restore --no-usage` and
the Import form's tick turn it off) merges, never replaces:
[`MergeLog`](../../internal/usage/backup_log.go) appends the backup's lines
this log doesn't have, compared byte for byte as a multiset, so a line here
is passed over as often as it is here. Restoring the same file twice adds
nothing; two calls the old log had as the same bytes both arrive; a line
that isn't a JSON object is passed over. Most of the log is read before the
gateway's log lock is taken, the rest under it, and the new lines are
appended with O_APPEND a few MB at a time after a newline if the log ends
in an unfinished line. Rows keep `Computer == ""`: they are this computer's
calls from then on, key spend caps included. Quota points merge with
`provider.MergeQuotaHistory`. `Result.Usage` is the number of calls added,
nil when the file has no usage (one made before, or with `--no-usage`),
which restores as before.
Not yet: where usage is also shared by sync, the old computer's calls are
in `usage-others` and, after a restore, in this log too, so they count
twice (#6987).
Tests: `TestBackupCarriesUsageHistory` (two homes, a restore twice, a
duplicate line, `--no-usage`), `TestOldBackupWithoutUsage`,
`TestUsageMergeKeepsLinesWhole` (an unfinished last line on both sides),
and `sync-signins.test.cjs` for the forms.
## Data folder on another disk
Settings › Sync's Data folder (CHENGJIAHEGOXIS and buhaodeshiyehao on X)
+87 -10
View File
@@ -5,7 +5,9 @@
// servers and skills magpie gives the agents). Sign-ins (subscription
// accounts and the plugins') are in it only when the user asks for them
// (WithSignIns): each is the sign-in of an agent on this machine, and
// without them each machine signs in on its own.
// without them each machine signs in on its own. The usage history is in
// it when asked for (WithUsage), as the CLI and the Settings page's Export
// do unless told not to; a sync's and an automatic backup's never have it.
//
// The file is JSON: a header naming how it is sealed, and the bundle
// encrypted with AES-256-GCM under a key derived from the passphrase with
@@ -13,6 +15,8 @@
package backup
import (
"bytes"
"compress/gzip"
"context"
"crypto/aes"
"crypto/cipher"
@@ -22,6 +26,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"maps"
"os"
@@ -39,6 +44,7 @@ import (
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// Ext is the extension backups are saved with.
@@ -112,6 +118,64 @@ type Bundle struct {
// put back, memory by memory, never put over what is there. Nil from
// a magpie before it, or with no memory.
Memory *memory.Bundle `json:"memory,omitempty"`
// Usage is the history of the calls made here and of the accounts'
// windows (WithUsage): merged where it is put back, never put over
// what is there. Nil when left out, and from a magpie before it.
Usage *Usage `json:"usage,omitempty"`
}
// Usage is the usage history a backup carries, so a restore on a new
// computer has it (JasonLeeForOnly on Discord): usage.jsonl's lines,
// gzipped (usage.LogBackup), and the quota cards' history as
// provider.QuotaHistoryData keeps it, gzipped too.
type Usage struct {
Calls int `json:"calls"` // how many lines Log has
Log []byte `json:"log,omitempty"` // gzipped usage.jsonl
Quotas []byte `json:"quotas,omitempty"` // gzipped quota-history.json
}
// WithUsage puts this computer's usage history in b. A log that can't be
// read is an error, never none.
func WithUsage(b *Bundle) error {
lines, n, err := usage.LogBackup()
if err != nil {
return err
}
u := &Usage{Calls: n, Log: lines}
if q := provider.QuotaHistoryData(); len(q) > 0 {
var z bytes.Buffer
w, _ := gzip.NewWriterLevel(&z, gzip.BestCompression)
w.Write(q)
if err := w.Close(); err != nil {
return err
}
u.Quotas = z.Bytes()
}
b.Usage = u
return nil
}
// restoreUsage merges u into this computer's usage history, and says how
// many calls it added.
func restoreUsage(u *Usage) (int, error) {
n, err := usage.MergeLog(u.Log)
if err != nil {
return n, err
}
if len(u.Quotas) > 0 {
zr, err := gzip.NewReader(bytes.NewReader(u.Quotas))
if err != nil {
return n, err
}
q, err := io.ReadAll(zr)
if err != nil {
return n, err
}
if err := provider.MergeQuotaHistory(q, time.Now()); err != nil {
return n, err
}
}
return n, nil
}
// WithSignIns puts this computer's sign-ins in b. One that can't be read
@@ -418,10 +482,13 @@ type Parts struct {
// Memory merges the backup's memory into this computer's
// (memory.Put): a memory here is never taken away by it.
Memory bool
// Usage merges the backup's usage history into this computer's
// (usage.MergeLog): a call here already is never added again.
Usage bool
}
// All is every part.
var All = Parts{Providers: true, Settings: true, Profiles: true, Agents: true, Library: true, SignIns: true, Memory: true}
var All = Parts{Providers: true, Settings: true, Profiles: true, Agents: true, Library: true, SignIns: true, Memory: true, Usage: true}
// Result says what a restore did.
type Result struct {
@@ -432,14 +499,17 @@ type Result struct {
SignIn []string `json:",omitempty"`
// Plugins are the plugins installed for it, PluginErrors why the others
// couldn't be, by spec
Plugins []string `json:",omitempty"`
PluginErrors map[string]string `json:",omitempty"`
Settings bool
Profiles int
Agents int // agent fields changed
Skipped []string // agent fields left alone: the agent is not on this machine, or the value failed
Library bool // the library was put in
Memory bool `json:",omitempty"` // memory changed: the backup's merged in
Plugins []string `json:",omitempty"`
PluginErrors map[string]string `json:",omitempty"`
Settings bool
Profiles int
Agents int // agent fields changed
Skipped []string // agent fields left alone: the agent is not on this machine, or the value failed
Library bool // the library was put in
Memory bool `json:",omitempty"` // memory changed: the backup's merged in
// Usage is how many of the backup's calls were added to the usage
// history here; nil when it had none, or they weren't asked for.
Usage *int `json:",omitempty"`
LibraryProblems []library.Problem `json:",omitempty"` // what of it couldn't be given to an agent
// SignIns is what putting the backup's sign-ins in did; nil when it
// had none, or they weren't asked for.
@@ -644,6 +714,13 @@ func Restore(b Bundle, parts Parts) (Result, error) {
}
}
}
if parts.Usage && b.Usage != nil {
n, err := restoreUsage(b.Usage)
if err != nil {
return r, fmt.Errorf("the usage history: %w", err)
}
r.Usage = &n
}
return r, nil
}
+209
View File
@@ -0,0 +1,209 @@
package backup
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// callLine is one call as usage.jsonl has it.
func callLine(t *testing.T, at time.Time, rid string, in int) string {
t.Helper()
b, err := json.Marshal(usage.Record{Time: at, Agent: "codex", Provider: "openai", Model: "gpt-5", Input: in, Output: 7, Status: 200, RequestID: rid})
if err != nil {
t.Fatal(err)
}
return string(b)
}
func writeLog(t *testing.T, lines ...string) {
t.Helper()
p := usage.Path()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
func logLines(t *testing.T) []string {
t.Helper()
b, err := os.ReadFile(usage.Path())
if err != nil {
t.Fatal(err)
}
return strings.Split(strings.TrimRight(string(b), "\n"), "\n")
}
func added(r Result) string {
if r.Usage == nil {
return "none"
}
return fmt.Sprint(*r.Usage)
}
func count(lines []string, line string) int {
n := 0
for _, l := range lines {
if l == line {
n++
}
}
return n
}
// The usage history goes in a backup, and putting it back on a new
// computer adds the calls it hasn't got, once, however often it is put
// back (JasonLeeForOnly on Discord: the history was lost moving servers).
func TestBackupCarriesUsageHistory(t *testing.T) {
home(t)
now := time.Now().UTC().Truncate(time.Second)
old1 := callLine(t, now.Add(-72*time.Hour), "r1", 100)
old2 := callLine(t, now.Add(-48*time.Hour), "r2", 200)
both := callLine(t, now.Add(-24*time.Hour), "r3", 300) // the new computer has it too
writeLog(t, old1, old2, both, old2) // r2 twice, as written twice
// an account's quota history
at := now.Add(-time.Hour)
q, _ := json.Marshal(map[string]map[string][]provider.QuotaPoint{"codex/me@example.com": {"5h": {{At: at, Left: 42}}}})
if err := os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "quota-history.json"), q, 0o600); err != nil {
t.Fatal(err)
}
b, err := Collect(false, "test")
if err != nil {
t.Fatal(err)
}
if b.Usage != nil {
t.Fatal("a whole collect (a sync's, an automatic backup's) carries no usage")
}
if err := WithUsage(&b); err != nil {
t.Fatal(err)
}
if b.Usage == nil || b.Usage.Calls != 4 || len(b.Usage.Log) == 0 || len(b.Usage.Quotas) == 0 {
t.Fatalf("usage in the backup: %+v", b.Usage)
}
sealed, err := Seal(b, "pass")
if err != nil {
t.Fatal(err)
}
home(t) // the new server
mine := callLine(t, now, "n1", 9)
writeLog(t, both, mine)
opened, err := Open(sealed, "pass")
if err != nil {
t.Fatal(err)
}
r, err := Restore(opened, All)
if err != nil {
t.Fatal(err)
}
if r.Usage == nil || *r.Usage != 3 {
t.Fatalf("calls added: %s, want 3 (r1, r2 twice; r3 is here)", added(r))
}
lines := logLines(t)
for line, want := range map[string]int{old1: 1, old2: 2, both: 1, mine: 1} {
if got := count(lines, line); got != want {
t.Errorf("%s: %d times, want %d\n%s", line, got, want, strings.Join(lines, "\n"))
}
}
if len(lines) != 5 {
t.Fatalf("log has %d lines, want 5", len(lines))
}
if got := len(usage.Load(time.Time{})); got != 5 {
t.Fatalf("Load reads %d calls, want 5", got)
}
hist, err := os.ReadFile(filepath.Join(filepath.Dir(provider.Path()), "quota-history.json"))
if err != nil || !bytes.Contains(hist, []byte("me@example.com")) {
t.Fatalf("quota history not merged: %s, %v", hist, err)
}
// put back again: nothing counted twice
r, err = Restore(opened, All)
if err != nil {
t.Fatal(err)
}
if r.Usage == nil || *r.Usage != 0 {
t.Fatalf("second restore added %s calls", added(r))
}
if again := logLines(t); len(again) != 5 {
t.Fatalf("after a second restore the log has %d lines, want 5", len(again))
}
// --no-usage
writeLog(t, mine)
if r, err = Restore(opened, Parts{Usage: false}); err != nil || r.Usage != nil {
t.Fatalf("usage left out: %+v, %v", r, err)
}
if got := logLines(t); len(got) != 1 {
t.Fatalf("usage left out, yet the log has %d lines", len(got))
}
}
// A backup made before usage went in it is put back as before: the log
// here is left as it is.
func TestOldBackupWithoutUsage(t *testing.T) {
home(t)
b, err := Collect(true, "old")
if err != nil {
t.Fatal(err)
}
// as a magpie before it wrote the file: no "usage" field at all
sealed, err := Seal(b, "pass")
if err != nil {
t.Fatal(err)
}
home(t)
mine := callLine(t, time.Now().UTC(), "n1", 9)
writeLog(t, mine)
opened, err := Open(sealed, "pass")
if err != nil {
t.Fatal(err)
}
r, err := Restore(opened, All)
if err != nil {
t.Fatal(err)
}
if r.Usage != nil {
t.Fatalf("an old backup said it added %d calls", *r.Usage)
}
if got := logLines(t); len(got) != 1 || got[0] != mine {
t.Fatalf("log changed: %q", got)
}
}
// A log here that ends in a line cut short, and lines in the backup that
// aren't calls: each call goes on a line of its own, and nothing else goes.
func TestUsageMergeKeepsLinesWhole(t *testing.T) {
home(t)
a := callLine(t, time.Now().UTC().Add(-time.Hour), "a", 1)
writeLog(t, a, "not json", `{"cut":`)
b := Bundle{}
if err := WithUsage(&b); err != nil {
t.Fatal(err)
}
home(t)
p := usage.Path()
os.MkdirAll(filepath.Dir(p), 0o755)
mine := callLine(t, time.Now().UTC(), "n", 2)
if err := os.WriteFile(p, []byte(mine+"\n"+`{"half`), 0o600); err != nil {
t.Fatal(err)
}
n, err := restoreUsage(b.Usage)
if err != nil || n != 1 {
t.Fatalf("added %d, %v; want 1", n, err)
}
lines := logLines(t)
want := []string{mine, `{"half`, a}
if fmt.Sprint(lines) != fmt.Sprint(want) {
t.Fatalf("log:\n%s\nwant:\n%s", strings.Join(lines, "\n"), strings.Join(want, "\n"))
}
}
+24 -9
View File
@@ -17,24 +17,26 @@ import (
)
// backupCmd writes every provider, setting, profile and agent model, and
// the library, to one file sealed with a passphrase:
// magpie backup [--no-keys] [--no-library] [--sign-ins] [file].
// 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, signIns, file := true, true, false, ""
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] [--sign-ins] [file])", 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] [--sign-ins] [file]")
return errors.New("usage: magpie backup [--no-keys] [--no-library] [--no-usage] [--sign-ins] [file]")
}
}
if file == "" {
@@ -47,6 +49,11 @@ func backupCmd(args []string) error {
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)
@@ -82,6 +89,9 @@ func backupCmd(args []string) error {
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))
}
@@ -94,7 +104,7 @@ func backupCmd(args []string) error {
return nil
}
// restoreCmd puts a backup in: magpie restore [--no-agents] [--no-library] [--no-sign-ins] <file>.
// 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 {
@@ -103,18 +113,20 @@ func restoreCmd(args []string) error {
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-sign-ins] <file>)", 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-sign-ins] <file>")
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-sign-ins] <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 {
@@ -140,6 +152,9 @@ func restoreCmd(args []string) error {
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 {
+3 -2
View File
@@ -72,8 +72,9 @@ const usage = `magpie — one place to pick every agent's model
magpie rename <old> <new> rename a profile
magpie rm <name> delete a profile
magpie backup [--no-keys] [--no-library] [file] providers, keys, settings, profiles, agent models and the library in one file, sealed with a passphrase
magpie restore [--no-agents] [--no-library] <file> put a backup in on this machine
magpie backup [--no-keys] [--no-library] [file] providers, keys, settings, profiles, agent models, the library and the usage history in one file, sealed with a passphrase
magpie restore [--no-agents] [--no-library] <file> put a backup in on this machine; its usage history is merged with the one here
--no-usage on either: the usage history left out
--sign-ins on backup: the subscriptions' and plugins' sign-ins too, sealed (off unless given); --no-sign-ins on restore leaves them out
magpie uninstall [--yes] disconnect every agent, putting back what each had, then remove magpie's service and files
--keep-data: all but deleting magpie's settings, providers and usage
+12
View File
@@ -3488,6 +3488,9 @@ const I18N = {
"Memory: what the agents know, merged memory by memory": "记忆:agent 记住的内容,逐条合并",
"With memory: what the agents know": "包含记忆:agent 记住的内容",
"Bring in memory too, merged with the memories here": "也导入记忆,与本机的记忆合并",
"With the usage history": "包含用量记录",
"Bring in the usage history too, merged with the one here": "也导入用量记录,与本机的记录合并",
"Usage history: {n} calls added": "用量记录:新增 {n} 次调用",
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "这个备份的设置用到了 {names},本机没有登录,备份里也没有它的登录信息。要在这里使用,请在「服务商 → 添加服务商」中登录;不用的话无需处理。",
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "登录信息:新增 {added} 个,更新 {updated} 个,{kept} 个保持本机的",
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "保持本机的账号:本机的续期时间更晚,或是智能体自己登录着的账号。",
@@ -8857,6 +8860,9 @@ const I18N = {
"Memory: what the agents know, merged memory by memory": "記憶:agent 記住的內容,逐條合併",
"With memory: what the agents know": "包含記憶:agent 記住的內容",
"Bring in memory too, merged with the memories here": "也匯入記憶,與本機的記憶合併",
"With the usage history": "包含用量紀錄",
"Bring in the usage history too, merged with the one here": "也匯入用量紀錄,與本機的紀錄合併",
"Usage history: {n} calls added": "用量紀錄:新增 {n} 次呼叫",
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "這個備份的設定用到了 {names},本機沒有登入,備份裡也沒有它的登入資訊。要在這裡使用,請在「服務商 → 新增服務商」中登入;不用的話無需處理。",
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "登入資訊:新增 {added} 個,更新 {updated} 個,{kept} 個保持本機的",
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "保持本機的帳號:本機的續期時間更晚,或是代理自己登入著的帳號。",
@@ -14236,6 +14242,9 @@ const I18N = {
"Memory: what the agents know, merged memory by memory": "メモリー:エージェントが覚えていること、1 件ずつマージ",
"With memory: what the agents know": "メモリーも含める:エージェントが覚えていること",
"Bring in memory too, merged with the memories here": "メモリーも取り込み、このコンピューターのメモリーとマージする",
"With the usage history": "使用量の履歴も含める",
"Bring in the usage history too, merged with the one here": "使用量の履歴も取り込み、このコンピューターの履歴とマージする",
"Usage history: {n} calls added": "使用量の履歴:{n} 件の呼び出しを追加しました",
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "このバックアップの設定は {names} を使いますが、このコンピューターではサインインしておらず、バックアップにもそのサインインはありません。ここで使うには「プロバイダ → プロバイダを追加」でサインインしてください。使わないなら何もする必要はありません。",
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "サインイン:{added} 件追加、{updated} 件更新、{kept} 件はここのまま",
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "ここのままにしたものは、ここでの更新のほうが新しいか、エージェント自身がサインインしているアカウントです。",
@@ -19628,6 +19637,9 @@ const I18N = {
"Memory: what the agents know, merged memory by memory": "Gedächtnis: was die Agenten wissen, Eintrag für Eintrag zusammengeführt",
"With memory: what the agents know": "Mit dem Gedächtnis: was die Agenten wissen",
"Bring in memory too, merged with the memories here": "Auch das Gedächtnis übernehmen, mit dem hiesigen zusammengeführt",
"With the usage history": "Mit dem Nutzungsverlauf",
"Bring in the usage history too, merged with the one here": "Auch den Nutzungsverlauf übernehmen, mit dem hiesigen zusammengeführt",
"Usage history: {n} calls added": "Nutzungsverlauf: {n} Aufrufe hinzugefügt",
"This backup's settings use {names}, which isn't signed in on this computer, and the backup has no sign-in for it. To use it here, sign in in Providers → Add a provider; if you don't, nothing needs doing.": "Die Einstellungen dieses Backups nutzen {names}, das auf diesem Computer nicht angemeldet ist, und das Backup hat keine Anmeldung dafür. Um es hier zu nutzen, melde dich unter Anbieter → Anbieter hinzufügen an; sonst ist nichts zu tun.",
"Sign-ins: {added} added, {updated} updated, {kept} kept as they are here": "Anmeldungen: {added} hinzugefügt, {updated} aktualisiert, {kept} wie hier belassen",
"One kept as it is here was renewed later here, or is the account the agent itself is signed in with.": "Ein hier belassenes Konto wurde hier später erneuert oder ist das Konto, mit dem der Agent selbst angemeldet ist.",
+7 -4
View File
@@ -239,10 +239,11 @@ window.exportForm = function () {
const [keysL, keys] = tick(t("With the providers' API keys"), true);
const [libL, lib] = tick(t("With the library: instructions, MCP servers, skills, hooks and subagents"), true);
const [memL, mem] = tick(t("With memory: what the agents know"), true);
const [useL, use] = tick(t("With the usage history"), true);
// sign-ins: off unless picked (qianxunji, curtinp118 on Discord)
const [siL, si] = tick(t("With the sign-ins: subscription accounts and plugin sign-ins"), false);
const what = el("div", "stack");
what.append(keysL, libL, memL, siL);
what.append(keysL, libL, memL, useL, siL);
const passF = field(t("Passphrase"), p1, t("Needed to open the file. Subscriptions aren't in it: sign in to them on the other computer."));
const passSay = passF[1].querySelector(".hint");
si.onchange = () => {
@@ -259,7 +260,7 @@ window.exportForm = function () {
if (p1.value !== p2.value) return say(t("The two passphrases differ"));
go.classList.add("busy");
try {
const r = await api("backup/export", { pass: p1.value, keys: keys.checked, library: lib.checked, memory: mem.checked, signIns: si.checked });
const r = await api("backup/export", { pass: p1.value, keys: keys.checked, library: lib.checked, memory: mem.checked, usage: use.checked, signIns: si.checked });
ed.replaceChildren(el("div", "done", t("Saved to {path}", { path: r.path })));
} catch (e) {
go.classList.remove("busy");
@@ -303,9 +304,10 @@ window.importForm = function () {
const [agentsL, agents] = tick(t("Set the agents' models too"), true);
const [libL, lib] = tick(t("Bring in the library too: instructions, MCP servers, skills, hooks and subagents"), true);
const [memL, mem] = tick(t("Bring in memory too, merged with the memories here"), true);
const [useL, use] = tick(t("Bring in the usage history too, merged with the one here"), true);
const [siL, si] = tick(t("Bring in the sign-ins too, when the file has them"), true);
const what = el("div", "stack");
what.append(agentsL, libL, memL, siL);
what.append(agentsL, libL, memL, useL, siL);
ed.append(...field(t("File"), pf), ...field(t("Passphrase"), pass), ...field("", what, t("Providers with the same id are replaced; one that came without a key keeps the key it has here. The library replaces the one here, which is kept with its backups.")));
const go = el("button", "text primary", t("Import"));
const cancel = el("button", "text", t("Cancel"));
@@ -315,7 +317,7 @@ window.importForm = function () {
if (!data) return say(t("Choose a file first"));
go.classList.add("busy");
try {
const r = await api("backup/import", { data, pass: pass.value, agents: agents.checked, library: lib.checked, memory: mem.checked, signIns: si.checked });
const r = await api("backup/import", { data, pass: pass.value, agents: agents.checked, library: lib.checked, memory: mem.checked, usage: use.checked, signIns: si.checked });
const lines = [t("Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed", { added: r.Added, replaced: r.Replaced, profiles: r.Profiles, agents: r.Agents })];
if (r.NeedKey?.length) lines.push(t("Needs a key: {names}", { names: r.NeedKey.join(", ") }));
if (r.SignIns) lines.push(...signInsSaid(r.SignIns));
@@ -327,6 +329,7 @@ window.importForm = function () {
if (r.Plugins?.length) lines.push(t("Plugins added: {names}", { names: r.Plugins.join(", ") }));
for (const [spec, error] of Object.entries(r.PluginErrors || {})) lines.push(t("Couldn't add the plugin {spec}: {error}", { spec, error }));
if (r.Library) lines.push(t("Library brought in and written into the agents"));
if (r.Usage != null) lines.push(t("Usage history: {n} calls added", { n: r.Usage }));
for (const p of r.LibraryProblems || []) lines.push(t("{agent} couldn't get {what}: {error}", { agent: p.agent, what: p.what, error: p.error }));
ed.replaceChildren(...lines.map((l) => el("div", "done", l)));
refreshAfterSync();
+18 -1
View File
@@ -28,6 +28,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
Keys bool
Library *bool // nil is yes
Memory *bool // nil is yes
Usage *bool // nil is yes: the usage history
SignIns bool // the subscriptions' and plugins' sign-ins too
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
@@ -45,6 +46,12 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
if in.Memory != nil && !*in.Memory {
b.Memory = nil
}
if in.Usage == nil || *in.Usage {
if err := backup.WithUsage(&b); err != nil {
fail(rw, fmt.Errorf("the usage history couldn't be read, so no backup was made: %w", err))
return
}
}
if in.SignIns {
if err := backup.WithSignIns(&b); err != nil {
fail(rw, fmt.Errorf("the sign-ins couldn't be read, so no backup was made: %w", err))
@@ -70,7 +77,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
}
os.Chmod(name, 0o600)
_ = w.OpenFolder(dir) // saved either way; the path is in the answer
writeJSON(rw, map[string]any{"path": tilde(name), "providers": len(b.Providers), "profiles": len(b.Profiles), "agents": len(b.Agents), "library": b.Library != nil, "signIns": signInCount(b.SignIns)})
writeJSON(rw, map[string]any{"path": tilde(name), "providers": len(b.Providers), "profiles": len(b.Profiles), "agents": len(b.Agents), "library": b.Library != nil, "signIns": signInCount(b.SignIns), "usage": usageCount(b.Usage)})
})
mux.HandleFunc("POST /api/backup/import", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
@@ -79,6 +86,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
Agents bool
Library *bool // nil is yes
Memory *bool // nil is yes: merged with the memories here
Usage *bool // nil is yes: merged with the usage history here
SignIns *bool // nil is yes: the backup's sign-ins, when it has them
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
@@ -100,6 +108,7 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
parts.Library = in.Library == nil || *in.Library
parts.Memory = in.Memory == nil || *in.Memory
parts.SignIns = in.SignIns == nil || *in.SignIns
parts.Usage = in.Usage == nil || *in.Usage
res, err := backup.Restore(b, parts)
if err != nil {
fail(rw, err)
@@ -375,3 +384,11 @@ func signInCount(s *provider.SignIns) int {
}
return len(s.Logins) + len(s.Plugins)
}
// usageCount is how many calls a backup's usage history holds.
func usageCount(u *backup.Usage) int {
if u == nil {
return 0
}
return u.Calls
}
+10 -4
View File
@@ -63,7 +63,7 @@ function serve(lang, posts) {
return json(sync);
}
if (pathname === "/api/backup/export") { post(); return json({ path: "/home/me/magpie.magpie-backup", signIns: 3 }); }
if (pathname === "/api/backup/import") { post(); return json({ Added: 1, Replaced: 0, Profiles: 0, Agents: 0, SignIns: signInsResult }); }
if (pathname === "/api/backup/import") { post(); return json({ Added: 1, Replaced: 0, Profiles: 0, Agents: 0, SignIns: signInsResult, Usage: 12 }); }
if (pathname === "/api/autobackup") return json(auto);
if (pathname.startsWith("/api/autobackup/")) {
const b = post();
@@ -163,11 +163,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await click(exTick);
await form.locator(".hint", { hasText: w("Needed to open the file. The sign-ins are in it: anyone with the file and the passphrase can use those accounts, so pick a strong one.") }).waitFor();
const [p1, p2] = [form.locator("input[type=password]").nth(0), form.locator("input[type=password]").nth(1)];
// the usage history goes unless unticked (JasonLeeForOnly on Discord)
assert.equal(await form.locator("label.tick", { hasText: w("With the usage history") }).locator("input").isChecked(), true);
await p1.fill("correct horse");
await p2.fill("correct horse");
await noneWider(page);
await click(form.locator("button.primary"));
assert.deepEqual(await waitPost("/api/backup/export"), { pass: "correct horse", keys: true, library: true, signIns: true, memory: true });
assert.deepEqual(await waitPost("/api/backup/export"), { pass: "correct horse", keys: true, library: true, signIns: true, memory: true, usage: true });
await form.locator(".done").waitFor();
await click(exportRow.locator("button"));
@@ -176,17 +178,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
form = list.locator(".sync-form");
const imTick = form.locator("label.tick", { hasText: w("Bring in the sign-ins too, when the file has them") }).locator("input");
assert.equal(await imTick.isChecked(), true);
assert.equal(await form.locator("label.tick", { hasText: w("Bring in the usage history too, merged with the one here") }).locator("input").isChecked(), true);
await form.locator("input[type=file]").setInputFiles({ name: "magpie.magpie-backup", mimeType: "application/octet-stream", buffer: Buffer.from("sealed") });
await form.locator(".fname", { hasText: "magpie.magpie-backup" }).waitFor();
await form.locator("input[type=password]").fill("correct horse");
await click(form.locator("button.primary"));
assert.equal((await waitPost("/api/backup/import"))?.signIns, true);
const imported = await waitPost("/api/backup/import");
assert.equal(imported?.signIns, true);
assert.equal(imported?.usage, true);
const done = form.locator(".done");
await done.first().waitFor();
const lines = await done.allTextContents();
for (const l of [w("Sign-ins: {added} added, {updated} updated, {kept} kept as they are here", { added: 2, updated: 1, kept: 1 }),
w("One kept as it is here was renewed later here, or is the account the agent itself is signed in with."),
w("Codex is signed in with the backup's account.")]) assert.ok(lines.includes(l), `${l} in ${lines.join(" | ")}`);
w("Codex is signed in with the backup's account."),
w("Usage history: {n} calls added", { n: 12 })]) assert.ok(lines.includes(l), `${l} in ${lines.join(" | ")}`);
await noneWider(page);
await click(rowNamed(w("Import")).locator("button"));
+206
View File
@@ -0,0 +1,206 @@
package usage
// The usage log in a backup file (JasonLeeForOnly on Discord, who moved
// magpie to a new server with backup and restore and lost every call's
// history): LogBackup packs usage.jsonl's lines, gzipped, and MergeLog
// adds the ones this computer's log doesn't have yet. A line is the
// call's record as it was written, so a line already here, from an
// earlier restore of the same backup or from the log itself, is the same
// bytes and is never added twice.
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"hash/maphash"
"io"
"os"
"path/filepath"
)
// LogBackup is usage.jsonl's whole lines, gzipped, and how many there
// are: none (nil, 0) when there is no log. A line still being written
// when it is read is left for the next backup.
func LogBackup() ([]byte, int, error) {
f, err := os.Open(Path())
if errors.Is(err, os.ErrNotExist) {
return nil, 0, nil
}
if err != nil {
return nil, 0, err
}
defer f.Close()
var z bytes.Buffer
w, _ := gzip.NewWriterLevel(&z, gzip.BestCompression)
n := 0
rd := bufio.NewReaderSize(f, 64<<10)
for {
line, err := rd.ReadBytes('\n')
if err != nil {
if err != io.EOF {
return nil, 0, err
}
break // an unfinished last line
}
if len(bytes.TrimSpace(line)) == 0 {
continue
}
if _, err := w.Write(line); err != nil {
return nil, 0, err
}
n++
}
if err := w.Close(); err != nil {
return nil, 0, err
}
if n == 0 {
return nil, 0, nil
}
return z.Bytes(), n, nil
}
// logLine is a line as MergeLog compares it: without its line ending.
func logLine(b []byte) []byte { return bytes.TrimRight(b, " \t\r\n") }
// MergeLog adds the lines of a log LogBackup packed that usage.jsonl
// doesn't have, at its end, and says how many it added. A line the log
// has is passed over as often as the log has it, so a restore made twice
// adds nothing the second time, and two calls that were the same bytes
// both stay. A line that isn't a JSON object is passed over.
func MergeLog(gz []byte) (int, error) {
if len(gz) == 0 {
return 0, nil
}
zr, err := gzip.NewReader(bytes.NewReader(gz))
if err != nil {
return 0, err
}
seed := maphash.MakeSeed()
have := map[uint64]int32{}
path := Path()
// most of the log is read before the gateway's lock is taken, so a
// long one doesn't hold its calls up; what it wrote meanwhile is read
// under the lock below
off, err := countLines(path, 0, seed, have)
if err != nil {
return 0, err
}
mu.Lock()
defer mu.Unlock()
if _, err := countLines(path, off, seed, have); err != nil {
return 0, err
}
// the log is opened once a line is new, and written to a few MB at a
// time: a long history isn't held whole twice over
var f *os.File
var before os.FileInfo
var buf []byte
flush := func() error {
if len(buf) == 0 {
return nil
}
if f == nil {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
var err error
if f, err = os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600); err != nil {
return err
}
before, _ = statLogHandle(f)
// a log that ends in an unfinished line gets its own: the first
// line added is never run into it
if before != nil && before.Size() > 0 && !endsInNewline(path, before.Size()) {
buf = append([]byte{'\n'}, buf...)
}
}
_, err := f.Write(buf)
buf = buf[:0]
return err
}
added := 0
rd := bufio.NewReaderSize(zr, 64<<10)
var werr error
for werr == nil {
raw, err := rd.ReadBytes('\n')
line := logLine(raw)
if len(line) > 0 && line[0] == '{' && json.Valid(line) {
k := maphash.Bytes(seed, line)
if have[k] > 0 {
have[k]--
} else {
buf = append(append(buf, line...), '\n')
added++
if len(buf) >= 4<<20 {
werr = flush()
}
}
}
if err != nil {
if err != io.EOF {
werr = err
}
break
}
}
if werr == nil {
werr = flush()
}
if f != nil {
after, _ := statLogHandle(f)
noteLogAppend(path, before, after)
f.Close()
}
if werr != nil {
// what part of it reached the log is there: a restore again adds
// the rest, and not what reached it
return added, werr
}
return added, nil
}
// countLines counts the whole lines of the log from off on into have, by
// their hash, and says where the last whole one ended.
func countLines(path string, off int64, seed maphash.Seed, have map[uint64]int32) (int64, error) {
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return off, nil
}
if err != nil {
return off, err
}
defer f.Close()
if _, err := f.Seek(off, io.SeekStart); err != nil {
return off, err
}
rd := bufio.NewReaderSize(f, 64<<10)
for {
raw, err := rd.ReadBytes('\n')
if err != nil {
if err != io.EOF {
return off, err
}
return off, nil // an unfinished line is read again under the lock
}
off += int64(len(raw))
if line := logLine(raw); len(line) > 0 {
have[maphash.Bytes(seed, line)]++
}
}
}
// endsInNewline says whether the log's byte at size-1 is a newline.
func endsInNewline(path string, size int64) bool {
f, err := os.Open(path)
if err != nil {
return true
}
defer f.Close()
b := make([]byte, 1)
if _, err := f.ReadAt(b, size-1); err != nil {
return true
}
return b[0] == '\n'
}
+3 -3
View File
@@ -159,7 +159,7 @@ b000018f7903dfb44f7bff6d469a6bd5ec13ba9528893bf409bdde638589c630 docs/ja/snow-c
1ea5845f140e9e6aa932120bec2f1ff7bf3731603f39996948f561b1a1f52a7f docs/ja/stepcode.html
1eb86470ebe9f83f402d7d77ee8cd51e29f41b5ba4aed2da16b6947c0eee6bd2 docs/ja/stepfun.html
9964db876b8f2f16d2c6ea36921c2ad888d7794fac33a447a28bffa5ca1d4e83 docs/ja/subscriptions.html
5c5d5de3e22e12f28567012d832eac0408401c39dbc84ae0cd4cb7e5a3b5051f docs/ja/sync.html
354dc5d23cabee10911bba3ff3946f8561169c4dc06ddfdca05d25b093400d25 docs/ja/sync.html
cfab436ba62869c63471dbce5355f88737230e50f3c916b9b7bf79ac8434c465 docs/ja/t3-code.html
0309b9d5310b23a80bd11981b2f13c77e0f6bf9ebba12d2fd0c747bdeb0895ce docs/ja/tencent-cloud.html
7d0235fa7af13cba72826dc17f1e4bd08e5b4c115998e1c5db67879dcb890009 docs/ja/troubleshooting.html
@@ -234,7 +234,7 @@ cbf3a16eee9a07f5c1f5dda30b26787d574a79189fbe8a26ed6088aa9c962d88 docs/routing-g
48ac24aec6e88393e743659432c8edbf6b99a3ede8cee44426c4d728353b9892 docs/stepcode.html
1969c326de53bf8c97ed5580516edb8a5a6fa5375a74494abdfc913298126284 docs/stepfun.html
79eb1159590a6d4c5d1a1df8a2a6a7b158357ba2d64f62bdbf21a1bf8276e021 docs/subscriptions.html
38ed829727bc0a28d33beb8d565e6a2743812e777acf925546424c3d61745748 docs/sync.html
81460e3808d855b4b3446617b6cddc6776c71380f9e94fa4b42944c927dc0693 docs/sync.html
6b275b946ee17d91680be8c59fb57332ff3962ec06bb456c2114753af4755dba docs/t3-code.html
d14ec7a227d30a6f79037ec591a164a518d148894cdceb98b7ad6f6322b50430 docs/tencent-cloud.html
067c04117d9cc32474087b6a813d6ed475923f3bdb12022aeaba79dcd3ef65da docs/troubleshooting.html
@@ -359,7 +359,7 @@ caff76b2bba710d19f899b699b6d35f499b4907ab7e4beefbdee3c2543f556ce docs/zh/start.
f8a9f30aabfa53592dd5e548480763776a2d4913175eccd3fd6d107858a0d0c0 docs/zh/stepcode.html
dc7be40c877df9ea7ef2c9ccc6c829bdd217d3f74a2ebdf0c54a848da0cba82f docs/zh/stepfun.html
b98fe5e40042853057e726642fae823183b85b27ead65de68705a13e0ab4a318 docs/zh/subscriptions.html
5bbfedaa3d63eca4cd555e2499dcc40068f4cdb8ec0ddf54e0067d7c928b46ab docs/zh/sync.html
5533f4b82efb5bd68629fd6c9adf3f0cb263244b20cd3b07f5f4a16161c9c0f1 docs/zh/sync.html
612d90166bfa902ba8758729926ec49cad6e29be5c218821ad169c35e8798e47 docs/zh/t3-code.html
afcdb46194424409ced78a15df7beb5bc9b29da51e406e3518f24e6f1445e673 docs/zh/tencent-cloud.html
1ac57d96e52c645303c2ed6840179b540987e0d724d4ab3354549d10b09b45b3 docs/zh/troubleshooting.html
+2 -1
View File
@@ -211,9 +211,10 @@ magpie webdav undo-sync # 前回の同期で入っ
<p>同期せず新しいコンピュータに移るだけなら、暗号化バックアップファイルを使います。</p>
<div class="code"><span class="lang">ターミナル</span><button class="copy" data-copy="sy-backup">コピー</button><pre id="sy-backup">magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
magpie backup --no-keys ~/b.magpie-backup # no API keys in it
magpie backup --no-usage # no usage history in it
magpie restore magpie.magpie-backup # on the other machine
magpie restore --no-agents b.magpie-backup # agents left as they are</pre></div>
<p>手元で AES-256-GCM で暗号化し、鍵はパスフレーズから PBKDF2-SHA256 で作るので、パスフレーズなしでは読めません。復元すると同じ ID のプロバイダーは置き換え、ほかは追加します。エージェントのモデルは、そのコンピュータに入っているエージェントにだけ設定します。</p>
<p>手元で AES-256-GCM で暗号化し、鍵はパスフレーズから PBKDF2-SHA256 で作るので、パスフレーズなしでは読めません。復元すると同じ ID のプロバイダーは置き換え、ほかは追加します。エージェントのモデルは、そのコンピュータに入っているエージェントにだけ設定します。バックアップには使用履歴も入ります(--no-usage で外せます)。復元ではそのコンピュータにない呼び出しだけを足すので、二度復元しても二重には数えません。</p>
<h2 id="faq"><a class="anchor" href="#faq">よくある質問</a></h2>
<h3>magpie は坚果云(Nutstore)で同期できますか?</h3>
+2 -1
View File
@@ -211,9 +211,10 @@ magpie webdav undo-sync # put back what the last s
<p>For a move to a new computer without sync, use an encrypted backup file:</p>
<div class="code"><span class="lang">Terminal</span><button class="copy" data-copy="sy-backup">Copy</button><pre id="sy-backup">magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
magpie backup --no-keys ~/b.magpie-backup # no API keys in it
magpie backup --no-usage # no usage history in it
magpie restore magpie.magpie-backup # on the other machine
magpie restore --no-agents b.magpie-backup # agents left as they are</pre></div>
<p>It is encrypted on your machine with AES-256-GCM, the key derived from the passphrase with PBKDF2-SHA256; nothing in it can be read without the passphrase. Restoring replaces providers with the same id and adds the rest; agent models are set only for agents installed on that computer.</p>
<p>It is encrypted on your machine with AES-256-GCM, the key derived from the passphrase with PBKDF2-SHA256; nothing in it can be read without the passphrase. Restoring replaces providers with the same id and adds the rest; agent models are set only for agents installed on that computer. The file also carries the usage history (--no-usage leaves it out); a restore adds the calls that computer hasn't got, so restoring twice counts nothing twice.</p>
<h2 id="faq"><a class="anchor" href="#faq">FAQ</a></h2>
<h3>Can magpie sync through Nutstore (坚果云)?</h3>
+2 -1
View File
@@ -211,9 +211,10 @@ magpie webdav undo-sync # 撤销上次同步带来
<p>不想开同步,只是搬到新电脑,就用加密备份文件:</p>
<div class="code"><span class="lang">终端</span><button class="copy" data-copy="sy-backup">复制</button><pre id="sy-backup">magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
magpie backup --no-keys ~/b.magpie-backup # no API keys in it
magpie backup --no-usage # no usage history in it
magpie restore magpie.magpie-backup # on the other machine
magpie restore --no-agents b.magpie-backup # agents left as they are</pre></div>
<p>备份用 AES-256-GCM 在本机加密,密钥由口令经 PBKDF2-SHA256 派生,没有口令谁也读不了。恢复时同 id 的供应商被替换,其余的加上;Agent 的模型只设给那台电脑上装了的 Agent。</p>
<p>备份用 AES-256-GCM 在本机加密,密钥由口令经 PBKDF2-SHA256 派生,没有口令谁也读不了。恢复时同 id 的供应商被替换,其余的加上;Agent 的模型只设给那台电脑上装了的 Agent。备份文件里也带着用量记录(加 --no-usage 不带);恢复时只补上那台电脑没有的调用,恢复两次也不会重复计数。</p>
<h2 id="faq"><a class="anchor" href="#faq">常见问题</a></h2>
<h3>magpie 能用坚果云同步配置吗?</h3>
+2 -1
View File
@@ -10231,11 +10231,12 @@ For a move to a new computer without sync, use an encrypted backup file:
```
magpie backup # writes magpie.magpie-backup, asks for a passphrase twice
magpie backup --no-keys ~/b.magpie-backup # no API keys in it
magpie backup --no-usage # no usage history in it
magpie restore magpie.magpie-backup # on the other machine
magpie restore --no-agents b.magpie-backup # agents left as they are
```
It is encrypted on your machine with AES-256-GCM, the key derived from the passphrase with PBKDF2-SHA256; nothing in it can be read without the passphrase. Restoring replaces providers with the same id and adds the rest; agent models are set only for agents installed on that computer.
It is encrypted on your machine with AES-256-GCM, the key derived from the passphrase with PBKDF2-SHA256; nothing in it can be read without the passphrase. Restoring replaces providers with the same id and adds the rest; agent models are set only for agents installed on that computer. The file also carries the usage history (--no-usage leaves it out); a restore adds the calls that computer hasn't got, so restoring twice counts nothing twice.
## FAQ
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long