gateway: a key let use Magpie Memory reaches it from another computer

Niapyaya on X reaches their own MCP servers through the MCP hub from a
remote machine, but not magpie-memory: memory answered the agents on
this computer alone, on /mcp/magpie/memory (547585cd9) and in the hub
(HereOnly), whatever key came. That was on purpose: a friend's key
could read every memory or plant a global rule the digest writes into
every agent's instructions here.

So it stays off for every key, and the user can let one key of their
own use it:

- access.Key.Memory, set by "memory-key" (`magpie gateway-key memory
  <id> on|off`, or the key's ... > Advanced > Magpie Memory). As Admin,
  only a key the user made can have it (memoryOf): never the sharing
  key, a read-only or Browser key, nor an issued or expiring one.
  Read-only takes it away; the management API can't set it.
- memoryMCP lets a caller from elsewhere in only while magpie is
  shared, by such a key, and never from a page by hubFromPage (Origin,
  Sec-Fetch-Site, a Mozilla/ agent; Node's fetch sends Sec-Fetch-Mode,
  #5522). This computer's check is unchanged.
- The hub gives magpie-memory (HubServer.Memory, from isMemory) to an
  Away visitor only by such a key (HubVisitor.Memory), listed and run,
  in the gateway and again in the library's Call.
- Advanced in the key's menu now opens Management API and Magpie
  Memory, each its own pick; a key with it says so in its row. Strings
  in zh, zh-TW, ja, de. Docs: memory.md, mcp-router.md, and the site's
  remote page (en, zh, ja) with its index rebuilt.

Image already answers a key directly (/mcp/magpie/image, held to the
key); sessions stays this computer's. There is no skills MCP server.

Tests: TestMemoryMCPToAKeyGivenIt, TestHubGivesMemoryToAKeyLetUseIt,
TestMemoryKey, the hubServerOf Memory column, and gateway-key-admin's
GUI file now goes through Advanced > Management API and covers Memory.

Run (mote unless said; base d01e0a465, rebased onto c4bae0724, which
only touches the Settings keep guard):
- Red on the old code (mica): TestMemoryMCPToAKeyGivenIt (403 to the
  key) and TestHubGivesMemoryToAKeyLetUseIt (hub listed [docs] only).
- go test -count=1 -timeout 45m ./internal/access ./internal/gateway
  ./internal/library ./internal/cli ./internal/gui: access, library ok.
  Reds, each the same at a clean origin/main c4bae0724 and filed:
  gateway TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117) and
  the doneHold panic log (#6505); cli TestHealthcheck…/TestUpdate…
  WithoutMagpieAddr, TestUpdateFindsAMagpieThatWroteNoRecord (#6471,
  #6223); gui TestSettingsSaveKeepsWhatItDoesNotSend (fixed by
  c4bae0724).
- GUI, both engines, every language, at this head: 64 files (every
  caller-keys / gateway-plugin file and i18n-*): 1008 of 1024 pass;
  api-key-theme (#6444) and connect-address-kept (#6755) fail the same
  at clean origin/main c4bae0724.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; builds for all three OSes ok.
- Broken by hand: drop !hubFromPage -> the Sec-Fetch-Site case gets 200,
  red; drop the key's Memory check -> another key gets 200, red. Drop
  sharedWith -> still green: serveMCP's share guard refuses first, so
  memoryReaches' check is a second line, not the only one.

Not tried: a real remote agent against a real shared magpie (tests use
httptest with 192.0.2.7 as the remote address); the full suite runs
after the push.
This commit is contained in:
yetone
2026-11-19 02:31:18 +08:00
parent c4bae07248
commit 4e24994a6e
25 changed files with 535 additions and 42 deletions
+1 -1
View File
@@ -42,7 +42,7 @@ The gateway can't import the library (the library imports the gateway), so the g
- A tool turned off in the Library is neither listed nor run, for every agent, including those that have no setting of their own for it.
- A call that times out leaves the server running for the next; a server that died is started again. A server that can't be started is an error on each call, not a retry loop.
- Every process the router starts is in a `proc` tree magpie ends when the switch goes off, the server is edited, it has been idle, or the gateway stops. A test ends them in cleanup (`hubSandbox`).
- A caller from another computer (a LAN key, a tunnel or proxy here) or a web page is never given a server that acts as this computer's user (`HubServer.HereOnly`): Magpie Browser, which `/mcp/magpie/browser` refuses it directly, magpie's image server, which draws with this magpie's own token past the key's models, accounts and spend, and another magpie's router, which passes a call on to its own browser. A web page is judged by `hubFromPage` (an `Origin`, a `Sec-Fetch-Site` or a `Mozilla/` agent, which a page's POST always carries and its script can't remove), not by `Sec-Fetch-Mode`: Alma's MCP client is Node's fetch, which sends `Sec-Fetch-Mode: cors` with no Origin, and was taken for a page and left without magpie-image (chang_lochuan on X; `TestHubGivesAlmaItsHereOnlyServersNotAPage`). They are neither listed nor run, in the gateway (`hubServersOf`, `hubTools`) and again in the library (`visitorServers`, `Call`) (`TestHubKeepsThisComputersOwnServersHere`, both packages). Such a caller uses `/mcp/magpie/image` directly, held to its key. The exception is a keyed visitor's own browser: `magpie mcp browser` is `HubServer.Keyed`, given to a caller from elsewhere only when it came with a gateway key (`HubVisitor.Key`), and `hubCall` names its session `key:<id>/…`, so it reaches only a browser that connected with that same key (`TestHubGivesAKeyItsBrowser`); this computer's own browser stays here.
- A caller from another computer (a LAN key, a tunnel or proxy here) or a web page is never given a server that acts as this computer's user (`HubServer.HereOnly`): Magpie Browser, which `/mcp/magpie/browser` refuses it directly, magpie's image server, which draws with this magpie's own token past the key's models, accounts and spend, and another magpie's router, which passes a call on to its own browser. A web page is judged by `hubFromPage` (an `Origin`, a `Sec-Fetch-Site` or a `Mozilla/` agent, which a page's POST always carries and its script can't remove), not by `Sec-Fetch-Mode`: Alma's MCP client is Node's fetch, which sends `Sec-Fetch-Mode: cors` with no Origin, and was taken for a page and left without magpie-image (chang_lochuan on X; `TestHubGivesAlmaItsHereOnlyServersNotAPage`). They are neither listed nor run, in the gateway (`hubServersOf`, `hubTools`) and again in the library (`visitorServers`, `Call`) (`TestHubKeepsThisComputersOwnServersHere`, both packages). Such a caller uses `/mcp/magpie/image` directly, held to its key. The exception is a keyed visitor's own browser: `magpie mcp browser` is `HubServer.Keyed`, given to a caller from elsewhere only when it came with a gateway key (`HubVisitor.Key`), and `hubCall` names its session `key:<id>/…`, so it reaches only a browser that connected with that same key (`TestHubGivesAKeyItsBrowser`); this computer's own browser stays here. Magpie Memory (`HubServer.Memory`) is given to a caller from elsewhere only by a key the user let use it (`HubVisitor.Memory`, `access.Key.Memory`), as `/mcp/magpie/memory` answers it (`TestHubGivesMemoryToAKeyLetUseIt`; [memory](memory.md#mcp-server)).
- A gateway key with no hold reaches the Library's other command servers through the router from another computer while it is on, as it reaches plugin tools. They run with the user's rights on this computer. A key held to some models, accounts or a spend limit (`nativeHeld`) is given only the HTTP servers elsewhere (`HubServer.Program` false), not a program run here.
- A tools plugin's server (`plugin` set, [Plugin tools](plugin-tools.md)) is behind the router as any server is, but its tools are listed and run in this process through the plugin host, not over its URL, and they aren't cached: the host has them.
- A Remote magpie's server is offered once and asked for only then; a remote whose router is turned off later keeps its server (its tools list empty). The provider's own extra headers (a proxy's) aren't carried to it, and a remote with several keys is asked with its first (`p.Key`). A server the user added at another magpie's router also sends `X-Magpie-Router`, so that router leaves out its own Remote magpies' servers for it.
+21 -6
View File
@@ -78,12 +78,27 @@ and refuses empty or over-long text, an unknown kind and a bad scope
[internal/gateway/memory_mcp.go](../../internal/gateway/memory_mcp.go):
`memory_search`, `memory_save`, `memory_forget`, `memory_context`, Streamable HTTP at
`MemoryMCPPath` (`/mcp/magpie/memory`), served like the search server
(`serveMCP`) but to the agents on this computer alone, as the hub gives it
(`HereOnly`): memory is what is known about this computer's user, and its
digest goes into every agent's instructions here, so another computer's
gateway key (which may be a friend's, and may use every MCP server unless
it is held to some) and a web page, even one Settings lists, are turned
away (`TestMemoryMCPGuarded`).
(`serveMCP`) but to the agents on this computer, and to another
computer's only by a gateway key the user let use it, as the hub gives it
(`HereOnly`, `HubServer.Memory`; `memoryReaches`): memory is what is known
about this computer's user, and its digest goes into every agent's
instructions here, so any other gateway key (which may be a friend's, and
may use every MCP server unless it is held to some) and a web page, even
one Settings lists, are turned away (`TestMemoryMCPGuarded`).
- A key is let use it with `access.Key.Memory`: the key's ··· › Advanced ›
Magpie Memory on the Gateway page, or `magpie gateway-key memory <id> on`
(Niapyaya on X: an agent on a remote machine adding memories). As
`Admin`, only a key the user made can have it (`memoryOf`): never the
sharing key, a read-only or Browser key, nor an issued or expiring one
(`TestMemoryKey`). Read-only takes it away; the management API can't set
it. From elsewhere it answers only while magpie is shared
(`sharedWith`), and never to a page by `hubFromPage` (an Origin,
`Sec-Fetch-Site`, a `Mozilla/` agent), not `fromBrowser`, as Node's
fetch, the MCP SDK's transport, sends `Sec-Fetch-Mode`
(`TestMemoryMCPToAKeyGivenIt`, `TestHubGivesMemoryToAKeyLetUseIt`). Such
a caller has no folder here (`memoryCaller`), so it saves globally or
names a project by its key.
- The Library offers it in the market as `magpie-memory`
([market.go](../../internal/library/market.go)), run as
+35 -1
View File
@@ -184,6 +184,14 @@ type Key struct {
// not a read-only, browser, issued or expiring key, nor the default
// sharing key, which magpie hands to agents.
Admin string `json:"admin,omitempty"`
// Memory lets the key's agents on another computer use Magpie Memory
// (/mcp/magpie/memory, and the hub's magpie-memory), reading and
// saving what is known about this computer's user (Niapyaya on X).
// Memory's digest goes into every agent's instructions here, so it is
// never a key's by default: only a key the user made themselves can
// have it, as Admin (memoryOf). Agents on this computer use memory
// whatever it says.
Memory bool `json:"memory,omitempty"`
// Expires is when the key stops working (an issued key, IssueKey);
// zero for one that doesn't. Prune removes it a while after.
Expires time.Time `json:"expires,omitzero"`
@@ -279,6 +287,8 @@ type Identity struct {
Browser bool
// Admin is Key.Admin, "" for a key that can't have it (adminOf).
Admin string
// Memory is Key.Memory, false for a key that can't have it (memoryOf).
Memory bool
// sum is the SHA-256 of the secret the request came with, so a
// connection kept open can tell the key was rotated since (Current).
sum [32]byte
@@ -503,6 +513,8 @@ type Change struct {
Browser bool `json:"browser,omitempty"`
// Admin is what "admin-key" sets (CleanAdmin's AdminLocal, AdminAny or "").
Admin string `json:"admin,omitempty"`
// Memory is what "memory-key" sets (Key.Memory).
Memory bool `json:"memory,omitempty"`
// Issues is what "issuer-key" sets: the key may issue short-lived
// keys under itself (Key.Issues).
Issues bool `json:"issues,omitempty"`
@@ -726,6 +738,7 @@ func Update(action string, in Change) (string, error) {
keys[i].ReadOnly = in.ReadOnly
if in.ReadOnly {
keys[i].Admin = ""
keys[i].Memory = false
}
case "admin-key":
// the management API changes providers, accounts and keys, so
@@ -745,6 +758,21 @@ func Update(action string, in Change) (string, error) {
}
}
keys[i].Admin = level
case "memory-key":
// memory's digest goes into every agent's instructions here, so
// only a key the user made for their own agents elsewhere can
// read and write it, never one handed to others
if in.Memory {
switch {
case defaultKey:
return "", errors.New("The sharing key is the one magpie gives agents that reach it from elsewhere, so it can't use Magpie Memory from another computer: add a key of its own for that")
case keys[i].Browser || keys[i].ReadOnly:
return "", errors.New("A read-only key, or the Magpie Browser extension's, can't use Magpie Memory: add another key for that")
case keys[i].Issuer != "" || !keys[i].Expires.IsZero():
return "", errors.New("An issued key can't use Magpie Memory from another computer: let a key of yours do it")
}
}
keys[i].Memory = in.Memory
case "on-key", "off-key":
keys[i].Off = action == "off-key"
case "remove-key":
@@ -768,7 +796,7 @@ func Update(action string, in Change) (string, error) {
default:
return "", fmt.Errorf("unknown key action %q", action)
}
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "admin-key" && action != "move-key" {
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "admin-key" && action != "memory-key" && action != "move-key" {
mirror = &keys[i]
}
}
@@ -1047,3 +1075,9 @@ func adminOf(k Key) string {
}
return k.Admin
}
// memoryOf is whether a key really may use Magpie Memory from another
// computer: never one that can't hold it, whatever the file says.
func memoryOf(k Key) bool {
return k.Memory && k.Issuer == "" && !k.ReadOnly && !k.Browser && k.Expires.IsZero() && !k.LAN
}
+2 -2
View File
@@ -353,12 +353,12 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q names an account group, and magpie can't read its account groups now: %v", k.Name, err)}
}
k.Accounts = accounts
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Admin: adminOf(k), Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact}
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Admin: adminOf(k), Memory: memoryOf(k), Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact}
// the default key as Default tells it: marked LAN, or the id the
// settings name (settings read only for an unmarked key)
who.Default = k.LAN || (k.ID != "" && settings.Shared().LANKeyID == k.ID)
if who.Default {
who.Admin = ""
who.Admin, who.Memory = "", false
}
if k.Issuer == "" {
return who, nil
+87
View File
@@ -0,0 +1,87 @@
package access
import (
"strings"
"testing"
"time"
)
// Niapyaya on X: a key can be let use Magpie Memory from another
// computer, but only a key the user made for it, and only by the user:
// never the sharing key, a read-only or Browser key, nor an issued one.
func TestMemoryKey(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
plainID, plain := addKey(t, "plain")
if who, ok := Authenticate(plain); !ok || who.Memory {
t.Fatal("a new key has Memory")
}
for _, on := range []bool{true, false, true} {
if _, err := Update("memory-key", Change{Key: plainID, Memory: on}); err != nil {
t.Fatal(on, err)
}
if who, _ := Authenticate(plain); who.Memory != on {
t.Errorf("memory %v: Memory %v", on, who.Memory)
}
}
// read-only takes it away, and is refused it
if _, err := Update("access-key", Change{Key: plainID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
if who, _ := Authenticate(plain); who.Memory {
t.Error("a key made read-only kept Memory")
}
if _, err := Update("memory-key", Change{Key: plainID, Memory: true}); err == nil {
t.Error("a read-only key was given Memory")
}
// the extension's key
if _, err := Update("add-key", Change{Name: "ext", Browser: true}); err != nil {
t.Fatal(err)
}
keys, _ := List()
if _, err := Update("memory-key", Change{Key: keys[len(keys)-1].ID, Memory: true}); err == nil {
t.Error("the extension's key was given Memory")
}
// the sharing key, given to every agent that reaches magpie
if err := ConfigureLAN(true, false); err != nil {
t.Fatal(err)
}
keys, _ = List()
for _, k := range keys {
if k.LAN {
if _, err := Update("memory-key", Change{Key: k.ID, Memory: true}); err == nil || !strings.Contains(err.Error(), "sharing key") {
t.Errorf("the sharing key was given Memory: %v", err)
}
}
}
if who, _ := Authenticate(LANSecret()); who.Memory {
t.Error("the sharing key has Memory")
}
// an issued key, even when the file says otherwise
issuerID, _ := addKey(t, "issuer")
if _, err := Update("memory-key", Change{Key: issuerID, Memory: true}); err != nil {
t.Fatal(err)
}
if _, err := Update("issuer-key", Change{Key: issuerID, Issues: true}); err != nil {
t.Fatal(err)
}
k, err := IssueKey(Issue{Name: "sandbox", TTL: time.Hour, Issuer: issuerID})
if err != nil {
t.Fatal(err)
}
if who, ok := Authenticate(k.Key); !ok || who.Memory {
t.Error("an issued key has Memory")
}
keys, _ = List()
for _, key := range keys {
if key.Issuer != "" {
if _, err := Update("memory-key", Change{Key: key.ID, Memory: true}); err == nil || !strings.Contains(err.Error(), "issued") {
t.Errorf("an issued key was given Memory: %v", err)
}
}
}
}
+45
View File
@@ -74,6 +74,10 @@ func gatewayKeysTo(out io.Writer, args []string) error {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyAdmin(out, args[1:])
}
if action == "memory" {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyMemory(out, args[1:])
}
if action == "move" {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyMove(out, args[1:])
@@ -1021,6 +1025,47 @@ func gatewayKeyAdmin(out io.Writer, args []string) error {
return err
}
// gatewayKeyMemory shows or sets whether a key's agents on another
// computer may use Magpie Memory (/mcp/magpie/memory and the hub's
// magpie-memory), reading and saving what is known about this computer's
// user (Niapyaya on X):
//
// magpie gateway-key memory <id> [on | off]
func gatewayKeyMemory(out io.Writer, args []string) error {
usage := fmt.Errorf("usage: magpie gateway-key memory <id> [on | off]")
if len(args) == 0 || len(args) > 2 {
return usage
}
id := args[0]
if len(args) == 2 {
var on bool
switch strings.ToLower(args[1]) {
case "on":
on = true
case "off":
default:
return usage
}
if _, err := access.Update("memory-key", access.Change{Key: id, Memory: on}); err != nil {
return err
}
}
keys, err := access.List()
if err != nil {
return err
}
i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id })
if i < 0 {
return fmt.Errorf("Key not found")
}
if k := keys[i]; k.Memory {
_, err = fmt.Fprintf(out, "%s: its agents on other computers may read and save Magpie Memory, while magpie is shared\n", k.Name)
} else {
_, err = fmt.Fprintf(out, "%s: Magpie Memory only for the agents on this computer\n", k.Name)
}
return err
}
// gatewayKeyMove puts a key at a place in the list, counted from 1 as
// `magpie gateway-key list` shows them, the order the app's Gateway page
// lists them in too, where a key is dragged to its place (alextjy on
+1
View File
@@ -159,6 +159,7 @@ const usage = `magpie — one place to pick every agent's model
magpie gateway-key mcp <id> [all|none|<server>|<server>/<tool> ...] the MCP servers and tools a key may use
magpie gateway-key access <id> [read-only|full] read-only: the key reads quotas and usage (GET /, /v1/magpie/quotas, /v1/magpie/usage) and uses no model, MCP server or write
magpie gateway-key admin <id> [off|local|any] let the key manage providers, accounts and gateway keys through /v1/magpie/admin/ (local: from this computer only)
magpie gateway-key memory <id> [on|off] let the key's agents on other computers read and save Magpie Memory
magpie gateway-key move <id> <place> put a key at a place in the list (from 1), the order list and the app show them in
magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json]
a short-lived key (1m to 30 days) that stops working by itself; --from holds it to a key that issues keys; prints the key
+15 -1
View File
@@ -153,7 +153,8 @@ type HubServer struct {
// magpie's own token, past a gateway key's models, accounts and
// spend), and another magpie's router (which passes a call on to its
// own). It is given only to a caller on this computer (HubVisitor),
// Magpie Browser also to a keyed one elsewhere (Keyed).
// Magpie Browser also to a keyed one elsewhere (Keyed), and Magpie
// Memory to one elsewhere by a key let use it (Memory).
HereOnly bool
// Program: the server is a program run on this computer, with the
// user's rights (a command, or a tools plugin), not an HTTP server
@@ -165,6 +166,12 @@ type HubServer struct {
// and to another computer's caller with a key, and calls go to that
// key's browsers only.
Keyed bool
// Memory: the server is Magpie Memory (`magpie mcp memory`), which
// holds what is known about this computer's user and writes into
// every agent's instructions here: given to this computer, and to
// another computer's caller by a key the user let use it
// (access.Key.Memory), as memoryReaches holds its own route.
Memory bool
}
// HubVisitor is who a hub request is from, for what it is given of the
@@ -176,6 +183,9 @@ type HubServer struct {
type HubVisitor struct {
Away, Held bool
Key string
// Memory: an Away visitor by a key let use Magpie Memory
// (access.Key.Memory), given that server (HubServer's Memory).
Memory bool
}
// Gives is whether v is given s.
@@ -186,6 +196,9 @@ func (v HubVisitor) Gives(s HubServer) bool {
if s.Keyed {
return v.Key != ""
}
if s.Memory {
return v.Memory
}
return !s.HereOnly && !(v.Held && s.Program)
}
@@ -209,6 +222,7 @@ func hubVisitor(r *http.Request) HubVisitor {
v := HubVisitor{Away: away, Held: away && nativeHeld(access.Caller(r.Context()))}
if !local(r) && !hubFromPage(r) {
v.Key = access.Caller(r.Context()).KeyID
v.Memory = access.Caller(r.Context()).Memory
}
return v
}
+74
View File
@@ -225,3 +225,77 @@ func TestHubGivesAlmaItsHereOnlyServersNotAPage(t *testing.T) {
t.Fatalf("ran for a page: %q", got)
}
}
// Magpie Memory goes through the hub to another computer's caller by a
// gateway key the user let use it (access.Key.Memory, Niapyaya on X), as
// /mcp/magpie/memory answers it: listed and run. Another key, the key
// sent by a web page and the key once memory is taken away aren't given
// it, and it never runs for them.
func TestHubGivesMemoryToAKeyLetUseIt(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
servers := []HubServer{
{Name: "magpie-memory", HereOnly: true, Program: true, Memory: true},
{Name: "magpie-image", HereOnly: true, Program: true},
{Name: "docs"},
}
var tools []HubTool
for _, s := range servers {
tools = append(tools, HubTool{Server: s.Name, Tool: "do", Spec: hubSpec("do")})
}
f := &fakeHub{on: true, tools: map[string][]HubTool{"": tools}, servers: map[string][]HubServer{"": servers}}
withHub(t, f)
h := lanGuard(New().Handler())
keys, secrets := newCaller(t, "Remote box", "Friend")
if _, err := access.Update("memory-key", access.Change{Key: keys[0].ID, Memory: true}); err != nil {
t.Fatal(err)
}
const there = "192.0.2.7:4000"
listed := func(hdr ...string) []string {
t.Helper()
m := readMCP(t, hubPostAt(h, HubMCPAll, there, toolsList, hdr...))
var out []string
for _, t := range m.Result.Tools {
out = append(out, strings.TrimSuffix(t.Name, hubSep+"do"))
}
slices.Sort(out)
return out
}
given := []string{"Authorization", "Bearer " + secrets[0]}
other := []string{"Authorization", "Bearer " + secrets[1]}
page := append([]string{"Origin", "https://evil.example"}, given...)
browser := append([]string{"User-Agent", "Mozilla/5.0 (Macintosh) Chrome/140"}, given...)
if got, want := listed(given...), []string{"docs", "magpie-memory"}; !slices.Equal(got, want) {
t.Errorf("the key let use memory is given %v, want %v", got, want)
}
m := readMCP(t, hubPostAt(h, HubMCPAll, there, toolsCall("magpie-memory"+hubSep+"do", `{}`), given...))
if m.Error != nil || m.Result.IsError {
t.Fatalf("memory for the key let use it: %+v", m)
}
if got := f.ran(); len(got) != 1 {
t.Fatalf("ran %q, want magpie-memory once", got)
}
if got, want := listed(other...), []string{"docs"}; !slices.Equal(got, want) {
t.Errorf("another key is given %v, want %v", got, want)
}
for _, auth := range [][]string{other, browser} {
m := readMCP(t, hubPostAt(h, HubMCPAll, there, toolsCall("magpie-memory"+hubSep+"do", `{}`), auth...))
if m.Error == nil && !m.Result.IsError {
t.Errorf("memory ran for %v: %+v", auth, m)
}
}
if w := hubPostAt(h, HubMCPAll, there, toolsList, page...); w.Code == http.StatusOK && strings.Contains(w.Body.String(), "magpie-memory") {
t.Errorf("a page with the key is given memory: %s", w.Body.String())
}
if _, err := access.Update("memory-key", access.Change{Key: keys[0].ID}); err != nil {
t.Fatal(err)
}
if got, want := listed(given...), []string{"docs"}; !slices.Equal(got, want) {
t.Errorf("once taken away, the key is given %v, want %v", got, want)
}
if got := f.ran(); len(got) != 1 {
t.Fatalf("memory ran for a caller not given it: %q", got)
}
}
+21 -7
View File
@@ -13,6 +13,7 @@ import (
"sync"
"time"
"github.com/yetone/magpie/internal/access"
// search by meaning, when switched on (memory.Semantic)
_ "github.com/yetone/magpie/internal/memembed"
"github.com/yetone/magpie/internal/memory"
@@ -54,18 +55,31 @@ const (
const memoryServerName = "magpie-memory"
func (s *Server) memoryMCP(w http.ResponseWriter, r *http.Request) {
// what is known about this computer's user, and what goes into every
// agent's instructions here (the digest): only an agent on this
// computer reads or writes it, as the hub gives it (HereOnly). Another
// computer's gateway key, which may be a friend's, and a web page,
// even one Settings lists, are turned away.
if !local(r) || fromBrowser(r) {
http.Error(w, "magpie's memory MCP server answers the agents on this computer alone", http.StatusForbidden)
if !memoryReaches(r) {
http.Error(w, "magpie's memory MCP server answers the agents on this computer, and another computer's only while magpie is shared and by a gateway key let use Magpie Memory (the key's ··· › Advanced in magpie's gateway keys, or `magpie gateway-key memory <id> on`); never a web page", http.StatusForbidden)
return
}
serveMCP(w, r, "magpie's memory", memoryServerName, 1<<20, s.memoryMCPCall)
}
// memoryReaches is whether r may read and write magpie's memory: what is
// known about this computer's user, and what goes into every agent's
// instructions here (the digest). An agent on this computer may; another
// computer's only while magpie is shared, by a gateway key the user let
// use it themselves (access.Key.Memory, Niapyaya on X: an agent on a
// remote machine saving to it), as the hub gives it (HubVisitor's
// Memory). Any other key, which may be a friend's and uses every MCP
// server unless held to some, and a web page, one Settings lists and that
// sends a key included, are turned away. From elsewhere a page is told by
// hubFromPage, not fromBrowser, whose Sec-Fetch-Mode Node's fetch sends
// too (#5522): the MCP SDK's own transport, which a remote agent uses.
func memoryReaches(r *http.Request) bool {
if local(r) {
return !fromBrowser(r)
}
return sharedWith(r) && access.Caller(r.Context()).Memory && !hubFromPage(r)
}
var memoryKinds = strings.Join(memory.Kinds, ", ")
func memoryMCPTools() []any {
+90 -2
View File
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/memory"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
@@ -188,8 +189,9 @@ func TestMemoryMCPSaysWhatItCantKnow(t *testing.T) {
// Memory is this computer's user's, and its digest goes into the agents'
// instructions here: another computer is turned away, shared or not, with
// a gateway key or without, and so is a web page, one Settings lists too;
// none of them reads, saves or forgets a memory.
// a gateway key or without (one not let use memory: TestMemoryMCPToAKey
// GivenIt), and so is a web page, one Settings lists too; none of them
// reads, saves or forgets a memory.
func TestMemoryMCPGuarded(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
@@ -245,6 +247,92 @@ func TestMemoryMCPGuarded(t *testing.T) {
}
}
// A gateway key the user let use Magpie Memory (access.Key.Memory,
// Niapyaya on X: an agent on a remote machine adding memories) reads and
// saves it from another computer while magpie is shared. Nothing else
// from there does: no key, another key, the key once memory is taken
// away, the key while magpie isn't shared, and the key sent by a web page
// (an Origin, Sec-Fetch-Site, a browser's User-Agent).
func TestMemoryMCPToAKeyGivenIt(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
h := lanGuard(New().Handler())
if said, isErr := memPost(t, h, memorySaveTool, `{"text":"The user writes Go with any, never interface{}","kind":"preference","scope":"global"}`); isErr {
t.Fatal(said)
}
keys, secrets := newCaller(t, "Remote box", "Friend") // shares magpie
if _, err := access.Update("memory-key", access.Change{Key: keys[0].ID, Memory: true}); err != nil {
t.Fatal(err)
}
const there = "192.0.2.7:4000"
search := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory_search","arguments":{}}}`
save := func(text string) string {
return `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"memory_save","arguments":{"text":"` + text + `","kind":"preference","scope":"global"}}}`
}
refused := func(why string, hdr ...string) {
t.Helper()
for _, body := range []string{search, save("Refused " + why)} {
w := mcpPostTo(h, MemoryMCPPath, there, body, hdr...)
// no key is the share's own 401; the rest memory's 403
if (w.Code != http.StatusForbidden && w.Code != http.StatusUnauthorized) || strings.Contains(w.Body.String(), "interface") {
t.Fatalf("%s: %d %s", why, w.Code, w.Body.String())
}
}
}
key := []string{"Authorization", "Bearer " + secrets[0]}
// the key let use it reads and saves
got := readMCP(t, mcpPostTo(h, MemoryMCPPath, there, search, key...))
if got.Error != nil || got.Result.IsError || !strings.Contains(got.Result.Content[0].Text, "interface{}") {
t.Fatalf("search with the key: %+v", got)
}
got = readMCP(t, mcpPostTo(h, MemoryMCPPath, there, save("Deploys go through the staging box first"), key...))
if got.Error != nil || got.Result.IsError {
t.Fatalf("save with the key: %+v", got)
}
if said, isErr := memPost(t, h, memorySearchTool, `{}`); isErr || !strings.Contains(said, "staging box") {
t.Fatalf("what the remote agent saved isn't here: %v %s", isErr, said)
}
refused("no key")
refused("another key", "Authorization", "Bearer "+secrets[1])
refused("a page's Origin", append([]string{"Origin", "https://evil.example"}, key...)...)
refused("a page's Sec-Fetch-Site", append([]string{"Sec-Fetch-Site", "cross-site"}, key...)...)
refused("a browser", append([]string{"User-Agent", "Mozilla/5.0 (Macintosh) Chrome/140"}, key...)...)
// Node's fetch, the MCP SDK's own transport, sends Sec-Fetch-Mode
// (#5522): it is an agent, not a page
got = readMCP(t, mcpPostTo(h, MemoryMCPPath, there, search, append([]string{"Sec-Fetch-Mode", "cors", "User-Agent", "node"}, key...)...))
if got.Error != nil || got.Result.IsError {
t.Fatalf("Node's fetch with the key: %+v", got)
}
st := settings.Load()
st.LAN = false
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
refused("not shared", key...)
st.LAN = true
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
if _, err := access.Update("memory-key", access.Change{Key: keys[0].ID}); err != nil {
t.Fatal(err)
}
refused("memory taken away", key...)
l, _, err := memory.All()
if err != nil {
t.Fatal(err)
}
for _, m := range l {
if strings.Contains(m.Text, "Refused") {
t.Fatalf("a refused caller saved %q", m.Text)
}
}
}
func TestRootDirs(t *testing.T) {
got := rootDirs([]string{"file:///Users/a/p", "https://x/y", "file:///C:/w/p"})
if len(got) != 2 || got[0] != filepath.FromSlash("/Users/a/p") {
+20
View File
@@ -788,6 +788,11 @@ const I18N = {
"From any computer": "任何电脑均可",
"Management API": "管理 API",
"Manages magpie": "可管理 magpie",
"Magpie Memory": "Magpie Memory",
"{name} can read and save Magpie Memory from any computer": "{name} 现在可在任何电脑上读写 Magpie Memory",
"{name} uses Magpie Memory from this computer only": "{name} 只在本机使用 Magpie Memory",
"Memory from any computer": "任何电脑可用记忆",
"This key's agents on other computers can read and save Magpie Memory while magpie is shared": "共享 magpie 时,其他电脑上用这个密钥的 Agent 可以读写 Magpie Memory",
"{name} can manage magpie from this computer": "{name} 现在可在本机管理 magpie",
"{name} can manage magpie from any computer": "{name} 现在可在任何电脑上管理 magpie",
"{name} can't manage magpie": "{name} 不再能管理 magpie",
@@ -6293,6 +6298,11 @@ const I18N = {
"From any computer": "任何電腦均可",
"Management API": "管理 API",
"Manages magpie": "可管理 magpie",
"Magpie Memory": "Magpie Memory",
"{name} can read and save Magpie Memory from any computer": "{name} 現在可在任何電腦上讀寫 Magpie Memory",
"{name} uses Magpie Memory from this computer only": "{name} 只在本機使用 Magpie Memory",
"Memory from any computer": "任何電腦可用記憶",
"This key's agents on other computers can read and save Magpie Memory while magpie is shared": "共享 magpie 時,其他電腦上用這個金鑰的 Agent 可以讀寫 Magpie Memory",
"{name} can manage magpie from this computer": "{name} 現在可在本機管理 magpie",
"{name} can manage magpie from any computer": "{name} 現在可在任何電腦上管理 magpie",
"{name} can't manage magpie": "{name} 不再能管理 magpie",
@@ -11754,6 +11764,11 @@ const I18N = {
"From any computer": "どのコンピュータからでも",
"Management API": "管理 API",
"Manages magpie": "magpie を管理",
"Magpie Memory": "Magpie Memory",
"{name} can read and save Magpie Memory from any computer": "{name} はどのコンピュータからでも Magpie Memory を読み書きできます",
"{name} uses Magpie Memory from this computer only": "{name} はこのコンピュータでのみ Magpie Memory を使います",
"Memory from any computer": "どこからでもメモリー",
"This key's agents on other computers can read and save Magpie Memory while magpie is shared": "magpie を共有している間、ほかのコンピュータでこのキーを使うエージェントが Magpie Memory を読み書きできます",
"{name} can manage magpie from this computer": "{name} はこのコンピュータから magpie を管理できます",
"{name} can manage magpie from any computer": "{name} はどのコンピュータからでも magpie を管理できます",
"{name} can't manage magpie": "{name} は magpie を管理できなくなりました",
@@ -17235,6 +17250,11 @@ const I18N = {
"From any computer": "Von jedem Computer",
"Management API": "Verwaltungs-API",
"Manages magpie": "Verwaltet magpie",
"Magpie Memory": "Magpie Memory",
"{name} can read and save Magpie Memory from any computer": "{name} kann Magpie Memory von jedem Computer aus lesen und speichern",
"{name} uses Magpie Memory from this computer only": "{name} nutzt Magpie Memory nur von diesem Computer aus",
"Memory from any computer": "Memory von jedem Computer",
"This key's agents on other computers can read and save Magpie Memory while magpie is shared": "Agents auf anderen Computern können mit diesem Schlüssel Magpie Memory lesen und speichern, solange magpie geteilt ist",
"{name} can manage magpie from this computer": "{name} kann magpie von diesem Computer aus verwalten",
"{name} can manage magpie from any computer": "{name} kann magpie von jedem Computer aus verwalten",
"{name} can't manage magpie": "{name} kann magpie nicht mehr verwalten",
+34 -4
View File
@@ -234,7 +234,7 @@ function renderGatewayKeys() {
tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id });
// the copy sits by the key it copies (the owner: stranded among the
// badges it read as nobody's); Rotate and Remove wait in the row's menu
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : k.admin && gatewayKeyCanAdmin(k) ? [gatewayAdminTag(k)] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k), gatewayRedactBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k));
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : k.admin && gatewayKeyCanAdmin(k) ? [gatewayAdminTag(k)] : []), ...(k.memory && gatewayKeyCanAdmin(k) ? [gatewayMemoryTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k), gatewayRedactBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k));
const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u));
if (under.length) row.classList.add("with-limit"), row.append(...under);
list.append(row);
@@ -350,9 +350,10 @@ function gatewayKeyMore(k) {
...(k.browser || k.readOnly ? [] : [{ name: "Model names", icon: MCP_GLYPH, run: () => gatewayAliasesAsk(k) }]),
...(k.browser ? [] : [{ name: "Keep accounts out", icon: KEEP_OUT_GLYPH, run: () => gatewayKeptOutPick(k, more) }]),
{ name: "Rotate key", icon: ROTATE_GLYPH, run: () => askGatewayKey(k, true) },
// the management API (#6307, ljayic on X), seldom set, so under
// Advanced; only a key the user made can hold it (access's adminOf)
...(gatewayKeyCanAdmin(k) ? [{ name: "Advanced", icon: ADVANCED_GLYPH, run: () => gatewayAdminPick(k, more) }] : []),
// the management API (#6307, ljayic on X) and Magpie Memory from
// other computers (Niapyaya on X), seldom set, so under Advanced;
// only a key the user made can hold them (access's adminOf, memoryOf)
...(gatewayKeyCanAdmin(k) ? [{ name: "Advanced", icon: ADVANCED_GLYPH, run: () => gatewayAdvanced(k, more) }] : []),
{ name: "Remove", icon: REMOVE_GLYPH, sep: true, run: () => askGatewayKey(k, false) },
]);
};
@@ -366,6 +367,35 @@ const ADVANCED_GLYPH = "M2.5 4.5h6M11.5 4.5h2M2.5 11.5h2M7.5 11.5h6M10 3v3M6 10v
function gatewayKeyCanAdmin(k) {
return !k.lan && !k.browser && !k.readOnly && !k.issuer && !k.expires;
}
// gatewayAdvanced is a key's seldom-set grants, each its own pick
function gatewayAdvanced(k, anchor) {
openRowMenu(anchor, [
{ name: "Management API", icon: ADVANCED_GLYPH, run: () => gatewayAdminPick(k, anchor) },
{ name: "Magpie Memory", icon: MEMORY_GLYPH, run: () => gatewayMemoryPick(k, anchor) },
]);
}
const MEMORY_GLYPH = "M3 3.5h10v9H3zM5.5 6h5M5.5 8h5M5.5 10h3";
// gatewayMemoryPick sets whether the key's agents on other computers may
// read and save Magpie Memory (/mcp/magpie/memory and the hub's
// magpie-memory, Niapyaya on X). This computer's agents always may.
function gatewayMemoryPick(k, anchor) {
const opts = [
{ v: "", name: "From this computer" },
{ v: "any", name: "From any computer" },
];
openProtoMenu(anchor, opts, k.memory ? "any" : "", async (v) => {
if (v === (k.memory ? "any" : "")) return;
const out = await gatewayKeyAction("memory-key", { key: k.id, memory: v === "any" });
if (out) status(t(v ? "{name} can read and save Magpie Memory from any computer" : "{name} uses Magpie Memory from this computer only", { name: k.name }), "ok");
}, "Magpie Memory", "sess-menu");
}
// a key whose agents elsewhere read and save Magpie Memory says so in its
// row, always: what it saves goes into every agent's instructions here
function gatewayMemoryTag() {
const tag = el("span", "amodels key-readonly key-memory set", t("Memory from any computer"));
tag.title = t("This key's agents on other computers can read and save Magpie Memory while magpie is shared");
return tag;
}
// gatewayAdminPick sets how the key may use the management API
// (/v1/magpie/admin/): not at all, from this computer, or from any
async function gatewayAdminPick(k, anchor) {
+1
View File
@@ -188,6 +188,7 @@ function fixture(lang, theme, events, options = {}) {
if (action === "remove-key") keys = keys.filter((v) => v !== k);
if (action === "on-key" || action === "off-key") k.off = action === "off-key";
if (action === "admin-key") k.admin = body.admin || undefined;
if (action === "memory-key") k.memory = body.memory || undefined;
if (action === "limit-key") {
// what a key has used is the fixture's; a new limit starts unused
const usedOf = (l) => {
+36 -11
View File
@@ -1,23 +1,25 @@
// A gateway key is given the management API (/v1/magpie/admin/, #6307,
// ljayic on X) from its row's menu, under Advanced: off, from this
// computer or from any. A key that can manage magpie says so in its row.
// The sharing key, a read-only key and Magpie Browser's can't hold it,
// so their menus don't offer it.
// Beside it, Advanced lets a key's agents on other computers read and
// save Magpie Memory (Niapyaya on X), and such a key says so in its row.
// The sharing key, a read-only key and Magpie Browser's can't hold
// either, so their menus don't offer them.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
const words = {
en: { more: "Key actions", adv: "Advanced", head: "Management API", off: "Off", local: "From this computer", any: "From any computer", tag: "Manages magpie", madeLocal: "Server can manage magpie from this computer", madeOff: "Server can't manage magpie" },
zh: { more: "密钥操作", adv: "高级", head: "管理 API", off: "关闭", local: "仅限本机", any: "任何电脑均可", tag: "可管理 magpie", madeLocal: "Server 现在可在本机管理 magpie", madeOff: "Server 不再能管理 magpie" },
"zh-TW": { more: "金鑰操作", adv: "進階", head: "管理 API", off: "關閉", local: "僅限本機", any: "任何電腦均可", tag: "可管理 magpie", madeLocal: "Server 現在可在本機管理 magpie", madeOff: "Server 不再能管理 magpie" },
ja: { more: "キーの操作", adv: "詳細設定", head: "管理 API", off: "オフ", local: "このコンピュータから", any: "どのコンピュータからでも", tag: "magpie を管理", madeLocal: "Server はこのコンピュータから magpie を管理できます", madeOff: "Server は magpie を管理できなくなりました" },
de: { more: "Schlüsselaktionen", adv: "Erweitert", head: "Verwaltungs-API", off: "Aus", local: "Von diesem Computer", any: "Von jedem Computer", tag: "Verwaltet magpie", madeLocal: "Server kann magpie von diesem Computer aus verwalten", madeOff: "Server kann magpie nicht mehr verwalten" },
en: { more: "Key actions", adv: "Advanced", head: "Management API", off: "Off", local: "From this computer", any: "From any computer", tag: "Manages magpie", madeLocal: "Server can manage magpie from this computer", madeOff: "Server can't manage magpie", mem: "Magpie Memory", memTag: "Memory from any computer", memOn: "Server can read and save Magpie Memory from any computer", memOff: "Server uses Magpie Memory from this computer only" },
zh: { more: "密钥操作", adv: "高级", head: "管理 API", off: "关闭", local: "仅限本机", any: "任何电脑均可", tag: "可管理 magpie", madeLocal: "Server 现在可在本机管理 magpie", madeOff: "Server 不再能管理 magpie", mem: "Magpie Memory", memTag: "任何电脑可用记忆", memOn: "Server 现在可在任何电脑上读写 Magpie Memory", memOff: "Server 只在本机使用 Magpie Memory" },
"zh-TW": { more: "金鑰操作", adv: "進階", head: "管理 API", off: "關閉", local: "僅限本機", any: "任何電腦均可", tag: "可管理 magpie", madeLocal: "Server 現在可在本機管理 magpie", madeOff: "Server 不再能管理 magpie", mem: "Magpie Memory", memTag: "任何電腦可用記憶", memOn: "Server 現在可在任何電腦上讀寫 Magpie Memory", memOff: "Server 只在本機使用 Magpie Memory" },
ja: { more: "キーの操作", adv: "詳細設定", head: "管理 API", off: "オフ", local: "このコンピュータから", any: "どのコンピュータからでも", tag: "magpie を管理", madeLocal: "Server はこのコンピュータから magpie を管理できます", madeOff: "Server は magpie を管理できなくなりました", mem: "Magpie Memory", memTag: "どこからでもメモリー", memOn: "Server はどのコンピュータからでも Magpie Memory を読み書きできます", memOff: "Server はこのコンピュータでのみ Magpie Memory を使います" },
de: { more: "Schlüsselaktionen", adv: "Erweitert", head: "Verwaltungs-API", off: "Aus", local: "Von diesem Computer", any: "Von jedem Computer", tag: "Verwaltet magpie", madeLocal: "Server kann magpie von diesem Computer aus verwalten", madeOff: "Server kann magpie nicht mehr verwalten", mem: "Magpie Memory", memTag: "Memory von jedem Computer", memOn: "Server kann Magpie Memory von jedem Computer aus lesen und speichern", memOff: "Server nutzt Magpie Memory nur von diesem Computer aus" },
};
const keys = () => [
{ id: "ops", name: "Ops", masked: "sk-magpie-key-…000000", admin: "any" },
{ id: "ops", name: "Ops", masked: "sk-magpie-key-…000000", admin: "any", memory: true },
{ id: "server", name: "Server", masked: "sk-magpie-key-…222222" },
{ id: "laptop", name: "Laptop", masked: "sk-magpie-key-…111111", readOnly: true },
{ id: "magpie", name: "Magpie", masked: "sk-magpie-key-…444444", lan: true },
@@ -47,12 +49,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await row(id).getByRole("button", { name: w.more, exact: true }).click();
await page.locator(".row-menu").waitFor();
};
const levels = async (id) => {
const levels = async (id, head = w.head) => {
await menu(id);
await item(w.adv).click();
await item(head).click();
await page.locator(".proto-menu").waitFor();
assert.equal((await page.locator(".proto-menu .pm-head").textContent()).trim(), w.head);
assert.equal((await page.locator(".proto-menu .pm-head").textContent()).trim(), head);
};
const memTag = (id) => row(id).locator(".key-memory");
const memories = () => events.filter((e) => e.action === "memory-key").map((e) => e.body);
const admins = () => events.filter((e) => e.action === "admin-key").map((e) => e.body);
// a key that can manage magpie says so always, not only on hover
@@ -90,14 +95,34 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await level(w.any).getAttribute("aria-checked"), "true");
await page.keyboard.press("Escape");
// Magpie Memory from other computers: off unless given, and said
// in the row while on
assert.equal((await memTag("ops").textContent()).trim(), w.memTag);
assert.ok((await memTag("ops").getAttribute("title")).length > 10, "the memory tag says what it means");
assert.equal(await memTag("server").count(), 0);
await levels("server", w.mem);
assert.equal(await level(w.local).getAttribute("aria-checked"), "true");
await level(w.any).click();
await page.waitForFunction(() => !!document.querySelector('#gatewayKeys .acc[data-key="server"] .key-memory'));
assert.deepEqual(memories(), [{ key: "server", memory: true }]);
assert.equal((await page.locator("#status").textContent()).trim(), w.memOn);
await levels("server", w.mem);
assert.equal(await level(w.any).getAttribute("aria-checked"), "true");
await level(w.local).click();
await page.waitForFunction(() => !document.querySelector('#gatewayKeys .acc[data-key="server"] .key-memory'));
assert.deepEqual(memories().at(-1), { key: "server", memory: false });
assert.equal((await page.locator("#status").textContent()).trim(), w.memOff);
// keys that can't hold it aren't offered it
for (const id of ["laptop", "magpie", "ext"]) {
await menu(id);
assert.equal(await item(w.adv).count(), 0, `${id} offers the management API`);
await page.keyboard.press("Escape");
assert.equal(await tag(id).count(), 0);
assert.equal(await memTag(id).count(), 0);
}
assert.equal(admins().length, 2);
assert.equal(memories().length, 2);
assert.deepEqual(await scrolled(), before, "a click moved the page");
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
@@ -105,7 +130,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const rowBox = await row("ops").boundingBox(), b = await tag("ops").boundingBox();
assert.ok(b.x >= rowBox.x && b.x + b.width <= rowBox.x + rowBox.width + 1, "the tag runs out of its row");
assert.equal(await page.locator("select").count(), 0, "no native select");
const borders = await page.locator("#gatewayKeys .key-admin").evaluateAll((els) => els.map((e) => {
const borders = await page.locator("#gatewayKeys .key-admin, #gatewayKeys .key-memory").evaluateAll((els) => els.map((e) => {
const c = getComputedStyle(e);
return { left: c.borderLeftStyle, right: c.borderRightStyle, leftColor: c.borderLeftColor, rightColor: c.borderRightColor };
}));
+1 -1
View File
@@ -176,7 +176,7 @@ func writeCards(m map[string]hubCard) {
// for, else what it says of itself; its title; and its tools but those
// turned off, as it last listed them.
func hubServerOf(s *Server) gateway.HubServer {
out := gateway.HubServer{Name: s.Name, About: serverAbout(s), Bridge: s.Bridge != "", HereOnly: hereOnly(s), Program: s.Plugin != "" || !s.Remote(), Keyed: keepsSession(s) && !s.Remote()}
out := gateway.HubServer{Name: s.Name, About: serverAbout(s), Bridge: s.Bridge != "", HereOnly: hereOnly(s), Program: s.Plugin != "" || !s.Remote(), Keyed: keepsSession(s) && !s.Remote(), Memory: isMemory(s)}
c := cardOf(s)
if c == nil {
return out
+4
View File
@@ -887,6 +887,10 @@ func TestHubKeepsThisComputersOwnServersHere(t *testing.T) {
if got, want := hubServerOf(&c.s).Keyed, len(c.s.Args) > 1 && c.s.Args[1] == "browser"; got != want {
t.Errorf("%+v: keyed %v, want %v", c.s, got, want)
}
// only Magpie Memory goes to a key let use it (gateway.HubServer's Memory)
if got, want := hubServerOf(&c.s).Memory, len(c.s.Args) > 1 && c.s.Args[1] == "memory"; got != want {
t.Errorf("%+v: memory %v, want %v", c.s, got, want)
}
}
keyed := gateway.WithHubVisitor(here, gateway.HubVisitor{Away: true, Key: "k1"})
if got := servers(keyed); !slices.Equal(got, []string{"fake", browserServerName}) && !slices.Equal(got, []string{browserServerName, "fake"}) {
+3 -3
View File
@@ -150,7 +150,7 @@ edc48cb9c5cab1dc68dc37a45301de5d5aad2d9493644d9cbd5e8cffc440e04f docs/ja/qwen.h
bca931e9d9b38c9731b66bd9826a90b17517430604efc79c70fdc54642aad860 docs/ja/raycast.html
102f231724d15be5dbb900b2578996360dd42bbb3bff00eb36735c6079cfb371 docs/ja/reasonix.html
1f79eb94c513c1d4bcefb645dfcb7264e3e22235ebd601c0d96aaea72dad30c7 docs/ja/relay.html
cab90e2a6a8f7ae00a798f7e0a718cc2192be9a24c7bc5a888c57f70363807b1 docs/ja/remote.html
765a718e2b95c3f576cbc6ed731b7f05ee3f5c54c73105961bd7852d6c78e593 docs/ja/remote.html
c7070237e2a6b86e43a2a22c43d72a8a6a36e00c7f9877028d5a7fbbeceaafcb docs/ja/routing-groups.html
ae657d3db2c4cfacb886a228bc97c3c074d83d3bed441ad60c01931325e3fe44 docs/ja/shelley.html
f2f8e870c8fd1f14483d223ad834b1c99b64c6e39a02b7bd0b12ab74e239624c docs/ja/siliconflow.html
@@ -225,7 +225,7 @@ fa0abe144eb2d7ba48885d1678da96c0082b56a00c7f3af13cdfc69add50a121 docs/quota.htm
5a080ad90e3b09d6ab0824dd18a64415c1ac49802643c882c68c71fc12f1893f docs/raycast.html
5b78f68002ecda11bd702508c804784d10b0d868ad168ff724037c62ed305798 docs/reasonix.html
68f3a707c0bddad8235b98bdea01fd65cbbed787dbabfb2ff1bd067402d5ba48 docs/relay.html
0e05b67d73868a8c88f95ebc8fc1f815c459fbf7fcef13da5837cdb4a5a148c8 docs/remote.html
a7f83a1373e18562e59f50220d1bf5fabaa145b87aa00233086f28d625412f39 docs/remote.html
cbf3a16eee9a07f5c1f5dda30b26787d574a79189fbe8a26ed6088aa9c962d88 docs/routing-groups.html
9c22ec06ed58767bdb661e8ccb6bf324ee42d94ef74fe27e6a05b53885316d3d docs/shelley.html
6f431de880c17c89b081bb424ea551ba48f1502b11c656c6af28c222acf7419e docs/siliconflow.html
@@ -350,7 +350,7 @@ d77d78aa72937c4756d65f286460e3dbcaa2c216a586e9d06486d5f3d967c1b6 docs/zh/quota.
04fbd0c8ea71f091ad0b59e8afff7aa937a19c3385b10d0de84a6b5ad33ccde1 docs/zh/raycast.html
90b30d2a659a4be508c00493b8b8f32ac5fe3da8d8c9078cbd7e486d39632381 docs/zh/reasonix.html
049a712b80c51e3305610a56bbc1f1928278cb8bdf1c29a26bf88f768f3f0ed5 docs/zh/relay.html
08bcdd1e6d5d37ae1021e17bbe7cb0cef122ada822e857ff9bcd9b4bca21deec docs/zh/remote.html
549388c73f5e90ff20c21da689c958056f84668ba9a45e0383cda3f94116beb6 docs/zh/remote.html
b2218124e8755dad24e20ecccf7938c9b30e8ae51de574ce46c1514d871ce0c4 docs/zh/routing-groups.html
1d4b1922da7504bbcf8f6c6b8a77d3688fc877d0a1188c9d3d3d3f9b29deafc6 docs/zh/shelley.html
57da389d7a92c3ae1da447f06fb63f4437f16a2c775476f9e25eba40391e41ad docs/zh/siliconflow.html
+10
View File
@@ -261,6 +261,16 @@ curl -s -X POST http://127.0.0.1:3425/v1/magpie/admin/gateway-keys/add-key \
<p>アプリ自身のページと同じ処理が <code>/v1/magpie/admin/</code> の下にあります。<code>GET providers</code>、<code>POST provider/{save,delete,on,off,name,…}</code>、<code>POST keys/…</code>(プロバイダーのキー)、<code>GET</code>/<code>POST gateway-keys[/{add-key,rename-key,limit-key,models-key,remove-key,…}]</code>、<code>GET</code>/<code>POST account-groups[/…]</code>、<code>GET routing-groups[/{id}]</code> と <code>POST routing-groups/{create,update,delete,switch,…}</code>(ルーティングページのグループと組み合わせ。検証はアプリと同じで、<code>update</code> は送ったフィールドだけを変えます)、そして <code>POST signin</code>(<code>{"agent":…}</code>)は、ベンダーのページと入力するコードを返し、パスワードは受け取りません。ブラウザーのあるコンピューターで開いてください。保存済みのキーとゲートウェイキーの秘密は再び返されず、このコンピューターのほかのアプリを変更する操作も提供しません。サインインはエクスポートしません。すべてのアカウントの秘密を渡すことになるからです。</p>
<p>読み取り専用キー、拡張機能のキー、発行されたキーや短期キー、共有キーは使えません。キーの有無にかかわらず Web ページからは呼べません(<code>Origin</code> や <code>Sec-Fetch-*</code> を持つリクエストはすべて拒否)。このコンピューターの別名で届いたリクエストも拒否されます。ネットワーク越しに共有している場合、<code>any</code> のキーだけが通ります。</p>
<h2 id="memory"><a class="anchor" href="#memory">ほかのコンピュータからのメモリー</a></h2>
<p>Magpie Memory はこのコンピュータのエージェントに応えます。ほかのコンピュータのエージェントにも読み書きさせるには、そのエージェント専用のゲートウェイキーを作って許可します。アプリのキーのメニュー › 詳細設定 › Magpie Memory から、またはコマンドラインで:</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-memory">コピー</button>
<pre id="ex-memory">magpie gateway-key add remote-box
magpie gateway-key memory &lt;id&gt; on</pre>
</div>
<p>magpie を共有している間、そのエージェントは <code>http://&lt;このコンピュータ&gt;:3425/mcp/magpie/memory</code> を <code>Authorization: Bearer &lt;キー&gt;</code> 付きで使うか、MCP ルーターで <code>magpie-memory</code> を見つけます。保存した内容はここのすべてのエージェントの指示に入るため、ほかのキーには渡しません。共有キー、読み取り専用・発行された・短期のキー、キーの有無にかかわらず Web ページも使えません。</p>
<h2 id="api"><a class="anchor" href="#api">統計 API</a></h2>
<p>使用量ページの内容は JSON でも、このコンピューターに、また magpie を共有している間はゲートウェイキー付きのリクエストに提供されます。予算、モデル、アカウントで制限されたキーには、自分のリクエストと上限だけが返ります。持ち主がそのキーの<span class="ui">残量</span>をオンにすると(<code>magpie gateway-key quotas &lt;id&gt; on</code>)、使えるもののクォータも返ります。</p>
<ul>
+10
View File
@@ -261,6 +261,16 @@ curl -s -X POST http://127.0.0.1:3425/v1/magpie/admin/gateway-keys/add-key \
<p>It answers the same as the app’s own pages do, under <code>/v1/magpie/admin/</code>: <code>GET providers</code>, <code>POST provider/{save,delete,on,off,name,…}</code>, <code>POST keys/…</code> (a provider’s keys), <code>GET</code>/<code>POST gateway-keys[/{add-key,rename-key,limit-key,models-key,remove-key,…}]</code>, <code>GET</code>/<code>POST account-groups[/…]</code>, <code>GET routing-groups[/{id}]</code> and <code>POST routing-groups/{create,update,delete,switch,…}</code> (the Routing page’s groups and combos, checked as the app checks them; <code>update</code> changes only the fields you send), and <code>POST signin</code> with <code>{"agent":…}</code>, which answers the vendor’s page and the code to type there, never a password; open it on a computer with a browser. A saved key and a gateway key’s secret are never told again, and what changes this computer’s apps is not served. Sign-ins are not exported: that would hand out every account’s secrets.</p>
<p>A key that is read-only, the extension’s, issued or short-lived, or the sharing key, can’t have it. A web page can’t call it, with a key or without (any request with <code>Origin</code> or <code>Sec-Fetch-*</code> is refused), and nor can a request under another name for this computer. Shared over the network, only a key set to <code>any</code> gets in.</p>
<h2 id="memory"><a class="anchor" href="#memory">Memory from other computers</a></h2>
<p>Magpie Memory answers the agents on this computer. To let an agent on another computer read and save it too, give that agent a gateway key of its own and allow it, from the key’s menu in the app under Advanced › Magpie Memory, or from the command line:</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-memory">Copy</button>
<pre id="ex-memory">magpie gateway-key add remote-box
magpie gateway-key memory &lt;id&gt; on</pre>
</div>
<p>While magpie is shared, that agent uses <code>http://&lt;this computer&gt;:3425/mcp/magpie/memory</code> with <code>Authorization: Bearer &lt;key&gt;</code>, or finds <code>magpie-memory</code> in the MCP router. What it saves goes into every agent’s instructions here, so no other key gets it: not the sharing key, a read-only, issued or short-lived key, nor a web page, with the key or without.</p>
<h2 id="api"><a class="anchor" href="#api">Stats API</a></h2>
<p>What the Usage page shows is also served as JSON, to this computer and, while magpie is shared, to a request with a gateway key. A key held to a budget, models or accounts is told only its own calls and limit, and the quotas of what it may use once its owner turns on <span class="ui">Quotas</span> for it (<code>magpie gateway-key quotas &lt;id&gt; on</code>).</p>
<ul>
+10
View File
@@ -261,6 +261,16 @@ curl -s -X POST http://127.0.0.1:3425/v1/magpie/admin/gateway-keys/add-key \
<p>它和应用自己的页面答得一样,路径在 <code>/v1/magpie/admin/</code> 下:<code>GET providers</code>、<code>POST provider/{save,delete,on,off,name,…}</code>、<code>POST keys/…</code>(提供商的密钥)、<code>GET</code>/<code>POST gateway-keys[/{add-key,rename-key,limit-key,models-key,remove-key,…}]</code>、<code>GET</code>/<code>POST account-groups[/…]</code>、<code>GET routing-groups[/{id}]</code> 和 <code>POST routing-groups/{create,update,delete,switch,…}</code>(路由页的路由组和组合,校验和应用里一样;<code>update</code> 只改你发送的字段),以及 <code>POST signin</code>(<code>{"agent":…}</code>),它返回厂商的网页和要输入的代码,从不收密码;请在有浏览器的电脑上打开。已保存的密钥和网关密钥的明文不会再被告知,会改动这台电脑上其他应用的操作也不提供。登录不会被导出:那会交出每个账号的密钥。</p>
<p>只读密钥、浏览器扩展的密钥、签发的或短期的密钥以及共享密钥,都不能拥有它。网页不能调用它,带不带密钥都一样(带 <code>Origin</code> 或 <code>Sec-Fetch-*</code> 的请求一律拒绝),用别的名字指向本机的请求也不行。通过网络共享时,只有设为 <code>any</code> 的密钥能进来。</p>
<h2 id="memory"><a class="anchor" href="#memory">其他电脑使用记忆</a></h2>
<p>Magpie Memory 只回应这台电脑上的 Agent。要让另一台电脑上的 Agent 也能读写它,给那个 Agent 一个专用的网关密钥并允许它:在 App 里该密钥的菜单 › 高级 › Magpie Memory,或在命令行里:</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-memory">复制</button>
<pre id="ex-memory">magpie gateway-key add remote-box
magpie gateway-key memory &lt;id&gt; on</pre>
</div>
<p>共享 magpie 时,那个 Agent 用 <code>http://&lt;这台电脑&gt;:3425/mcp/magpie/memory</code> 加 <code>Authorization: Bearer &lt;密钥&gt;</code>,或在 MCP 路由器里找到 <code>magpie-memory</code>。它保存的内容会进入这里每个 Agent 的指令,所以别的密钥都用不了:共享密钥、只读密钥、签发的或短期的密钥都不行,网页带不带密钥也都不行。</p>
<h2 id="api"><a class="anchor" href="#api">统计 API</a></h2>
<p>用量页上的内容也以 JSON 提供给本机;共享 magpie 时,也提供给带网关密钥的请求。受预算、模型或账号限制的密钥只能看到自己的请求和限额;主人为它打开<span class="ui">额度</span>后(<code>magpie gateway-key quotas &lt;id&gt; on</code>),还能看到它可用部分的额度。</p>
<ul>
+11
View File
@@ -10718,6 +10718,17 @@ It answers the same as the app’s own pages do, under `/v1/magpie/admin/`: `GET
A key that is read-only, the extension’s, issued or short-lived, or the sharing key, can’t have it. A web page can’t call it, with a key or without (any request with `Origin` or `Sec-Fetch-*` is refused), and nor can a request under another name for this computer. Shared over the network, only a key set to `any` gets in.
## Memory from other computers
Magpie Memory answers the agents on this computer. To let an agent on another computer read and save it too, give that agent a gateway key of its own and allow it, from the key’s menu in the app under Advanced › Magpie Memory, or from the command line:
```
magpie gateway-key add remote-box
magpie gateway-key memory <id> on
```
While magpie is shared, that agent uses `http://<this computer>:3425/mcp/magpie/memory` with `Authorization: Bearer <key>`, or finds `magpie-memory` in the MCP router. What it saves goes into every agent’s instructions here, so no other key gets it: not the sharing key, a read-only, issued or short-lived key, nor a web page, with the key or without.
## Stats API
What the Usage page shows is also served as JSON, to this computer and, while magpie is shared, to a request with a gateway key. A key held to a budget, models or accounts is told only its own calls and limit, and the quotas of what it may use once its owner turns on Quotas for it (`magpie gateway-key quotas <id> on`).
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