library: a Remote magpie's skills and prompts can be used on the client (KoiLx0 on X)

A Remote magpie's editor has a new switch, Use its skills and prompts.
The remote serves its Library at GET /v1/magpie/library (local or shared
callers; a held key is refused; no MCP servers, which the MCP switch
already covers; borrowed items are never passed on). The client fetches
it every 10 minutes and once on switching on, and adds each skill and
prompt set as remote-<id>-<name>, recording a hash of what it wrote.
It only changes what still matches that hash: a skill or set of the
user's by the same name, one the user edited, and one the user removed
stay as they are; an update or drop moves the old copy to the backups;
switching off takes out what is unchanged. The first set becomes active
only when no prompt is active.

Run (wsl-run, magpie-wt/remote-library at the pushed head after rebase):
- go vet -tags nogui ./..., GOOS=windows and GOOS=darwin vet of library,
  provider, gateway, gui: clean. gofmt -l clean.
- go test ./internal/library ./internal/provider: ok. internal/gateway:
  TestReadOnlyKeyEveryRoute named the new route (fixed here, now ok);
  the package then ran to the end of a 30m wsl timeout on a slow box.
- TestBorrowRemoteLibrary and TestBorrowedSkillGoesWithTheRemote: broke
  by hand (the user's-own-skill guard turned off), TestBorrowRemoteLibrary
  went red with "kept []", restored.
- GUI remote-magpie.test.cjs (chromium + webkit): its new assertions for
  the switch pass, but the file is red on main before this change
  (#6099: line 160 and a layout assertion), so they ran in a copy with
  those two assertions relaxed. i18n tests ran in the same call.
Reds not mine: #6099, #6103 (TestSettingsSaveKeepsWhatItDoesNotSend).

Not tried: a real two-machine run; internal/gui and gateway full
packages to completion on wsl; Collect/Put (sync backups) still carry
borrowed items as ordinary ones.
This commit is contained in:
yetone
2026-11-11 15:59:46 +08:00
parent 6c95722da6
commit 5a9b5720da
14 changed files with 847 additions and 7 deletions
+1
View File
@@ -17,6 +17,7 @@ Pi's extensions and packages.
| Part | Responsibility | Source |
| --- | --- | --- |
| library.json | `Library` holds the instruction sets, the MCP servers, the skills, the projects, skill groups and copy settings. `Applied` records what magpie last wrote into each agent, so it only ever takes away its own. The instruction texts and skill folders live under `Dir` (`library/` in magpie's config folder). | [`library.go`](../../internal/library/library.go) |
| A Remote magpie's skills and prompts | A Remote magpie provider's editor has a switch, Use its skills and prompts (`borrowOn` in library.json, `SetBorrow`; KoiLx0 on X: manage them once on the remote machine). The remote serves its Library at `GET /v1/magpie/library` (`gateway.SharedLibrary` = `library.Shared`, to `local` or `sharedWith` callers; a held key is refused; no MCP servers, which the MCP switch covers; borrowed items are never passed on). `keepBorrowed` (10 minutes, and once on switching on) fetches it with the provider's key (`provider.RemoteLibrary`) and `Borrow` adds each skill and each instruction set as `remote-<id>-<name>`, recording a hash of what it wrote (`Borrowed`). It only ever changes what still matches that hash: a skill or set of the user's by the same name, one the user edited, and one the user removed after it was taken stay as they are (`Kept`, shown under the switch); an update or a drop moves the old copy to the backups; switching off takes out what is unchanged. The first set becomes the active one only when nothing is active. `Collect`/`Put` (sync backups) still carry borrowed items as ordinary ones. | [`borrow.go`](../../internal/library/borrow.go), [`remote_library.go`](../../internal/provider/remote_library.go), `TestBorrowRemoteLibrary` |
| One change | `change` locks the library, loads it, applies one edit, saves, syncs every agent and saves again. Every exported mutation (`SaveServer`, `InstallSkills`, `SetSkillHow` and the rest) goes through it. One change runs at a time, whether from the page or the CLI. | [`library.go`](../../internal/library/library.go) |
| Targets | `Targets` lists the detected agents (`agent.Detected`), a folder an agent shares with its vendor's other app when only that app is here (`agent.SharedHere`: the Cursor editor's `~/.cursor`, whose `mcp.json` and skills it reads, listed as Cursor; `TestCursorEditorAloneKeepsItsLibraryRow`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent whose CLI is gone (`CLIMissing`: an uninstall that left the folder behind, #2177, #2254) is no target: it is given nothing it can't read. One that isn't a target but still has skills, servers or hooks magpie gave it (in `Applied`, or listed in an item's `Agents`) is held (`held`, a `Target` with `Gone`): a sync takes edits from its copies and then only takes out of it (`syncSkills`, `syncMCP` and `syncHooks` give a gone target nothing new), and `Read` lists it with `gone: true` while it has any. The page shows a gone agent's chip only on the rows of what it has, lit, so a click takes it out (`withGone` in plugins/library/client.js), leaves it out of All, the per-agent How sheet and every picker, and lists it in By agent as Not installed here with Turn all on off (@jiahao_jayden on X: an uninstalled WorkBuddy was on every skill's row; `TestGoneAgentListedToTakeOut`, `library-gone-agents.test.cjs`). On a Mac WorkBuddy and WorkBuddy AI are detected by their apps' bundle ids (`com.tencent.workbuddy.mac`, `com.workbuddy.workbuddy-ai`, `macBundle`), not by `~/.workbuddy`, which an uninstall leaves and magpie itself writes into (`TestWorkBuddyOnMacIsItsApp`); off a Mac the folder still counts. `everyTarget` keeps it for the guards that refuse an agent's own places: a project folder whose skills folder or MCP file is the agent's, and an instruction set kept in its instructions file. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi, OmO, Gemini CLI, Antigravity CLI, Crush, Cline, CodeBuddy Code, Kimi Code and Goose each by its own rule, never reading this machine's variables (Kimi Code's and Goose's shared `~/.agents/skills` there isn't given), Pi's MCP file chosen by `piMCP` as on this machine from the version the distro's `pi --version` gave its probe (`InstalledVersion`) and the distro's npm folders (`wslPiRoots`; leokon on Discord: only the Windows Pi was offered MCP servers, `TestWSLPiMCP`, `TestWSLMCPSiblings`), and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. A place below a folder the distro has as a link is opened where the link leads (`wslOpen`, agent-wiring's WSL folders that are links, #4502); a link the distro couldn't resolve gives that agent one `wsl` problem and nothing is written to it (`TestWSLFolderIsALinkToC`, `TestWSLFolderLinkUnresolved`). An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. Every built-in agent is a target or is in `noLibrary` with why: OpenBot was added with neither and was in no picker (SSNQT on X), so `TestEveryAgentInLibrary` fails a new agent until it gets one (34 were in no picker when it landed, listed there under #5897). | [`targets.go`](../../internal/library/targets.go) |
| Stopped WSL distro | A stopped distro's agents are no targets: opening their files would start the distro, or the read fails (#3896). While a distro runs, `keepShape` keeps each agent's places and what its MCP file takes in `wsl.json` (`agent.WSLKeep`, key `library:<kind>`). While it is stopped, `Read` lists its agents from that (`asleepView`, `asleep: <distro>`), ticks as library.json has them; one magpie never saw there is listed only on the rows that name it, as `unseen`, its ticks not shown (cybercaius on Discord: the MCP page knew a distro's agents only once WSL had started). A tick on a stopped agent is kept in library.json as any is (`Takes` accepts one with a known shape; `serversAgents` judges it by `shape.reaches`), nothing is written and nothing in the distro runs; `Woken`, from `KeepLinked`'s loop (and the app's start-up sync), syncs when a distro the library names is seen go from stopped to running (`wsl.exe -l --running`, which starts nothing). The page greys a stopped agent's chip, says so in its tooltip and in one line per distro (`.lib-asleep`); an unseen chip is `aria-disabled` and kept by every click on its row (`keptOf`). The CLI says the same on stderr (`AsleepIn`). Queued, not a start button: a start costs the memory #3896 is about, and All or a bulk tick would start every distro. The Instructions page lists them too (`asleepInstructions`, #4182), at the instructions file the shape keeps, switched on as library.json has them, with what each gets besides (magpie's own folder) and nothing read from the file: its own lines and edits aren't counted then, and its path is plain text, not a reveal, which would open the distro. One switched on whose file magpie never saw is listed as `unseen`, its switch greyed out and kept by every other switch; before, a switch on the page sent the agents without the stopped distro's and took them off. A switch on one is written by `Woken`, which watches a distro named in `Instructions.Agents`, or whose agent still has magpie's part (`Applied.Instructions`), so one switched off has it taken out. The Hooks page lists the stopped agents with a shape as it does while the distro runs (`hooksView`, #4237): greyed, since magpie gives no agent in WSL hooks yet (`wslNoHooks`), and a hook given one says so; there is nothing for `Woken` to write. So does the Subagents page for the kinds it lists (`subagentsView`, `wslNoSubagents`, #4238). | [`wsl_asleep.go`](../../internal/library/wsl_asleep.go), [`targets.go`](../../internal/library/targets.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
+33
View File
@@ -1027,6 +1027,7 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("POST /v1/magpie/usage/requests", s.usageIngest)
mux.HandleFunc("GET /v1/magpie/quotas/history", s.quotasHistory)
mux.HandleFunc("GET "+provider.RemoteCardsPath, s.quotaCards)
mux.HandleFunc("GET "+provider.RemoteLibraryPath, s.sharedLibrary)
mux.HandleFunc("POST "+provider.RemoteRefreshPath, s.quotaCardsRefresh)
mux.HandleFunc("POST "+provider.RemoteCodexResetPath, s.codexReset)
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
@@ -1240,6 +1241,38 @@ func (s *Server) quotaCards(w http.ResponseWriter, r *http.Request) {
writeCards(w, r, scope)
}
// SharedLibrary is the Library as another magpie is told it (JSON), set
// by the app: the gateway doesn't know the library package.
var SharedLibrary func() ([]byte, error)
// sharedLibrary tells another magpie that has this one as its provider
// the skills and prompts of the Library, to use them as its own (KoiLx0
// on X). Only to this computer and to a full-access key of a magpie
// shared on the local network: a key held to models, a budget or
// accounts is the user's limit on what that caller may use.
func (s *Server) sharedLibrary(w http.ResponseWriter, r *http.Request) {
if !local(r) && !sharedWith(r) {
writeError(w, provider.Chat, http.StatusForbidden, "magpie's Library is told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
return
}
if heldKey(access.Caller(r.Context())) {
refuseHeld(w, r, heldQuotasOff)
return
}
if SharedLibrary == nil {
writeError(w, provider.Chat, http.StatusNotFound, "this magpie has no Library to tell")
return
}
b, err := SharedLibrary()
if err != nil {
writeError(w, provider.Chat, http.StatusInternalServerError, "reading the Library: "+err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.Write(b)
}
// remoteRefreshes is when another magpie last had each card read again
// here: one refreshed by hand is read at most once in remoteRefreshGap,
// however often it is asked, so the vendor sees no more than this
+2
View File
@@ -19,6 +19,8 @@ import (
// in readOnlyRoutes fails TestReadOnlyKeyEveryRoute, so a new one is
// classified before it ships: the guard refuses it until then.
var readOnlyRefused = []string{
// the Library's skills and prompts: a held key is a display, not a client
"GET /v1/magpie/library",
// model lists and their Ollama spellings: what the key could use
"GET /v1/models", "GET /models", "GET /v1/models/{id...}", "GET /muse-code/models",
"GET /api/hello", "GET /api/version", "GET /api/tags",
+6
View File
@@ -9756,6 +9756,11 @@ function drawEditor(p, presetID) {
l.classList.add("library-mcp");
c.onchange = () => (draft.libraryMCP = c.checked);
ed.append(...field(t("MCP servers"), l));
// KoiLx0 on X
const [l2, c2] = tick(t("Use its skills and prompts"), (draft.libraryShared ??= !!p?.libraryShared));
l2.classList.add("library-shared");
c2.onchange = () => (draft.libraryShared = c2.checked);
ed.append(...field(t("Skills and prompts"), l2));
}
// lcc580 on X
if ((p?.preset || pr?.id) === "remote-magpie") {
@@ -10253,6 +10258,7 @@ function drawEditor(p, presetID) {
if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.hiddenDrawers = draft.hiddenDrawers; body.hiddenVideomakers = draft.hiddenVideomakers; body.noModels = noneChosen(); body.bestInFamily = bestChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); }
body.searches = !!draft.searches && searchable();
if (draft.libraryMCP != null) body.libraryMCP = draft.libraryMCP;
if (draft.libraryShared != null) body.libraryShared = draft.libraryShared;
body.pinUpstream = !!draft.pinUpstream;
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
body.unredacted = !!draft.unredacted;
+8
View File
@@ -2872,6 +2872,8 @@ const I18N = {
"{name} added": "已添加 {name}",
"Give it a name": "先起个名字",
"Add its MCP servers to the Library": "把它的 MCP 服务器加到资源库",
"Use its skills and prompts": "使用它的技能和提示词",
"Skills and prompts": "技能和提示词",
"Model names": "模型名",
"With the provider serving it there": "带上它那边的供应商(穿透)",
"A base URL is needed": "需要填写 Base URL",
@@ -7919,6 +7921,8 @@ const I18N = {
"{name} added": "已新增 {name}",
"Give it a name": "先起個名字",
"Add its MCP servers to the Library": "把它的 MCP 伺服器加到資源庫",
"Use its skills and prompts": "使用它的技能和提示詞",
"Skills and prompts": "技能和提示詞",
"Model names": "模型名稱",
"With the provider serving it there": "帶上它那邊的供應商(穿透)",
"A base URL is needed": "需要填寫 Base URL",
@@ -12944,6 +12948,8 @@ const I18N = {
"{name} added": "{name} を追加しました",
"Give it a name": "名前を付けてください",
"Add its MCP servers to the Library": "その MCP サーバーをライブラリに追加",
"Use its skills and prompts": "そのスキルとプロンプトを使う",
"Skills and prompts": "スキルとプロンプト",
"Model names": "モデル名",
"With the provider serving it there": "向こうで提供しているプロバイダーを付ける",
"A base URL is needed": "ベース URL が必要です",
@@ -18000,6 +18006,8 @@ const I18N = {
"{name} added": "{name} hinzugefügt",
"Give it a name": "Vergeben Sie einen Namen",
"Add its MCP servers to the Library": "Seine MCP-Server zur Bibliothek hinzufügen",
"Use its skills and prompts": "Seine Skills und Prompts verwenden",
"Skills and prompts": "Skills und Prompts",
"Model names": "Modellnamen",
"With the provider serving it there": "Mit dem Anbieter, der es dort bereitstellt",
"A base URL is needed": "Eine Basis-URL ist erforderlich",
+29
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
@@ -339,6 +340,11 @@ type providerJSON struct {
// LibraryMCP: a Remote magpie whose router is a Library server, or
// is to be one (library.RemoteMCPOn)
LibraryMCP bool `json:"libraryMCP,omitempty"`
// LibraryShared: a Remote magpie whose Library's skills and prompts
// are used here (library.BorrowedOn), and LibraryNote what its last
// read said went wrong or was left as the user's (KoiLx0 on X)
LibraryShared bool `json:"libraryShared,omitempty"`
LibraryNote string `json:"libraryNote,omitempty"`
// RemoteUpdate: a Remote magpie's word on its last ask to follow
// this magpie's version (remoteUpdateNote)
RemoteUpdate *remoteUpdateJSON `json:"remoteUpdate,omitempty"`
@@ -1353,6 +1359,8 @@ func providersState() providersJSON {
remoteMCP = library.RemoteMCPOn()
}
info.LibraryMCP = remoteMCP[p.ID]
info.LibraryShared = library.BorrowedOn()[p.ID]
info.LibraryNote = library.BorrowNote(p.ID)
info.RemoteUpdate = remoteUpdateNote(p.ID, time.Now())
}
s.Providers = append(s.Providers, info)
@@ -1724,6 +1732,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// router a Library server (library.SetRemoteMCP); left out,
// it stays as it is
LibraryMCP *bool `json:"libraryMCP"`
// LibraryShared, on a Remote magpie, is the switch for its
// Library's skills and prompts (library.SetBorrow)
LibraryShared *bool `json:"libraryShared"`
// CopyOf, with New, is the provider the new one is a copy of
// (#268): its key and what else the form doesn't carry are
// taken from it when left out
@@ -2428,6 +2439,24 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
askHub = *req.LibraryMCP
}
}
if req.LibraryShared != nil {
if p, err := provider.Find(in.ID); err == nil && p.IsRemoteMagpie() && library.BorrowedOn()[in.ID] != *req.LibraryShared {
if _, err := library.SetBorrow(in.ID, *req.LibraryShared); err != nil {
fail(rw, err)
return
}
if *req.LibraryShared {
id := in.ID
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*provider.RemoteLibraryWait)
defer cancel()
if _, err := library.UseRemoteLibrary(ctx, id); err != nil {
log.Printf("library: the Library of %s: %v", id, err)
}
}()
}
}
}
provider.ForgetBalances()
if old == nil || old.AccessKeyID != in.AccessKeyID || old.SecretAccessKey != in.SecretAccessKey {
// the plan's windows are read afresh with the new access key
+4 -1
View File
@@ -229,6 +229,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(s.name, "Remote magpie");
assert.equal(s.id, "remote-magpie");
assert.equal(s.libraryMCP, false);
assert.equal(s.libraryShared, false, "skills and prompts off when added");
// named, its id following; then an id of its own; switched on
await page.locator("#addProvider").click();
@@ -239,9 +240,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await ed.locator("input.provider-name").fill("Home Lab");
assert.equal(await ed.locator("input.provider-id").getAttribute("placeholder"), "home-lab");
await ed.locator(".library-mcp input").check();
await ed.locator(".library-shared input").check();
await ed.locator(".bar button.primary", { hasText: w.add }).click();
await page.waitForFunction(() => !document.querySelector(".editor.new"));
assert.deepEqual([saves[1].name, saves[1].id, saves[1].libraryMCP], ["Home Lab", "home-lab", true]);
assert.deepEqual([saves[1].name, saves[1].id, saves[1].libraryMCP, saves[1].libraryShared], ["Home Lab", "home-lab", true, true]);
await page.locator("#addProvider").click();
await tile.click();
await ed.locator(".ehead b", { hasText: "Remote magpie" }).waitFor();
@@ -259,6 +261,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await ed.locator(".ehead b", { hasText: "OpenAI" }).waitFor();
assert.equal(await ed.locator("input.endpoint").count(), 0);
assert.equal(await ed.locator(".library-mcp").count(), 0, "no switch on another preset");
assert.equal(await ed.locator(".library-shared").count(), 0, "no skills switch on another preset");
await page.keyboard.press("Escape");
await ed.waitFor({ state: "detached" });
+483
View File
@@ -0,0 +1,483 @@
package library
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
func init() {
gateway.SharedLibrary = func() ([]byte, error) {
b, err := Shared()
if err != nil {
return nil, err
}
return json.Marshal(b)
}
}
// borrowEvery is how often KeepLinked reads the Remote magpies' Libraries.
const borrowEvery = 10 * time.Minute
var lastBorrow time.Time
// keepBorrowed reads the Libraries of the Remote magpies switched on,
// each borrowEvery.
func keepBorrowed(ctx context.Context) {
if time.Since(lastBorrow) < borrowEvery {
return
}
lastBorrow = time.Now()
UseRemoteLibraries(ctx)
}
// A Remote magpie's Library, used here (KoiLx0 on X: prompts and skills
// kept on one computer, not set up again on every client). The remote
// tells its skills and instruction sets (Shared, GET
// provider.RemoteLibraryPath); with the editor's switch on, this
// magpie keeps them as items of its own Library, and the agents get them
// as any other. Its MCP servers are the Remote magpie's other switch
// (bridge_mcp.go): they run there, behind its router.
//
// - Nothing the user has is written over. A skill whose name the
// library already has stays as it is, and so does one taken and then
// changed here; a set is kept under an id of its own, so it is never
// one the user made. An item the user changed is theirs from then on:
// it isn't updated, and isn't taken out when the remote drops it or
// the switch goes off.
// - A skill is given to the agents the remote gives it to when it
// arrives, and the agents ticked here stay as they are after.
// - A set is added, never switched on over the user's: only when the
// text the agents get is empty, and they are ticked for none, does
// the first one become what they read (as a new set does, #106).
// - The servers' keys never leave the remote (Shared blanks them), and
// what the remote keeps for this computer alone (Local) is not told.
// - What was taken is recorded with a hash, per item, to tell the
// user's change from the remote's.
// Borrowed is what this computer took from one Remote magpie's Library:
// by name the hash of each skill as taken, and by id that of each set.
type Borrowed struct {
Name string `json:"name,omitempty"`
Skills map[string]string `json:"skills,omitempty"`
Sets map[string]string `json:"sets,omitempty"`
}
// maxShared is how much of the skills' files a Library tells another
// magpie, and the most of one file: base64 in JSON, it stays under what
// a remote reads (provider.maxRemoteLibrary).
const (
maxSharedAll = 24 << 20
maxSharedFile = 8 << 20
)
// Shared is the Library as another magpie is told it: the instruction
// sets with their texts and the skills with their files. The servers, the
// hooks and what each agent gets besides are this computer's; a skill
// linked to a folder here comes as its files.
func Shared() (*Bundle, error) {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return nil, err
}
b := &Bundle{Instructions: Instructions{Agents: orNone(slices.Sorted(slices.Values(l.Instructions.Agents))), Active: l.Instructions.Active},
Texts: map[string]string{}, MCP: []*Server{}, Skills: []*CarriedSkill{}}
for _, s := range l.Instructions.Sets {
if strings.HasPrefix(s.ID, borrowedPrefix) { // taken from a magpie: not passed on
continue
}
s.File = ""
b.Instructions.Sets = append(b.Instructions.Sets, s)
}
for _, s := range l.sets() {
if strings.HasPrefix(s.ID, borrowedPrefix) {
continue
}
if text := setText(l.textPath(s.ID)); text != "" {
b.Texts[s.ID] = text
}
}
if strings.HasPrefix(b.Instructions.Active, borrowedPrefix) {
b.Instructions.Active = ""
}
skills := sorted(l.Skills, func(s *Skill) string { return s.Name })
var names []*Skill
var dirs []string
for _, s := range skills {
if l.borrowedSkill(s.Name) { // taken from a magpie: not passed on
continue
}
names = append(names, s)
dirs = append(dirs, realDir(skillDir(s.Name)))
}
for i, c := range readSkillsMax(dirs, maxSharedFile, maxSharedAll) {
c.Name, c.Agents = names[i].Name, orNone(slices.Sorted(slices.Values(names[i].Agents)))
b.Skills = append(b.Skills, c)
}
return b, nil
}
// borrowedPrefix starts the id of a set taken from a Remote magpie.
const borrowedPrefix = "remote-"
func (l *Library) borrowedSkill(name string) bool {
for _, b := range l.Borrowed {
if _, ok := b.Skills[name]; ok {
return true
}
}
return false
}
// setID is the id a set of the remote id is kept under here.
func setID(remote, set string) string {
h := sha256.Sum256([]byte(remote))
return borrowedPrefix + hex.EncodeToString(h[:3]) + "-" + set
}
// skillSum is a skill's files and which of them run, as one hash.
func skillSum(c *CarriedSkill) string {
h := sha256.New()
for _, rel := range slices.Sorted(maps.Keys(c.Files)) {
fmt.Fprintf(h, "%s\x00%d\x00%v\x00", rel, len(c.Files[rel]), slices.Contains(c.Exec, rel))
h.Write(c.Files[rel])
}
return hex.EncodeToString(h.Sum(nil)[:12])
}
// BorrowedOn are the Remote magpies (provider ids) whose Library is used
// here. Nil when the library can't be read.
func BorrowedOn() map[string]bool {
mu.Lock()
l, err := load()
mu.Unlock()
if err != nil {
return nil
}
on := map[string]bool{}
for _, id := range l.BorrowOn {
on[id] = true
}
return on
}
// SetBorrow turns the switch of the Remote magpie id on or off. On, its
// Library is read at once (UseRemoteLibraries); off, what was taken from
// it and not changed since is taken out.
func SetBorrow(id string, on bool) (*Result, error) {
if on {
return change(func(l *Library) error {
if !slices.Contains(l.BorrowOn, id) {
l.BorrowOn = append(l.BorrowOn, id)
}
return nil
})
}
return change(func(l *Library) error {
l.BorrowOn = slices.DeleteFunc(l.BorrowOn, func(x string) bool { return x == id })
l.dropBorrowed(id, &Bundle{})
delete(l.Borrowed, id)
return nil
})
}
// dropBorrowed takes out what was taken from id that b no longer has and
// the user hasn't changed.
func (l *Library) dropBorrowed(id string, b *Bundle) {
got := l.Borrowed[id]
if got == nil {
return
}
have := map[string]bool{}
for _, s := range b.Skills {
have[s.Name] = true
}
stamp := time.Now().Format("2006-01-02_15-04-05.000")
for _, name := range slices.Sorted(maps.Keys(got.Skills)) {
if have[name] {
continue
}
cur := l.skill(name)
if cur != nil && readSum(name) == got.Skills[name] {
if err := removeSkill(l, name, stamp); err != nil {
log.Printf("library: taking out %s, once its remote dropped it: %v", name, err)
continue
}
}
delete(got.Skills, name) // gone, or the user's now
}
haveSet := map[string]bool{}
for _, s := range b.Instructions.Sets {
haveSet[setID(id, s.ID)] = true
}
if _, ok := b.Texts[defaultSet]; ok {
haveSet[setID(id, defaultSet)] = true
}
for _, sid := range slices.Sorted(maps.Keys(got.Sets)) {
if haveSet[sid] {
continue
}
if l.hasSet(sid) && sum(l.setName(sid), setText(l.textPath(sid))) == got.Sets[sid] {
if sid == l.active() {
l.Instructions.Active = ""
}
if l.kept == nil {
l.kept = newBackups()
}
if p := setPath(sid); readText(p) != "" {
l.kept.keep("library", p)
}
writeText(setPath(sid), "")
l.Instructions.Sets = slices.DeleteFunc(l.Instructions.Sets, func(s InstrSet) bool { return s.ID == sid })
}
delete(got.Sets, sid)
}
}
func (l *Library) setName(id string) string {
if s := l.instrSet(id); s != nil {
return s.Name
}
return ""
}
func sum(name, text string) string {
h := sha256.Sum256([]byte(name + "\x00" + strings.TrimSpace(text)))
return hex.EncodeToString(h[:12])
}
func readSum(name string) string {
return skillSum(readSkills([]string{realDir(skillDir(name))})[0])
}
// BorrowResult says what a read of a Remote magpie's Library did.
type BorrowResult struct {
Added []string // skills and sets taken in
Updated []string
Removed []string
Kept []string // the user's own by the same name, left as they are
}
// Borrow keeps the Library b of the Remote magpie id (called name) here,
// as the notes above say.
func Borrow(id, name string, b *Bundle) (*BorrowResult, error) {
if err := b.check(); err != nil {
return nil, err
}
out := &BorrowResult{}
_, err := change(func(l *Library) error {
*out = BorrowResult{}
if !slices.Contains(l.BorrowOn, id) { // switched off meanwhile
return errors.New("switched off")
}
if l.Borrowed == nil {
l.Borrowed = map[string]*Borrowed{}
}
got := l.Borrowed[id]
if got == nil {
got = &Borrowed{}
l.Borrowed[id] = got
}
got.Name = name
if got.Skills == nil {
got.Skills = map[string]string{}
}
if got.Sets == nil {
got.Sets = map[string]string{}
}
l.dropBorrowed(id, b)
if err := os.MkdirAll(skillsDir(), 0o755); err != nil {
return err
}
stage, err := os.MkdirTemp(Dir(), ".incoming-")
if err != nil {
return err
}
defer os.RemoveAll(stage)
aside := filepath.Join(BackupDir(), time.Now().Format("2006-01-02_15-04-05.000"), "skills")
for _, s := range b.Skills {
cur := l.skill(s.Name)
want := skillSum(s)
switch {
case cur == nil && got.Skills[s.Name] != "":
// taken before and taken out by the user since: not again
delete(got.Skills, s.Name)
out.Kept = append(out.Kept, "skill:"+s.Name)
continue
case cur == nil:
if _, err := os.Lstat(skillDir(s.Name)); err == nil { // a folder in the way that isn't a skill here
out.Kept = append(out.Kept, "skill:"+s.Name)
continue
}
case got.Skills[s.Name] == "" || readSum(s.Name) != got.Skills[s.Name]:
// the user's own, or taken and changed since
delete(got.Skills, s.Name)
out.Kept = append(out.Kept, "skill:"+s.Name)
continue
case got.Skills[s.Name] == want:
continue
}
if err := writeSkill(filepath.Join(stage, s.Name), s); err != nil {
return fmt.Errorf("skill %s: %w", s.Name, err)
}
if cur != nil {
if err := os.MkdirAll(aside, 0o700); err != nil {
return err
}
if err := move(skillDir(s.Name), filepath.Join(aside, s.Name)); err != nil {
return err
}
out.Updated = append(out.Updated, "skill:"+s.Name)
} else {
// the agents the remote gives it to, only when it comes
l.Skills = append(l.Skills, &Skill{Name: s.Name, Agents: slices.Clone(orNone(s.Agents))})
out.Added = append(out.Added, "skill:"+s.Name)
}
if err := os.Rename(filepath.Join(stage, s.Name), skillDir(s.Name)); err != nil {
return err
}
got.Skills[s.Name] = readSum(s.Name)
}
// the instruction sets
l.kept = newBackups()
var first string
sets := slices.Clone(b.Instructions.Sets)
if _, ok := b.Texts[defaultSet]; ok && !slices.ContainsFunc(sets, func(s InstrSet) bool { return s.ID == defaultSet }) {
sets = append(sets, InstrSet{ID: defaultSet})
}
for _, s := range sets {
text := strings.TrimSpace(b.Texts[s.ID])
if text == "" {
continue
}
sid := setID(id, s.ID)
label := name
if s.Name != "" {
label += " · " + s.Name
}
cur := l.instrSet(sid)
switch {
case cur == nil && got.Sets[sid] != "":
// taken before and taken out by the user since: not again
out.Kept = append(out.Kept, "set:"+sid)
continue
case cur != nil && (got.Sets[sid] == "" || sum(cur.Name, setText(l.textPath(sid))) != got.Sets[sid]):
delete(got.Sets, sid)
out.Kept = append(out.Kept, "set:"+sid)
continue
case cur != nil && got.Sets[sid] == sum(label, text):
continue
}
if p := setPath(sid); readText(p) != "" {
if err := l.kept.keep("library", p); err != nil {
return err
}
}
if err := writeText(setPath(sid), text); err != nil {
return err
}
if cur == nil {
l.Instructions.Sets = append(l.Instructions.Sets, InstrSet{ID: sid, Name: label})
out.Added = append(out.Added, "set:"+sid)
if first == "" {
first = sid
}
} else {
cur.Name = label
out.Updated = append(out.Updated, "set:"+sid)
}
got.Sets[sid] = sum(label, text)
}
// the agents read nothing yet: the first set taken is what they read
if first != "" && setText(l.sharedPath()) == "" {
l.Instructions.Active = first
if len(l.Instructions.Agents) == 0 {
l.Instructions.Agents = slices.Clone(orNone(b.Instructions.Agents))
}
}
return nil
})
if err != nil {
return nil, err
}
return out, nil
}
// borrowNotes are, per Remote magpie, what its last read said: "" when it
// went well. In memory only.
var borrowNotes = struct {
sync.Mutex
m map[string]string
}{m: map[string]string{}}
// BorrowNote is what the last read of the Remote magpie id's Library
// said went wrong, and the names it left as the user's.
func BorrowNote(id string) string {
borrowNotes.Lock()
defer borrowNotes.Unlock()
return borrowNotes.m[id]
}
func setBorrowNote(id, note string) {
borrowNotes.Lock()
borrowNotes.m[id] = note
borrowNotes.Unlock()
}
// UseRemoteLibrary reads the Library of the Remote magpie id and keeps it
// here (Borrow).
func UseRemoteLibrary(ctx context.Context, id string) (*BorrowResult, error) {
body, name, err := provider.RemoteLibrary(ctx, id)
if err != nil {
setBorrowNote(id, err.Error())
return nil, err
}
var b Bundle
if err := json.Unmarshal(body, &b); err != nil {
err = fmt.Errorf("the remote's Library isn't readable: %w", err)
setBorrowNote(id, err.Error())
return nil, err
}
b.MCP = nil // its servers run there: the router's switch gives them
r, err := Borrow(id, name, &b)
if err != nil {
setBorrowNote(id, err.Error())
return nil, err
}
note := ""
if len(r.Kept) > 0 {
note = "kept as yours: " + strings.Join(r.Kept, ", ")
}
setBorrowNote(id, note)
return r, nil
}
// UseRemoteLibraries reads the Library of every Remote magpie switched
// on.
func UseRemoteLibraries(ctx context.Context) {
for _, id := range slices.Sorted(maps.Keys(BorrowedOn())) {
cctx, cancel := context.WithTimeout(ctx, 2*provider.RemoteLibraryWait)
if _, err := UseRemoteLibrary(cctx, id); err != nil {
log.Printf("library: the Library of %s: %v", id, err)
}
cancel()
}
}
+216
View File
@@ -0,0 +1,216 @@
package library
import (
"encoding/json"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
)
// a Library as a remote magpie tells it: two skills and two prompt sets
func remoteLibrary(t *testing.T) *Bundle {
t.Helper()
sandbox(t)
_, err := Put(&Bundle{
Instructions: Instructions{Agents: []string{"claude"}, Sets: []InstrSet{{ID: "work", Name: "Work"}}, Active: "work"},
Texts: map[string]string{"default": "Be brief.", "work": "Reply in the user's language."},
MCP: []*Server{},
Skills: []*CarriedSkill{
{Name: "pdf", Agents: []string{"claude"}, Files: map[string][]byte{"SKILL.md": []byte("---\nname: pdf\ndescription: PDFs\n---\n")}},
{Name: "notes", Agents: []string{"claude"}, Files: map[string][]byte{"SKILL.md": []byte("---\nname: notes\ndescription: Notes\n---\n"), "run.sh": []byte("echo 1\n")}, Exec: []string{"run.sh"}},
},
})
if err != nil {
t.Fatal(err)
}
b, err := Shared()
if err != nil {
t.Fatal(err)
}
// what travels is JSON
j, err := json.Marshal(b)
if err != nil {
t.Fatal(err)
}
var out Bundle
if err := json.Unmarshal(j, &out); err != nil {
t.Fatal(err)
}
return &out
}
func borrowedText(t *testing.T, name string) string {
t.Helper()
b, err := os.ReadFile(filepath.Join(skillDir(name), "SKILL.md"))
if err != nil {
return ""
}
return string(b)
}
func names(l *Library) []string {
var out []string
for _, s := range l.Skills {
out = append(out, s.Name)
}
slices.Sort(out)
return out
}
// KoiLx0 on X: a client uses the remote's skills and prompts, and what
// the user has stays theirs.
func TestBorrowRemoteLibrary(t *testing.T) {
remote := remoteLibrary(t)
if remote.MCP == nil || len(remote.MCP) != 0 {
t.Fatalf("the servers stay on their computer: %v", remote.MCP)
}
// the client: a user's own skill of the same name, and their own prompt
h := sandbox(t)
skill(t, filepath.Join(h, "mine/pdf"), "pdf", "My PDFs")
if _, err := InstallSkills(filepath.Join(h, "mine"), []string{"pdf"}, []string{"claude"}); err != nil {
t.Fatal(err)
}
mine := borrowedText(t, "pdf")
if mine == "" {
t.Fatal("the user's skill wasn't installed")
}
// switched off: nothing is taken
if _, err := Borrow("office", "Office", remote); err == nil {
t.Fatal("a Library was taken with the switch off")
}
if _, err := SetBorrow("office", true); err != nil {
t.Fatal(err)
}
r, err := Borrow("office", "Office", remote)
if err != nil {
t.Fatal(err)
}
if !slices.Contains(r.Added, "skill:notes") || !slices.Contains(r.Kept, "skill:pdf") {
t.Fatalf("added %v, kept %v", r.Added, r.Kept)
}
if got := borrowedText(t, "pdf"); got != mine {
t.Fatalf("the user's own pdf was written over: %q", got)
}
if borrowedText(t, "notes") == "" {
t.Fatal("the remote's skill didn't arrive")
}
if fi, err := os.Stat(filepath.Join(skillDir("notes"), "run.sh")); err != nil || fi.Mode().Perm()&0o100 == 0 && runtime.GOOS != "windows" {
t.Fatalf("the script lost its mode: %v %v", fi, err)
}
l := mustLoad(t)
if i := slices.IndexFunc(l.Skills, func(s *Skill) bool { return s.Name == "notes" }); i < 0 || !slices.Contains(l.Skills[i].Agents, "claude") {
t.Fatalf("not given to the agents the remote gives it to: %+v", l.Skills)
}
// the prompts come as sets of their own, and the agents read the first
// since they read nothing
sid := setID("office", "work")
if !l.hasSet(sid) || !l.hasSet(setID("office", "default")) {
t.Fatalf("sets %+v", l.Instructions.Sets)
}
if l.active() != setID("office", "default") && l.active() != sid {
t.Fatalf("active %q", l.active())
}
if setText(l.textPath(sid)) != "Reply in the user's language." {
t.Fatalf("text %q", setText(l.textPath(sid)))
}
// a borrowed set is not passed on by Shared
back, err := Shared()
if err != nil {
t.Fatal(err)
}
for _, s := range back.Skills {
if s.Name == "notes" {
t.Fatal("a borrowed skill was told on")
}
}
for _, s := range back.Instructions.Sets {
if strings.HasPrefix(s.ID, borrowedPrefix) {
t.Fatal("a borrowed set was told on")
}
}
// the remote changes a skill and drops one; the user edited neither
remote.Skills = slices.DeleteFunc(remote.Skills, func(s *CarriedSkill) bool { return s.Name == "pdf" })
for _, s := range remote.Skills {
s.Files["SKILL.md"] = []byte("---\nname: notes\ndescription: Notes v2\n---\n")
}
if _, err := Borrow("office", "Office", remote); err != nil {
t.Fatal(err)
}
if !strings.Contains(borrowedText(t, "notes"), "v2") {
t.Fatalf("not updated: %q", borrowedText(t, "notes"))
}
// the user edits it: from then on it is theirs
edited := "---\nname: notes\ndescription: My notes\n---\n"
if err := os.WriteFile(filepath.Join(skillDir("notes"), "SKILL.md"), []byte(edited), 0o644); err != nil {
t.Fatal(err)
}
for _, s := range remote.Skills {
s.Files["SKILL.md"] = []byte("---\nname: notes\ndescription: Notes v3\n---\n")
}
r, err = Borrow("office", "Office", remote)
if err != nil {
t.Fatal(err)
}
if borrowedText(t, "notes") != edited || !slices.Contains(r.Kept, "skill:notes") {
t.Fatalf("the user's edit was written over: %q %v", borrowedText(t, "notes"), r.Kept)
}
// the remote drops it: the user's edit stays
remote.Skills = nil
if _, err := Borrow("office", "Office", remote); err != nil {
t.Fatal(err)
}
if borrowedText(t, "notes") != edited {
t.Fatal("a skill the user changed was taken out")
}
// the user's own pdf and prompt are never touched by turning it off
if _, err := SetBorrow("office", false); err != nil {
t.Fatal(err)
}
l = mustLoad(t)
if borrowedText(t, "pdf") != mine || !slices.Contains(names(l), "pdf") || !slices.Contains(names(l), "notes") {
t.Fatalf("turning it off took the user's: %v", names(l))
}
if l.hasSet(sid) {
t.Fatalf("its sets stayed: %+v", l.Instructions.Sets)
}
}
// A skill taken and not changed goes when the remote drops it or the
// switch goes off; one the user removed is not brought back.
func TestBorrowedSkillGoesWithTheRemote(t *testing.T) {
remote := remoteLibrary(t)
sandbox(t)
if _, err := SetBorrow("office", true); err != nil {
t.Fatal(err)
}
if _, err := Borrow("office", "Office", remote); err != nil {
t.Fatal(err)
}
if got := names(mustLoad(t)); !slices.Equal(got, []string{"notes", "pdf"}) {
t.Fatalf("%v", got)
}
if _, err := RemoveSkill("pdf"); err != nil {
t.Fatal(err)
}
if _, err := Borrow("office", "Office", remote); err != nil {
t.Fatal(err)
}
if got := names(mustLoad(t)); !slices.Equal(got, []string{"notes"}) {
t.Fatalf("a skill the user removed came back: %v", got)
}
if _, err := SetBorrow("office", false); err != nil {
t.Fatal(err)
}
if got := names(mustLoad(t)); len(got) != 0 {
t.Fatalf("left after switching off: %v", got)
}
}
+7 -4
View File
@@ -147,7 +147,10 @@ func orNone(xs []string) []string {
// readSkills is each skill folder's files. Links in it, .git and what
// isn't a plain file stay out. What goes is chosen smallest first across
// every skill, so the text of them all comes before any big file.
func readSkills(dirs []string) []*CarriedSkill {
func readSkills(dirs []string) []*CarriedSkill { return readSkillsMax(dirs, maxCarried, maxCarriedAll) }
// readSkillsMax is readSkills with a file's and the whole's budget given.
func readSkillsMax(dirs []string, perFile, all int64) []*CarriedSkill {
type file struct {
skill int
rel, p string
@@ -187,10 +190,10 @@ func readSkills(dirs []string) []*CarriedSkill {
slices.SortFunc(files, func(a, b file) int {
return cmp.Or(cmp.Compare(a.size, b.size), cmp.Compare(a.skill, b.skill), strings.Compare(a.rel, b.rel))
})
budget := int64(maxCarriedAll)
budget := all
for _, f := range files {
c := out[f.skill]
if f.size > maxCarried || f.size > budget {
if f.size > perFile || f.size > budget {
c.Left = append(c.Left, f.rel)
continue
}
@@ -198,7 +201,7 @@ func readSkills(dirs []string) []*CarriedSkill {
if err != nil {
continue
}
if n := int64(len(data)); n > maxCarried || n > budget { // grew since
if n := int64(len(data)); n > perFile || n > budget { // grew since
c.Left = append(c.Left, f.rel)
continue
}
+3
View File
@@ -861,6 +861,9 @@ func KeepLinked(ctx context.Context, interval time.Duration) {
keepBiliCompact()
// bili start, while an agent goes through its /bili/ prefix
keepBiliServe(ctx)
// the skills and prompts of a Remote magpie's Library, when
// switched on (borrow.go)
keepBorrowed(ctx)
// once a day, what agents saved to memory meanwhile
if res, err := PublishMemory(true); err != nil {
log.Println("library: memory:", err)
+6
View File
@@ -79,6 +79,12 @@ type Library struct {
// BridgesOn are the Remote magpies (provider ids) the user asked to
// give their router a server, in the editor's switch (bridge_mcp.go)
BridgesOn []string `json:"bridgesOn,omitempty"`
// BorrowOn are the Remote magpies (provider ids) whose Library's
// skills and prompts this computer uses, and Borrowed what it took
// from each (borrow.go). This computer's own: Collect doesn't carry
// either.
BorrowOn []string `json:"borrowOn,omitempty"`
Borrowed map[string]*Borrowed `json:"borrowed,omitempty"`
// SeenSkills are, by repository and ref ("owner/repo@ref", or a git
// address and ref), or by a folder the user added ("folder:<path>"),
// the folders of skills there the page has offered: picked or not at
+41
View File
@@ -0,0 +1,41 @@
package provider
import (
"context"
"errors"
"fmt"
"net/http"
"time"
)
// RemoteLibraryPath is where a remote magpie tells its Library's prompts
// and skills (KoiLx0 on X: managed on one computer, not on every client).
// It is answered to the computer itself and to a full-access gateway key
// of a magpie shared on the local network, as the quotas are.
const RemoteLibraryPath = "/v1/magpie/library"
// RemoteLibraryWait is how long a remote magpie has to send its skills.
const RemoteLibraryWait = 90 * time.Second
// maxRemoteLibrary is the most a remote's Library answer is read to: its
// skills' files, base64 in JSON (library.Shared keeps them under 24 MiB).
const maxRemoteLibrary = 48 << 20
const errRemoteNoLibrary = "remote magpie doesn't share its Library; update magpie on that computer"
// RemoteLibrary is the body of the Library the remote magpie id shares,
// and the remote's name.
func RemoteLibrary(ctx context.Context, id string) ([]byte, string, error) {
p, err := Find(id)
if err != nil {
return nil, "", err
}
if !p.IsRemoteMagpie() {
return nil, "", fmt.Errorf("%s is no remote magpie", id)
}
if p.Key == "" || p.Anthropic == "" {
return nil, "", errors.New("the remote magpie's address and key are needed")
}
b, err := remoteBodyAs(ctx, *p, http.MethodGet, RemoteLibraryPath, RemoteLibraryWait, maxRemoteLibrary, errRemoteNoLibrary)
return b, remoteName(*p), err
}
+8 -2
View File
@@ -511,6 +511,12 @@ func remoteJSON(ctx context.Context, p Provider, method, path string, wait time.
// gives back the body of a 2xx answer; any other is an error that says
// what to do about it.
func remoteBody(ctx context.Context, p Provider, method, path string, wait time.Duration) ([]byte, error) {
return remoteBodyAs(ctx, p, method, path, wait, 8<<20, errRemoteNoShare)
}
// remoteBodyAs is remoteBody for an answer of up to max bytes, and with
// noShare as the word for a remote that doesn't have the path.
func remoteBodyAs(ctx context.Context, p Provider, method, path string, wait time.Duration, max int64, noShare string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, wait)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, p.Anthropic+path, nil)
@@ -524,7 +530,7 @@ func remoteBody(ctx context.Context, p Provider, method, path string, wait time.
return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), err)
}
defer res.Body.Close()
b, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
b, err := io.ReadAll(io.LimitReader(res.Body, max))
if err != nil && ctx.Err() != nil {
return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), ctx.Err())
}
@@ -536,7 +542,7 @@ func remoteBody(ctx context.Context, p Provider, method, path string, wait time.
}
switch {
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed:
return nil, fmt.Errorf("%s", errRemoteNoShare)
return nil, fmt.Errorf("%s", noShare)
case res.StatusCode == http.StatusForbidden:
json.Unmarshal(b, &e)
switch e.Error.Code {