agent: Paseo's Claude model picker lists magpie's models (@TheMist016 on X)

Paseo (getpaseo/paseo) starts the same Claude Code, but builds its own model
list: first-party models plus settings.json's `model` and a few
ANTHROPIC_*_MODEL variables (providers/claude/models.ts). It never reads
Claude Code's modelPicker, where magpie writes every model, so the rest were
not selectable in Paseo. Paseo's own ~/.paseo/config.json takes
agents.providers.claude.additionalModels ([{id,label,description}], checked
against protocol/src/provider-config.ts) and passes each id to Claude Code as
written.

New agent "Paseo" (detected by ~/.paseo or PASEO_HOME): its switch writes the
models Claude Code's /model lists (same ids, [1m] marks, names; only the ones
picked for it) there, marked "via magpie" in the description; the user's own
entries and keys stay, off takes out only magpie's, a sync refreshes when on.
Claude Code must be connected to magpie as well.

Run (mote-run, sandbox HOME in tests): TestPaseoAdditionalModels,
TestStateListsPaseo, internal/agentenv, internal/gui full package ok;
internal/agent full run red only on TestPiGroupEntryKeepsItsMembers, which is
red the same on origin/main 12cd456f2 (passes alone; filed). gofmt clean,
vet darwin, windows and linux nogui on internal/agent. Broken by hand: Set
writing no models goes red.
Not tried: a real Paseo daemon reading the file (checked against its schema
source only); GUI browser suites.
This commit is contained in:
yetone
2026-11-11 23:08:39 +08:00
parent b587eb3069
commit 85e6ec5406
36 changed files with 372 additions and 887 deletions
+1 -1
View File
@@ -82,7 +82,7 @@ magpie finds the subscriptions your agents are signed in to by reading their sig
<table>
<tr><td>
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · Paseo · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
</td></tr>
</table>
+1 -1
View File
@@ -82,7 +82,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、
<table>
<tr><td>
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · Paseo · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
</td></tr>
</table>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -337,6 +337,7 @@ func onMachineAll(home, cfg string) []*Agent {
workbuddyAI(home),
codebuddy(home),
pencil(home),
paseo(home),
openPencil(home, cfg),
openBot(home, cfg),
craftAgents(home),
+158
View File
@@ -0,0 +1,158 @@
package agent
// Paseo (getpaseo/paseo, an app that runs Claude Code, Codex and others
// for you) starts the same Claude Code, which reads ~/.claude/settings.json
// and its modelPicker. Paseo lists models itself, though: its own first-party
// list plus the settings.json `model` and a few ANTHROPIC_*_MODEL tier
// variables (packages/server/src/server/agent/providers/claude/models.ts),
// never modelPicker. So the models magpie serves besides the main one and
// the tiers were not in Paseo's picker (@TheMist016 on X). Paseo takes more
// from its own ~/.paseo/config.json, agents.providers.claude.additionalModels,
// [{id,label,description}], appended to what it finds, each id passed to
// Claude Code as written (docs/custom-providers.md, ProviderProfileModelSchema).
//
// So the switch writes the models Claude Code's /model lists (the same ids,
// [1m] marks and names as claudeModelPicker) there, and takes out only its
// own entries on off, the user's staying. Claude Code itself must be
// connected to magpie for those ids to be served.
import (
"cmp"
"encoding/json"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
const paseoMark = "via magpie"
// paseoModels are magpie's models as Paseo's additionalModels entries.
func paseoModels() []map[string]any {
mark1M := claude1MFor("paseo")
labels := listLabels("paseo")
rows := []map[string]any{}
seen := map[string]bool{}
for _, o := range viaMagpie("paseo", "") {
id := provider.ClaudeSpelled(mark1M(o.Value))
if seen[id] {
continue
}
seen[id] = true
note := strings.TrimSuffix(o.Note, " · "+paseoMark)
desc := paseoMark
if note != "" && note != paseoMark {
desc = note + " · " + paseoMark
}
rows = append(rows, map[string]any{"id": id, "label": cmp.Or(labels[o.Ref], o.Label, o.Value), "description": desc})
}
return rows
}
// paseoOurs says an entry of additionalModels is magpie's.
func paseoOurs(e map[string]any) bool {
d, _ := e["description"].(string)
return d == paseoMark || strings.HasSuffix(d, " · "+paseoMark)
}
// paseoList is the file's additionalModels, and whether it could be read:
// a list that can't be is left as it is.
func paseoList(path string) (list []map[string]any, ok bool) {
raw, has := edit.GetJSONRaw(path, paseoKey)
if !has {
return nil, true
}
return list, json.Unmarshal([]byte(raw), &list) == nil
}
const paseoKey = "agents.providers.claude.additionalModels"
// paseoWrite puts magpie's entries (none when on is false) among the
// user's, which keep their place and come first.
func paseoWrite(path string, on bool) error {
cur, ok := paseoList(path)
if !ok {
return nil
}
mine := map[string]bool{}
var out []map[string]any
for _, e := range cur {
if !paseoOurs(e) {
out = append(out, e)
if id, _ := e["id"].(string); id != "" {
mine[id] = true
}
}
}
if on {
for _, e := range paseoModels() {
// an id the user listed themselves stays theirs
if !mine[e["id"].(string)] {
out = append(out, e)
}
}
}
if len(out) == 0 {
if _, has := edit.GetJSONRaw(path, paseoKey); !has {
return nil
}
return edit.DelJSON(path, paseoKey)
}
if raw, has := edit.GetJSONRaw(path, paseoKey); has && sameJSON(raw, out) {
return nil
}
return edit.SetJSON(path, edit.KV{Path: paseoKey, Value: out})
}
func paseo(home string) *Agent {
dir := os.Getenv("PASEO_HOME")
if dir == "" {
dir = filepath.Join(home, ".paseo")
}
path := filepath.Join(dir, "config.json")
wired := func() bool {
l, _ := paseoList(path)
for _, e := range l {
if paseoOurs(e) {
return true
}
}
return false
}
return &Agent{
ID: "paseo", Name: "Paseo", Icon: "generic", Aliases: []string{"getpaseo"},
Dir: dir, Path: path,
detect: func() bool { return isDir(dir) },
Notice: func() string {
if runtime.GOOS == "windows" || Running(`(^|/)[Pp]aseo( |$|\.)`, `Paseo\.app/`) {
return noticePaseo.String()
}
return ""
},
Sync: func() error {
if !wired() {
return nil
}
return paseoWrite(path, true)
},
ListsModels: true,
Fields: []Field{{
Key: "provider", Label: "provider",
Get: func() string {
if wired() {
return magpieID
}
return ""
},
Set: func(v string) error { return paseoWrite(path, v != "") },
Options: func(map[string]string) []Option {
return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "every magpie model in Paseo's Claude model picker"}}
},
}},
}
}
var noticePaseo = newNotice("Paseo reads its model list when its daemon starts — restart Paseo's daemon to see magpie's models. Claude Code must be connected to magpie too.")
+122
View File
@@ -0,0 +1,122 @@
package agent
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Paseo lists only settings.json's model and tiers, so magpie writes its
// models into ~/.paseo/config.json's agents.providers.claude.additionalModels
// (ProviderProfileModelSchema: id, label, description), leaves the user's own
// entries and keys, and takes out only its own (@TheMist016 on X).
func TestPaseoAdditionalModels(t *testing.T) {
home := syncHome(t)
t.Setenv("PASEO_HOME", "")
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil {
t.Fatal(err)
}
dir := filepath.Join(home, ".paseo")
path := filepath.Join(dir, "config.json")
a := paseo(home)
if a.Detected() {
t.Fatal("found with no ~/.paseo")
}
if !slices.ContainsFunc(All(), func(x *Agent) bool { return x.ID == "paseo" }) {
t.Fatal("Paseo is not among the agents")
}
os.MkdirAll(dir, 0o755)
user := `{"version":1,"daemon":{"listen":"127.0.0.1:6767"},"agents":{"providers":{"claude":{"additionalModels":[{"id":"mine/x","label":"Mine"}],"env":{"A":"b"}},"codex":{"enabled":true}}}}`
os.WriteFile(path, []byte(user), 0o600)
f := a.Field("provider")
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if f.Get() != magpieID {
t.Fatalf("get: %q", f.Get())
}
type doc struct {
Daemon map[string]any `json:"daemon"`
Agents struct {
Providers map[string]struct {
Additional []struct {
ID *string `json:"id"`
Label *string `json:"label"`
Desc string `json:"description"`
} `json:"additionalModels"`
Env map[string]string `json:"env"`
Enabled bool `json:"enabled"`
} `json:"providers"`
} `json:"agents"`
}
read := func() doc {
var d doc
if err := json.Unmarshal([]byte(readFile(path)), &d); err != nil {
t.Fatalf("%v\n%s", err, readFile(path))
}
return d
}
d := read()
c := d.Agents.Providers["claude"]
if d.Daemon["listen"] != "127.0.0.1:6767" || c.Env["A"] != "b" || !d.Agents.Providers["codex"].Enabled {
t.Errorf("the user's own keys changed: %s", readFile(path))
}
var ids []string
for _, e := range c.Additional {
if e.ID == nil || e.Label == nil || *e.ID == "" || *e.Label == "" {
t.Errorf("an entry Paseo's schema turns away: %+v", e)
}
ids = append(ids, *e.ID)
}
if len(ids) < 2 || ids[0] != "mine/x" || !slices.Contains(ids, "deepseek/pro") {
t.Errorf("ids: %v", ids)
}
for _, e := range c.Additional[1:] {
if !strings.HasSuffix(e.Desc, paseoMark) {
t.Errorf("not marked as magpie's: %+v", e)
}
}
n := len(ids)
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if len(read().Agents.Providers["claude"].Additional) != n {
t.Error("a sync changed the list")
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if f.Get() != "" {
t.Fatal("still wired after off")
}
c = read().Agents.Providers["claude"]
if len(c.Additional) != 1 || *c.Additional[0].ID != "mine/x" || c.Env["A"] != "b" {
t.Errorf("after off: %s", readFile(path))
}
// off, a sync leaves it off
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if len(read().Agents.Providers["claude"].Additional) != 1 {
t.Error("a sync put it back")
}
// on again with no file at all, then off leaves no empty key behind
os.Remove(path)
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if len(read().Agents.Providers["claude"].Additional) < 1 {
t.Error("no models in a new file")
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if strings.Contains(readFile(path), "additionalModels") {
t.Errorf("left behind: %s", readFile(path))
}
}
+1 -1
View File
@@ -95,7 +95,7 @@ var Vars = []string{
// named profile's folder (~/.openclaw-<profile>) and its own ~
"OPENCLAW_CONFIG_PATH", "OPENCLAW_STATE_DIR", "OPENCLAW_PROFILE", "OPENCLAW_HOME",
// MiMo Code, MiniMax Code, OpenHanako, Hermes, dsh, WorkBuddy, CodeBuddy Code
"MIMOCODE_HOME", "MINIMAX_DATA_DIR", "MAVIS_DATA_DIR", "HANA_HOME", "HERMES_HOME", "DSH_HOME",
"MIMOCODE_HOME", "MINIMAX_DATA_DIR", "MAVIS_DATA_DIR", "HANA_HOME", "PASEO_HOME", "HERMES_HOME", "DSH_HOME",
"WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR",
// DS Bot's data folder, and its Electron userData holding locations.json
"DS_BOT_HOME", "DS_BOT_SHELL_DATA",
+5 -72
View File
@@ -1100,7 +1100,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
log.Printf("claude: a branch of a claude -p run's session goes to a new interactive Claude Code, told the whole conversation")
from, req.branch = nil, nil
}
if from != nil && (from.cut != "" || len(from.cutCalls) > 0) {
if from != nil && from.cut != "" {
// a branch is a copy of the run's session as far as the reply
// that made the calls, a session of its own: Claude Code's
// interactive mode doesn't take --resume-session-at, and resumes
@@ -1111,20 +1111,14 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
if from.cutBefore {
cutter, how = cutSessionBefore, "a side request that sends the conversation whole, without the calls its run still waits on, goes on in a branch of that run's session, cut before them"
}
var sid string
var err error
if from.cut == "" {
sid, err = cutSessionBeforeCalls(from.sessions, from.session, from.cutCalls)
} else {
sid, err = cutter(from.sessions, from.session, from.cut)
}
sid, err := cutter(from.sessions, from.session, from.cut)
if err != nil {
log.Printf("claude: a branch of a run's session couldn't be cut (%v); a new Claude Code is told the whole conversation", err)
from, req.branch = nil, nil
} else {
log.Printf("claude: %s (%d messages)", how, len(from.since))
from.mu.Lock()
from.session, from.cut, from.cutCalls, from.cutBefore, from.gone = sid, "", nil, false, false
from.session, from.cut, from.cutBefore, from.gone = sid, "", false, false
from.mu.Unlock()
}
}
@@ -2536,9 +2530,6 @@ type savedSession struct {
// cutBefore: cut before that line, not after it: the reply's words
// stay and its calls go (a side request that dropped them, #6128)
cutBefore bool
// cutCalls: the cut is before the line of these tool calls, found by
// their ids, when the line's uuid isn't known yet (#6128).
cutCalls []string
// tui: the session was made by Claude Code's interactive mode; a
// branch of it is too, where it can be (claudePrint)
tui bool
@@ -2783,27 +2774,10 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
}
run.mu.Lock()
at, seq, said := "", 0, ""
var unread []string // pending calls whose line isn't read yet
if pending {
for id, l := range run.lines {
switch {
case l.told != told:
case l.uuid == "":
unread = append(unread, id)
if seq == 0 || l.seq < seq {
seq, said = l.seq, l.told
}
}
}
// A reply is parked on once its calls were streamed; its
// session line may not be read yet, nor on disk (#6128): the
// calls are found in the session by their ids, and a line
// already read is a surer place.
slices.Sort(unread)
for _, l := range run.lines {
if l.uuid != "" && l.told == told && (at == "" || l.seq < seq) {
at, seq, said = l.uuid, l.seq, l.told
unread = nil
}
}
} else {
@@ -2816,7 +2790,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
sid, sessions, prefix := run.sessionID, slices.Clone(run.sessions), run.cachePrefix
usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req))
run.mu.Unlock()
if at == "" && len(unread) == 0 {
if at == "" {
continue
}
switch {
@@ -2830,7 +2804,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
if pending && found != nil && seq <= foundSeq {
continue
}
found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutCalls: unread, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq
found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq
}
if !pending {
break
@@ -3033,47 +3007,6 @@ func cutSessionBefore(dirs []string, sid, uuid string) (string, error) {
return cutSessionAt(dirs, sid, uuid, cutBefore)
}
// cutSessionBeforeCalls is cutSession as far as the line before the first
// assistant line that calls one of ids, the calls a run's reply made that
// its line uuid isn't known for (#6128). Claude Code writes that line late,
// after its tool ran: asked again until cutWait is over, then, with the
// line not there, the session as it stands is what came before the calls.
func cutSessionBeforeCalls(dirs []string, sid string, ids []string) (string, error) {
if len(ids) == 0 {
return "", errors.New("no session to cut")
}
return cutSessionWhere(dirs, sid, "calls "+strings.Join(ids, ","), func(b []byte, last bool) int {
if end := cutBeforeCalls(b, ids); end >= 0 {
return end
}
if last {
return len(b)
}
return -1
})
}
// cutBeforeCalls is where in a session's lines b the first whole assistant
// line calling one of ids begins, -1 when none is there; a line with no
// newline yet is not whole.
func cutBeforeCalls(b []byte, ids []string) int {
for at := 0; at < len(b); {
nl := bytes.IndexByte(b[at:], '\n')
if nl < 0 {
break
}
line := b[at : at+nl]
start := at
at += nl + 1
for _, id := range ids {
if bytes.Contains(line, []byte(`"id":"`+id+`"`)) {
return start
}
}
}
return -1
}
// cutSessionWhere copies session sid as far as the place at finds in its
// lines (> 0), asked again until cutWait is over; last is the final ask.
// what is what it looks for, as an error says.
@@ -5,7 +5,6 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
// recih on X (#6128): Claude Code's AgentSummary sends the sub-agent's
@@ -71,60 +70,3 @@ func TestClaudeBranchForSummaryWithoutThePendingCall(t *testing.T) {
t.Fatalf("closed run: %v %q", got, why)
}
}
// #6128 (recih, v0.1.3757): the run parks on a call it streamed before the
// call's session line is read or written (Claude Code writes it after the
// tool ran), so the line has no uuid. The summary is found by the history
// the call answered, and the branch is cut before the call by its id,
// whether the line is on disk by then or not.
func TestClaudeBranchForSummaryBeforeTheCallLineIsRead(t *testing.T) {
was := cutWait
cutWait = 300 * time.Millisecond
t.Cleanup(func() { cutWait = was })
dir := t.TempDir()
const sid = "lead-session"
path := filepath.Join(dir, sid+".jsonl")
head := `{"uuid":"u1","sessionId":"` + sid + `","type":"user"}` + "\n" + `{"uuid":"a-words","sessionId":"` + sid + `","type":"assistant"}` + "\n"
if err := os.WriteFile(path, []byte(head), 0o600); err != nil {
t.Fatal(err)
}
user := func(s string) Message { return Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}} }
words := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "I will run the tests."}}}
history := []Message{user("task")}
b := newSubscriptionBridge()
run := &subscriptionRun{sessionID: sid, sessions: []string{dir}, tui: true}
own := "claude\x00u"
run.owner.Store(&own)
run.lines = map[string]callLine{"toolu_1": {seq: 1, told: historyKey(history)}} // parked, no uuid yet
b.runs["r"] = run
req := &Request{Messages: append(append(append([]Message{}, history...), words), user("Describe your progress in 3-5 words."))}
got, why := b.branch(req, own)
if got == nil {
t.Fatalf("no branch while the call's line is unread: %s", why)
}
if !got.cutBefore || len(got.cutCalls) != 1 || got.cutCalls[0] != "toolu_1" {
t.Fatalf("branch = %+v, want cut before the call toolu_1", got)
}
// the line is written while the cut waits for it: the cut is before it
go func() {
time.Sleep(60 * time.Millisecond)
f, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
defer f.Close()
f.WriteString(`{"uuid":"a-call","sessionId":"` + sid + `","type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_1"}]}}` + "\n")
}()
id, err := cutSessionBeforeCalls(got.sessions, got.session, got.cutCalls)
if err != nil {
t.Fatal(err)
}
if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") || strings.Contains(string(s), "a-call") {
t.Fatalf("branch keeps %q, want the words and not the call", s)
}
// the line never comes: what is on disk is what came before the call
id, err = cutSessionBeforeCalls(got.sessions, got.session, []string{"toolu_9"})
if err != nil {
t.Fatal(err)
}
if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") {
t.Fatalf("branch keeps %q, want the words", s)
}
}
+2 -2
View File
@@ -63,7 +63,7 @@ func openCodeGeminiServer(t *testing.T, s *Server) func() []openCodeAsk {
switch {
case r.Method != http.MethodPost:
return reply(404, "application/json", `{}`)
case gemini && (strings.HasPrefix(path, "/zen/v1/models/") || strings.HasPrefix(path, "/inference/go/google/v1beta/models/")):
case gemini && (strings.HasPrefix(path, "/zen/v1/models/") || strings.HasPrefix(path, "/inference/go/v1/models/")):
return reply(200, "text/event-stream", openCodeGeminiSSE)
case strings.Contains(path, ":") || strings.Contains(path, "/models/"):
return reply(404, "text/html", `<html>Not Found</html>`)
@@ -113,7 +113,7 @@ func TestOpenCodeGoGeminiModelOnGeminiAPI(t *testing.T) {
}
s := New()
took := openCodeGeminiServer(t, s)
const want = "opencode.ai/inference/go/google/v1beta/models/gemini-4-argon-contributor:streamGenerateContent?alt=sse"
const want = "opencode.ai/inference/go/v1/models/gemini-4-argon-contributor:streamGenerateContent?alt=sse"
check := func(what string, code int, body string) openCodeAsk {
t.Helper()
asked := took()
+6 -6
View File
@@ -36,7 +36,7 @@ func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefus
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "go", Name: "OpenCode Go", Preset: "opencode-go", Key: "sk-go-users-own",
Chat: provider.OpenCodeGoChat, Responses: provider.OpenCodeGoChat, Anthropic: provider.OpenCodeGoAnthropic,
Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go",
Models: models}); err != nil {
t.Fatal(err)
}
@@ -55,7 +55,7 @@ func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefus
model = m
}
}
if strings.HasPrefix(r.URL.Path, "/inference/go/") {
if strings.HasPrefix(r.URL.Path, "/zen/go/") {
for _, m := range serves {
if m == model {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}},
@@ -96,8 +96,8 @@ func TestOpenCodeGoFreeModelAskedAtZen(t *testing.T) {
}
a := asked()
// on the API Go was asked on, at Zen's free tier
want := map[string]string{"opencode.ai/inference/go/anthropic/v1/messages": "opencode.ai/inference/anthropic/v1/messages",
"opencode.ai/inference/go/openai/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"}
want := map[string]string{"opencode.ai/zen/go/v1/messages": "opencode.ai/inference/anthropic/v1/messages",
"opencode.ai/zen/go/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"}
if len(a) != 2 || want[a[0].url] == "" || a[1].url != want[a[0].url] {
t.Fatalf("asked %+v", a)
}
@@ -114,7 +114,7 @@ func TestOpenCodeGoOwnFreeModelStaysOnGo(t *testing.T) {
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from go") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/inference/go/") {
if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/zen/go/") {
t.Fatalf("asked %+v", a)
}
}
@@ -137,7 +137,7 @@ func TestOpenCodeGoUnavailableSaysWhere(t *testing.T) {
t.Fatalf("%d %s", rec.Code, body)
}
for _, a := range asked()[n:] {
if !strings.HasPrefix(a.url, "opencode.ai/inference/go/") {
if !strings.HasPrefix(a.url, "opencode.ai/zen/go/") {
t.Fatalf("a paid model asked at %s", a.url)
}
}
+1 -2
View File
@@ -422,7 +422,6 @@ func Run(version string, showMain bool, link string) error {
// a quiet start joins the Dock once started (below): Wails activates
// an app that starts in it
policy := dockPolicy(settings.Load().Dock && !quiet)
webView2Prepare()
h.app = application.New(application.Options{
// Windows and Linux start a new process for a magpie:// link (or a
// second launch); it hands its arguments to the running one and quits.
@@ -473,7 +472,7 @@ func Run(version string, showMain bool, link string) error {
updates.install(false)
},
// Wails exits on some webview errors; say why before it does.
ErrorHandler: func(err error) { webView2Failed(h.app, err) },
ErrorHandler: func(err error) { log.Println("magpie:", err) },
})
// Windows without the WebView2 runtime can make no window: Wails would
// exit on the first, with nothing on screen to say why (#1806). The
+5
View File
@@ -4875,6 +4875,7 @@ const I18N = {
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent 运行时把设置放在内存里,任一设置变化时会全部写回 —— 请先退出 LiveAgent 再更改这里,然后打开它,在模型选择器中选一个 magpie 的模型。",
"OpenMausBot reads its engines when it starts and writes back the ones it holds when you change one in it — quit OpenMausBot before changing this, then open it and pick magpie as a bot's engine.": "OpenMausBot 启动时读取它的引擎,在其中改动任一引擎时会把它持有的引擎写回 —— 请先退出 OpenMausBot 再更改这里,然后打开它,给机器人选 magpie 作为引擎。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil 启动时读取自定义模型,需重启 Pencil 才能在它的模型选择器中看到 magpie 的模型。",
"Paseo reads its model list when its daemon starts — restart Paseo's daemon to see magpie's models. Claude Code must be connected to magpie too.": "Paseo 在守护进程启动时读取模型列表,需重启 Paseo 的守护进程才能看到 magpie 的模型。Claude Code 也须已接入 magpie。",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On a gateway it uses no Google sign-in, so what Google turns on for your account (its experiments, and commands such as /boost, /teamwork, /plugin and /generative_ui) is gone while it's on magpie; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity 启动时读取网关,需重启 Antigravity 才能使用 magpie 的模型。走网关时它不使用 Google 登录,所以 Google 为你的账号开启的功能(它的实验,以及 /boost、/teamwork、/plugin、/generative_ui 等命令)在接入 magpie 期间都没有;在这里关闭即可恢复。未在自己那一行接入的 agy 也会跟着它走。",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravity 的 {path} 设置了自己的网关,它优先于 ~/.antigravity/settings.json,所以不会连到 magpie",
"AGY_LLM_GATEWAY_URL is set to {url}, which wins over ~/.antigravity/settings.json, so Antigravity started with it doesn't reach magpie": "AGY_LLM_GATEWAY_URL 被设为 {url},它优先于 ~/.antigravity/settings.json,所以这样启动的 Antigravity 不会连到 magpie",
@@ -9951,6 +9952,7 @@ const I18N = {
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent 執行時把設定放在記憶體中,任一設定變更時會全部寫回 —— 請先結束 LiveAgent 再變更這裡,然後開啟它,在模型選擇器中選一個 magpie 的模型。",
"OpenMausBot reads its engines when it starts and writes back the ones it holds when you change one in it — quit OpenMausBot before changing this, then open it and pick magpie as a bot's engine.": "OpenMausBot 啟動時讀取它的引擎,在其中變更任一引擎時會把它持有的引擎寫回 —— 請先結束 OpenMausBot 再變更這裡,然後開啟它,為機器人選 magpie 作為引擎。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil 啟動時讀取自訂模型,需重啟 Pencil 才能在它的模型選擇器中看到 magpie 的模型。",
"Paseo reads its model list when its daemon starts — restart Paseo's daemon to see magpie's models. Claude Code must be connected to magpie too.": "Paseo 在守護程序啟動時讀取模型清單,需重啟 Paseo 的守護程序才能看到 magpie 的模型。Claude Code 也須已接入 magpie。",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On a gateway it uses no Google sign-in, so what Google turns on for your account (its experiments, and commands such as /boost, /teamwork, /plugin and /generative_ui) is gone while it's on magpie; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity 啟動時讀取閘道,需重啟 Antigravity 才能使用 magpie 的模型。走閘道時它不使用 Google 登入,所以 Google 為你的帳號開啟的功能(它的實驗,以及 /boost、/teamwork、/plugin、/generative_ui 等指令)在接入 magpie 期間都沒有;在這裡關閉即可恢復。未在自己那一列接入的 agy 也會跟著它走。",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravity 的 {path} 設定了自己的閘道,它優先於 ~/.antigravity/settings.json,所以不會連到 magpie",
"AGY_LLM_GATEWAY_URL is set to {url}, which wins over ~/.antigravity/settings.json, so Antigravity started with it doesn't reach magpie": "AGY_LLM_GATEWAY_URL 被設為 {url},它優先於 ~/.antigravity/settings.json,所以這樣啟動的 Antigravity 不會連到 magpie",
@@ -15029,6 +15031,7 @@ const I18N = {
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent は実行中に設定をメモリに保持し、設定が変わるたびにすべて書き戻します。ここを変更する前に LiveAgent を終了し、その後開いてモデル選択で magpie のモデルを選んでください。",
"OpenMausBot reads its engines when it starts and writes back the ones it holds when you change one in it — quit OpenMausBot before changing this, then open it and pick magpie as a bot's engine.": "OpenMausBot は起動時にエンジンを読み込み、その中でエンジンを変更すると保持しているエンジンを書き戻します。ここを変更する前に OpenMausBot を終了し、その後開いてボットのエンジンに magpie を選んでください。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil は起動時にカスタムモデルを読み込みます。モデル選択に magpie のモデルを表示するには Pencil を再起動してください。",
"Paseo reads its model list when its daemon starts — restart Paseo's daemon to see magpie's models. Claude Code must be connected to magpie too.": "Paseo は起動時にデーモンがモデル一覧を読み込みます。magpie のモデルを表示するには Paseo のデーモンを再起動してください。Claude Code も magpie に接続されている必要があります。",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On a gateway it uses no Google sign-in, so what Google turns on for your account (its experiments, and commands such as /boost, /teamwork, /plugin and /generative_ui) is gone while it's on magpie; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity は起動時にゲートウェイを読み込みます。magpie のモデルを使うには Antigravity を再起動してください。ゲートウェイ経由では Google のサインインは使われないため、Google がアカウントに有効にする機能(実験や、/boost、/teamwork、/plugin、/generative_ui などのコマンド)は magpie 接続中は使えません。ここでオフにすると元に戻ります。自分の行で接続していない agy もこれに従います。",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravity の {path} が独自のゲートウェイを設定しており、~/.antigravity/settings.json より優先されるため、magpie に届きません",
"AGY_LLM_GATEWAY_URL is set to {url}, which wins over ~/.antigravity/settings.json, so Antigravity started with it doesn't reach magpie": "AGY_LLM_GATEWAY_URL が {url} に設定されており、~/.antigravity/settings.json より優先されるため、これで起動した Antigravity は magpie に届きません",
@@ -20107,6 +20110,7 @@ const I18N = {
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent hält seine Einstellungen während der Ausführung im Speicher und schreibt sie bei jeder Änderung alle zurück – LiveAgent vor dieser Änderung beenden, dann öffnen und in seiner Modellauswahl ein magpie-Modell wählen.",
"OpenMausBot reads its engines when it starts and writes back the ones it holds when you change one in it — quit OpenMausBot before changing this, then open it and pick magpie as a bot's engine.": "OpenMausBot liest seine Engines beim Start und schreibt die gehaltenen zurück, sobald du dort eine änderst – OpenMausBot vor dieser Änderung beenden, dann öffnen und magpie als Engine eines Bots wählen.",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil liest seine eigenen Modelle beim Start – Pencil neu starten, um magpies Modelle in seiner Modellauswahl zu sehen.",
"Paseo reads its model list when its daemon starts — restart Paseo's daemon to see magpie's models. Claude Code must be connected to magpie too.": "Paseo liest seine Modellliste beim Start des Daemons – Paseo-Daemon neu starten, um magpies Modelle zu sehen. Claude Code muss ebenfalls mit magpie verbunden sein.",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On a gateway it uses no Google sign-in, so what Google turns on for your account (its experiments, and commands such as /boost, /teamwork, /plugin and /generative_ui) is gone while it's on magpie; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity liest sein Gateway beim Start – Antigravity neu starten, um magpies Modelle zu nutzen. Über ein Gateway nutzt es keine Google-Anmeldung, daher fehlt, was Google für dein Konto freischaltet (seine Experimente und Befehle wie /boost, /teamwork, /plugin und /generative_ui), solange es über magpie läuft; hier ausschalten gibt es zurück. Ein agy, das nicht in seiner eigenen Zeile verbunden ist, folgt ihm auch.",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravitys {path} setzt ein eigenes Gateway, das Vorrang vor ~/.antigravity/settings.json hat, daher erreicht es magpie nicht",
"AGY_LLM_GATEWAY_URL is set to {url}, which wins over ~/.antigravity/settings.json, so Antigravity started with it doesn't reach magpie": "AGY_LLM_GATEWAY_URL ist auf {url} gesetzt, das Vorrang vor ~/.antigravity/settings.json hat, daher erreicht ein damit gestartetes Antigravity magpie nicht",
@@ -20395,6 +20399,7 @@ const NOTICES = [
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.",
"OpenMausBot reads its engines when it starts and writes back the ones it holds when you change one in it — quit OpenMausBot before changing this, then open it and pick magpie as a bot's engine.",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.",
"Paseo reads its model list when its daemon starts — restart Paseo's daemon to see magpie's models. Claude Code must be connected to magpie too.",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On a gateway it uses no Google sign-in, so what Google turns on for your account (its experiments, and commands such as /boost, /teamwork, /plugin and /generative_ui) is gone while it's on magpie; turning it off here gives that back. An agy not connected on its own row follows it too.",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie",
"AGY_LLM_GATEWAY_URL is set to {url}, which wins over ~/.antigravity/settings.json, so Antigravity started with it doesn't reach magpie",
+1 -50
View File
@@ -6680,53 +6680,6 @@ magpie.plugin("library", (ctx) => {
};
}
// A skill of the user's own: a name and a description make its SKILL.md
// in the library's folder (josephBenchap on X); it opens in the reader,
// whose path opens it in their editor.
function newSkill() {
const all = skillAgents();
const d = { name: "", description: "", agents: all.map((a) => a.id) };
const ed = el("div", "editor lib-editor lib-newskill");
const head = el("div", "ehead");
head.append(glyph(GLYPH.skill), el("b", "", t("New skill")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2("", t("e.g. my-skill"), (v) => { d.name = v.trim(); });
name.classList.add("mono");
ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it")));
const desc = el("textarea", "lib-text small lib-newskilldesc");
desc.placeholder = t("e.g. Writes release notes. Use when asked for a changelog.");
desc.spellcheck = false;
desc.rows = 2;
desc.maxLength = 1024;
desc.oninput = () => { d.description = desc.value; };
desc.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter") { e.preventDefault(); modal?.save?.(); } };
ed.append(...field(t("Description"), desc, t("What it does and when to use it: the agent reads this to decide when to load it")));
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
ed.append(err);
const drawAgents = () => agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, all: true }));
drawAgents();
const bar = el("div", "bar");
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
const save = async () => {
err.textContent = "";
try {
take(await api("library/skills/create", { name: d.name, description: d.description, agents: d.agents }));
report(lib.result, t("{name} is in the library now", { name: d.name }));
render();
const made = lib.skills.find((x) => x.name === d.name);
if (made) viewSkill(made); else closeLibModal(true);
} catch (e) { err.textContent = e.message; }
};
bar.append(button(t("Create"), "primary", save));
ed.append(bar);
const original = JSON.stringify(d);
modal = { save, dirty: () => JSON.stringify(d) !== original };
openLib(ed);
requestAnimationFrame(() => name.focus());
}
function installCard() {
const card = el("div", "list lib-card lib-install");
const line = el("div", "lib-find");
@@ -6742,9 +6695,7 @@ magpie.plugin("library", (ctx) => {
if (probing) go.classList.add("busy");
inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") find(); else if (e.key === "Escape" && probe) { probe = null; render(); } };
const g = glyph(GLYPH.search, "lib-mini");
const mk = button(t("New skill"), "", () => newSkill());
mk.dataset.lib = "new-skill";
line.append(g, inp, go, mk);
line.append(g, inp, go);
card.append(line);
async function find() {
const src = inp.value.trim();
@@ -2,10 +2,6 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"New skill": "新建技能",
"e.g. my-skill": "例如 my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "例如:撰写发布说明。需要更新日志时使用。",
"What it does and when to use it: the agent reads this to decide when to load it": "它做什么、何时使用:Agent 据此决定何时加载它",
"This computer follows the server: what you change here is replaced by the next sync.": "这台电脑跟随服务器:你在这里的改动会被下一次同步替换。",
"Sync settings": "同步设置",
"Stop picking memories": "不再选择记忆",
@@ -979,10 +975,6 @@ magpie.strings({
"{name} read again from its source": "已重新从来源读取 {name}",
},
"zh-TW": {
"New skill": "新增技能",
"e.g. my-skill": "例如 my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "例如:撰寫發佈說明。需要更新日誌時使用。",
"What it does and when to use it: the agent reads this to decide when to load it": "它做什麼、何時使用:Agent 據此決定何時載入它",
"This computer follows the server: what you change here is replaced by the next sync.": "這台電腦跟隨伺服器:你在這裡的變更會被下一次同步取代。",
"Sync settings": "同步設定",
"Stop picking memories": "不再選擇記憶",
@@ -1956,10 +1948,6 @@ magpie.strings({
"{name} read again from its source": "已重新從來源讀取 {name}",
},
ja: {
"New skill": "新しいスキル",
"e.g. my-skill": "例: my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "例: リリースノートを書く。変更履歴を求められたときに使う。",
"What it does and when to use it: the agent reads this to decide when to load it": "何をするか、いつ使うか。エージェントはこれを読んで読み込むかを決めます",
"This computer follows the server: what you change here is replaced by the next sync.": "このコンピュータはサーバーに従います。ここでの変更は次の同期で置き換えられます。",
"Sync settings": "同期の設定",
"Stop picking memories": "メモリの選択を終える",
@@ -2933,10 +2921,6 @@ magpie.strings({
"{name} read again from its source": "{name} をソースから読み直しました",
},
de: {
"New skill": "Neuer Skill",
"e.g. my-skill": "z. B. my-skill",
"e.g. Writes release notes. Use when asked for a changelog.": "z. B. Schreibt Release Notes. Zu verwenden, wenn ein Changelog verlangt wird.",
"What it does and when to use it: the agent reads this to decide when to load it": "Was er tut und wann er gebraucht wird: Der Agent entscheidet danach, ob er ihn lädt",
"This computer follows the server: what you change here is replaced by the next sync.": "Dieser Computer folgt dem Server: Änderungen hier werden bei der nächsten Synchronisierung ersetzt.",
"Sync settings": "Sync-Einstellungen",
"Stop picking memories": "Keine Erinnerungen mehr auswählen",
+1 -1
View File
@@ -13,7 +13,7 @@ import (
// genericIcon are the clients magpie has no logo for yet, drawn with the
// generic cube on purpose (#4487). Each leaves this list when its real
// logo, from the app or its vendor, is added.
var genericIcon = map[string]bool{"ante": true, "pencil": true, "openpencil": true, "newmax": true, "kirocrew": true, "raft": true}
var genericIcon = map[string]bool{"ante": true, "pencil": true, "paseo": true, "openpencil": true, "newmax": true, "kirocrew": true, "raft": true}
// Every client a request can be recorded as is drawn by its own name and
// icon in the Routing page's request list, Usage and Sessions, which all
+5 -9
View File
@@ -604,13 +604,11 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
// Agents is named as the page sends it, so that it is this
// and not the instructions' own Agents that "agents" fills
Agents []string `json:"agents"`
// Description is a new skill's (skills/create)
Description string `json:"description"`
Source string
Paths []string
Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents
Server library.Server
Hook library.Hook // a hook saved (#1790)
Source string
Paths []string
Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents
Server library.Server
Hook library.Hook // a hook saved (#1790)
// a subagent saved (#2283)
Subagent library.Subagent
Agent string // the agent whose own skill is in the library's way
@@ -717,8 +715,6 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.RemoveSubagents([]string{in.Name})
case "skills/install":
res, err = library.InstallSkills(in.Source, in.Paths, in.Agents)
case "skills/create":
res, err = library.CreateSkill(in.Name, in.Description, in.Agents)
case "skills/update":
res, err = library.UpdateSkill(in.Name, in.Replace)
var gone *library.GoneError
+3 -4
View File
@@ -94,10 +94,9 @@ func inlinePage(html []byte, dir string) (out []byte, hashes []string) {
if !ok {
return tag
}
// the hash covers the exact text between the tags, the newline
// before </script> included
s := "<script>" + strings.ReplaceAll(body, "</script", `<\/script`) + "\n</script>"
hash(strings.TrimSuffix(strings.TrimPrefix(s, "<script>"), "</script>"))
body = strings.ReplaceAll(body, "</script", `<\/script`)
hash(body)
s := "<script>" + body + "\n</script>"
if attrDefer.MatchString(attrs) {
deferred = append(deferred, s)
return ""
+33
View File
@@ -0,0 +1,33 @@
package gui
import (
"os"
"path/filepath"
"testing"
)
// Paseo is on the page once ~/.paseo is there, with magpie to put in its
// Claude model picker (@TheMist016 on X).
func TestStateListsPaseo(t *testing.T) {
home := sandboxHome(t)
t.Setenv("PASEO_HOME", "")
find := func() *agentJSON {
for _, a := range state().Agents {
if a.ID == "paseo" {
return &a
}
}
return nil
}
if find() != nil {
t.Fatal("listed with no ~/.paseo")
}
os.MkdirAll(filepath.Join(home, ".paseo"), 0o755)
a := find()
if a == nil {
t.Fatal("Paseo not listed")
}
if a.Name != "Paseo" || len(a.Fields) != 1 || a.Fields[0].Key != "provider" || a.Fields[0].Options[0].Value != "magpie" {
t.Fatalf("Paseo: %+v", a)
}
}
-15
View File
@@ -2,15 +2,12 @@ package gui
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
@@ -459,18 +456,6 @@ func TestPluginPageWebComesAsOneDocument(t *testing.T) {
if n := strings.Count(csp, "'sha256-"); n != 3 || !strings.Contains(csp, "data:") {
t.Errorf("hashes of the three scripts: %s", csp)
}
// each hash is the sha256 of the exact bytes between the tags, as served
inl := regexp.MustCompile(`(?s)<script>(.*?)</script>`)
got := inl.FindAllStringSubmatch(body, -1)
if len(got) != 3 {
t.Fatalf("inline scripts: %d in %s", len(got), body)
}
for _, m := range got {
sum := sha256.Sum256([]byte(m[1]))
if h := "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"; !strings.Contains(csp, h) {
t.Errorf("served script %q has hash %s, not in the policy: %s", m[1], h, csp)
}
}
// not in a browser (the desktop window): files as they are
mux = http.NewServeMux()
pluginPageRoutes(mux, false)
@@ -1,93 +0,0 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A skill made in the Library (josephBenchap on X): Skills > New skill takes
// a name and a description and the agents, posts library/skills/create, and
// opens the new skill in the reader. A refusal is said in the dialog and the
// dialog stays. No native select, no sideways scroll. English and Chinese,
// Chromium and WebKit, 1100 and 420px. The API is faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/emo";
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
const lib = (skills) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("codex", "Codex"), agent("claude", "Claude Code")],
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills, servers: [],
});
function server(lang, posts, state) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib(state.skills) });
if (url.pathname === "/api/library/skills/create") {
const b = req.postDataJSON();
posts.push(b);
if (b.name === "taken") return route.fulfill({ status: 400, body: "there is a skill called taken already" });
state.skills = [{ name: b.name, description: b.description, agents: b.agents }];
return route.fulfill({ json: { ...lib(state.skills), result: { changed: b.agents, problems: [] } } });
}
if (url.pathname === "/api/library/skill") return route.fulfill({ json: { text: `---\nname: ${url.searchParams.get("name")}\n---\n`, path: `${HOME}/.magpie/library/skills/${url.searchParams.get("name")}/SKILL.md` } });
if (url.pathname === "/api/library/rtk") return route.fulfill({ json: {} });
if (url.pathname === "/api/davsync") return route.fulfill({ json: { on: false } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Library makes a skill of the user's own", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => { if (errors.length) console.log(errors); await browser.close(); });
for (const lang of ["en", "zh"]) {
for (const width of [1100, 420]) {
await t.test(`${lang} ${width}`, async () => {
const ctx = await browser.newContext({ viewport: { width, height: 800 } });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
const posts = [], state = { skills: [] };
await page.route("**/*", server(lang, posts, state));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const v = page.locator("#view-library");
await v.locator("[data-lib=new-skill]").click();
const dlg = page.locator(".lib-newskill");
await dlg.waitFor();
assert.equal(await dlg.locator("select").count(), 0, "native select");
const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert(sideways <= 0, `page scrolls sideways by ${sideways}px`);
// a refusal stays in the dialog
await dlg.locator("input").first().fill("taken");
await dlg.locator("textarea").fill("Does a thing");
await dlg.locator("button.primary").click();
await dlg.locator(".editor-error").filter({ hasText: "taken" }).waitFor();
assert.equal(posts.length, 1);
// one agent unticked, then created
await dlg.locator("input").first().fill("my-skill");
await dlg.locator(".lib-ag[data-agent=claude]").click();
await dlg.locator("button.primary").click();
await page.locator(".lib-reader").waitFor();
assert.deepEqual(posts[1], { name: "my-skill", description: "Does a thing", agents: ["codex"] });
await page.locator(".lib-reader .lib-md").filter({ hasText: "my-skill" }).waitFor();
await ctx.close();
});
}
}
});
}
@@ -1,47 +0,0 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A plugin page served to a browser comes as one document whose inline
// scripts are allowed by hash (pageinline.go). The hash is of the exact
// bytes between the tags, the newline before </script> included; a hash of
// the body alone blocks the script and leaves the page blank (zhangly1 on X).
// pluginpage_test.go checks the hashes Go sends against the bytes it serves;
// this checks the browsers agree, with no violation, and that a hash of the
// body without the newline would have been blocked.
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const tok = "d".repeat(32);
const sha = (s) => `'sha256-${crypto.createHash("sha256").update(s).digest("base64")}'`;
const body = "window.ran = 1;";
function serve(hash) {
return async (route) => {
const url = new URL(route.request().url());
if (url.pathname !== `/_magpie/plugin/${tok}/index.html`) return route.fulfill({ status: 404, body: "" });
const doc = `<!doctype html><meta charset="utf-8"><script>${body}\n</script><p id=p>page</p>`;
return route.fulfill({ headers: { "Content-Type": "text/html", "Content-Security-Policy": `sandbox allow-scripts; default-src 'none'; script-src ${hash}` }, body: doc });
};
}
async function open(browser, hash) {
const p = await browser.newPage();
p.setDefaultNavigationTimeout(60000);
await p.addInitScript(() => { window.violations = []; document.addEventListener("securitypolicyviolation", (e) => window.violations.push(e.violatedDirective)); });
await p.route("**/*", serve(hash));
await p.goto(`http://magpie.test/_magpie/plugin/${tok}/index.html`);
return p;
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a hash of the served bytes runs the page's script`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const ok = await open(browser, sha(body + "\n"));
assert.equal(await ok.evaluate(() => window.ran), 1);
assert.deepEqual(await ok.evaluate(() => window.violations), []);
// the old hash, of the body without the newline served after it
const bad = await open(browser, sha(body));
assert.equal(await bad.evaluate(() => window.ran), undefined);
});
}
-80
View File
@@ -2,11 +2,8 @@ package gui
import (
"fmt"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
)
// magpie's windows are WebView2 on Windows, a runtime Windows 10 doesn't
@@ -130,80 +127,3 @@ func splitArgs(s string) []string {
}
return out
}
// WebView2 that does not come up. A magpie started while the one before it
// is still going down finds the profile folder held by the old
// msedgewebview2, and Wails waits a minute for a controller that never
// arrives, then exits (@ljlwlcz on X, 0.1.3688: a restart by a script left
// no window). Two things answer it: the start waits for the folder to be
// free, and a start that still fails is tried again, a few times.
// webView2TryEnv counts the starts that ended in a WebView2 failure; each
// relaunch passes it on.
const webView2TryEnv = "MAGPIE_WV2_TRY"
// webView2Tries is how many starts are made before the failure is shown.
const webView2Tries = 3
// webView2Folder is the folder WebView2 keeps its profile in: the one magpie
// passes Wails (webViewUserDataPath), else Wails' own default,
// %AppData%\<exe name>.
func webView2Folder(userDataPath, appData, exe string) string {
if userDataPath != "" {
return userDataPath
}
if appData == "" || exe == "" {
return ""
}
return filepath.Join(appData, filepath.Base(exe))
}
// webView2Failure says whether err is the webview not coming up, the
// errors Wails' Embed reports: the controller timeout and the loader's.
func webView2Failure(err error) bool {
if err == nil {
return false
}
m := strings.ToLower(err.Error())
return strings.Contains(m, "webview2")
}
// webView2Try is the number of starts already made, from the env value.
func webView2Try(v string) int {
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
return 0
}
return n
}
// webView2Backoff is how long a start waits before the n-th try (n >= 1).
func webView2Backoff(n int) time.Duration {
return time.Duration(n) * 2 * time.Second
}
// awaitWebView2Folder polls free until it says so or max passes, and says
// whether it was free. sleep is a var for tests.
func awaitWebView2Folder(free func() bool, max, step time.Duration, sleep func(time.Duration)) bool {
for waited := time.Duration(0); ; waited += step {
if free() {
return true
}
if waited >= max {
return false
}
sleep(step)
}
}
// webView2FailedNotice is the box shown when the webview would not start
// after every try: what failed and what to do, in lang (English where it
// has none of its own).
func webView2FailedNotice(lang, reason, version string) (title, body string) {
if strings.HasPrefix(lang, "zh") {
return "magpie 的窗口没能打开",
fmt.Sprintf("WebView2 在 %d 次启动里都没有就绪(运行时 %s)。\r\n\r\n%s\r\n\r\n请结束残留的 msedgewebview2.exe 后重新打开 magpie;也可以用 \"magpie web\" 在浏览器里打开。详情见 magpie 的日志。", webView2Tries, version, reason)
}
return "magpie's window didn't open",
fmt.Sprintf("WebView2 was not ready in %d starts (runtime %s).\r\n\r\n%s\r\n\r\nEnd any leftover msedgewebview2.exe and open magpie again, or use \"magpie web\" in your browser. The details are in magpie's log.", webView2Tries, version, reason)
}
@@ -1,35 +0,0 @@
//go:build windows && !nogui
package gui
import (
"os"
"path/filepath"
"testing"
"golang.org/x/sys/windows"
)
// Chromium holds EBWebView\lockfile without sharing while its browser
// process runs; the start waits on it (@ljlwlcz on X).
func TestWebView2FreeSeesTheHeldLockfile(t *testing.T) {
dir := t.TempDir()
if !webView2Free(dir) {
t.Fatal("no lockfile is free")
}
lock := filepath.Join(dir, "EBWebView", "lockfile")
if err := os.MkdirAll(filepath.Dir(lock), 0o755); err != nil {
t.Fatal(err)
}
h, err := windows.CreateFile(windows.StringToUTF16Ptr(lock), windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
t.Fatal(err)
}
if webView2Free(dir) {
t.Fatal("a lockfile held without sharing is free")
}
windows.CloseHandle(h)
if !webView2Free(dir) {
t.Fatal("a released lockfile is held")
}
}
+1 -11
View File
@@ -2,17 +2,7 @@
package gui
import (
"log"
"github.com/wailsapp/wails/v3/pkg/application"
)
import "github.com/wailsapp/wails/v3/pkg/application"
// webView2Check: only Windows' windows are WebView2.
func webView2Check(*application.App) bool { return true }
// webView2Prepare: only Windows' windows are WebView2.
func webView2Prepare() {}
// webView2Failed: Wails exits after this on every OS; say why.
func webView2Failed(_ *application.App, err error) { log.Println("magpie:", err) }
-45
View File
@@ -1,10 +1,8 @@
package gui
import (
"errors"
"strings"
"testing"
"time"
)
// #1806 (ufec): Wails' "WebView2" is "" when its lookup fails, the version
@@ -57,46 +55,3 @@ func TestWebView2Notice(t *testing.T) {
t.Errorf("pt: %q, want English", title)
}
}
func TestWebView2Folder(t *testing.T) {
if got := webView2Folder(`D:\p\webview2`, `C:\A`, `C:\x\magpie.exe`); got != `D:\p\webview2` {
t.Fatal(got)
}
if got := webView2Folder("", "", "magpie.exe"); got != "" {
t.Fatal(got)
}
}
func TestWebView2Failure(t *testing.T) {
for err, want := range map[error]bool{
errors.New("timed out after 1m0s waiting for the WebView2 controller; x"): true,
errors.New("error calling Webview2Loader: boom"): true,
errors.New("something else"): false,
nil: false,
} {
if got := webView2Failure(err); got != want {
t.Errorf("%v: %t", err, got)
}
}
}
func TestWebView2Try(t *testing.T) {
if webView2Try("") != 0 || webView2Try("2") != 2 || webView2Try("-1") != 0 || webView2Try("x") != 0 {
t.Fatal("try")
}
}
// the start waits for the folder to be let go, and gives up after max
func TestAwaitWebView2Folder(t *testing.T) {
n := 0
var slept time.Duration
free := func() bool { n++; return n > 3 }
sleep := func(d time.Duration) { slept += d }
if !awaitWebView2Folder(free, time.Second, 100*time.Millisecond, sleep) || slept != 300*time.Millisecond {
t.Fatal(n, slept)
}
slept = 0
if awaitWebView2Folder(func() bool { return false }, time.Second, 100*time.Millisecond, sleep) || slept != time.Second {
t.Fatal(slept)
}
}
-77
View File
@@ -3,18 +3,11 @@
package gui
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"time"
"unsafe"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
"golang.org/x/sys/windows"
)
@@ -57,73 +50,3 @@ func webView2Box(title, body string) int {
webView2BoxStyle)
return int(r)
}
// webView2Dir is the profile folder WebView2 will use.
func webView2Dir() string {
exe, _ := os.Executable()
return webView2Folder(appdir.WebView(), os.Getenv("AppData"), exe)
}
// webView2Free says whether no other process holds the profile folder.
// Chromium keeps EBWebView\lockfile open without sharing while its browser
// process runs, so opening it fails with a sharing violation until the
// previous magpie's msedgewebview2 has gone.
func webView2Free(dir string) bool {
if dir == "" {
return true
}
f, err := os.OpenFile(filepath.Join(dir, "EBWebView", "lockfile"), os.O_RDWR, 0)
if err != nil {
return !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED)
}
f.Close()
return true
}
// webView2Prepare runs before the first window. A start after a failed
// one backs off first; then it waits, up to 30s, for the previous
// process' WebView2 to let go of the profile folder.
func webView2Prepare() {
try := webView2Try(os.Getenv(webView2TryEnv))
if try > 0 {
log.Printf("magpie: WebView2 start %d of %d, after a failure", try+1, webView2Tries)
time.Sleep(webView2Backoff(try))
}
dir := webView2Dir()
start := time.Now()
if !awaitWebView2Folder(func() bool { return webView2Free(dir) }, 30*time.Second, 250*time.Millisecond, time.Sleep) {
log.Printf("magpie: WebView2 folder %s is still held by another process after 30s; going on", dir)
} else if d := time.Since(start); d > time.Second {
log.Printf("magpie: waited %s for WebView2 folder %s to be free", d.Round(100*time.Millisecond), dir)
}
}
// webView2Failed is Wails' ErrorHandler; Wails exits as soon as it
// returns. It logs the error with what is needed to read it, and for a
// WebView2 failure starts magpie again (up to webView2Tries starts), the
// last failure shown in a box with the log's place.
func webView2Failed(app *application.App, err error) {
dir := webView2Dir()
ver := "unknown"
if app != nil {
ver = fmt.Sprint(app.Env.Info().PlatformInfo["WebView2"])
}
log.Printf("magpie: %v (WebView2 runtime %q, profile folder %s, held by another process: %t)", err, ver, dir, !webView2Free(dir))
if !webView2Failure(err) {
return
}
try := webView2Try(os.Getenv(webView2TryEnv)) + 1
if try < webView2Tries {
log.Printf("magpie: starting again (start %d of %d)", try+1, webView2Tries)
if rerr := update.Respawn(fmt.Sprintf("%s=%d", webView2TryEnv, try)); rerr != nil {
log.Println("magpie: starting again:", rerr)
} else {
return
}
}
title, body := webView2FailedNotice(trayLang(settings.Load().Lang, systemLang), err.Error(), ver)
procMessageBoxW.Call(0,
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(body))),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(title))),
mbIconError|mbSetForeground|mbTopmost)
}
-44
View File
@@ -1,44 +0,0 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
// A skill made in the Library (josephBenchap on X): SKILL.md with valid
// front matter in the library's folder, given to the agents picked, and a
// name that clashes or isn't folder-safe is refused.
func TestCreateSkill(t *testing.T) {
h := sandbox(t)
ok(t)(CreateSkill("my-skill", "Does: a thing\nacross lines", []string{"claude", "codex"}))
b, err := os.ReadFile(filepath.Join(skillDir("my-skill"), "SKILL.md"))
if err != nil {
t.Fatal(err)
}
m := parseMeta(b)
if m.Name != "my-skill" || m.Description != "Does: a thing across lines" {
t.Errorf("front matter: %+v\\n%s", m, b)
}
for _, d := range []string{".claude/skills/my-skill", ".codex/skills/my-skill"} {
if _, err := os.Stat(filepath.Join(h, d, "SKILL.md")); err != nil {
t.Errorf("not given to %s: %v", d, err)
}
}
v, _ := Read(nil)
if len(v.Skills) != 1 || v.Skills[0].Name != "my-skill" {
t.Errorf("listed: %+v", v.Skills)
}
skill(t, filepath.Join(h, ".claude/skills/theirs"), "theirs", "An agent's own")
for _, c := range [][2]string{
{"My-Skill", "d"}, {"theirs", "d"}, {"../x", "d"}, {"a/b", "d"}, {"", "d"}, {"fine", " "}, {"fine", strings.Repeat("x", 1025)},
} {
if _, err := CreateSkill(c[0], c[1], nil); err == nil {
t.Errorf("%q / %.10q was taken", c[0], c[1])
}
}
if _, err := os.Lstat(skillDir("fine")); err == nil {
t.Error("a refused skill left a folder")
}
}
-47
View File
@@ -1731,53 +1731,6 @@ func (l *Library) offered(p *Probe, path string, shown bool) {
}
}
// CreateSkill makes a skill of the user's own in the library's folder: a
// SKILL.md with a name and description in its front matter, listed with no
// source and given to the agents like any other. The name can't be one the
// library has, one an agent has of its own, or a folder in the way.
func CreateSkill(name, description string, agents []string) (*Result, error) {
name = strings.TrimSpace(name)
if err := checkName("skill", name); err != nil {
return nil, err
}
description = strings.Join(strings.Fields(description), " ")
if description == "" {
return nil, errors.New("a skill needs a description: it is how an agent knows when to load it")
}
if len([]rune(description)) > 1024 {
return nil, errors.New("the description is over 1024 characters")
}
return change(func(l *Library) error {
same := func(n string) bool { return strings.EqualFold(n, name) }
if slices.ContainsFunc(l.Skills, func(s *Skill) bool { return same(s.Name) }) ||
slices.ContainsFunc(foundSkills(l), func(f FoundSkill) bool { return same(f.Name) }) {
return fmt.Errorf("there is a skill called %s already", name)
}
dir := skillDir(name)
if _, err := os.Lstat(dir); err == nil {
return fmt.Errorf("the library's folder already has a %s in it (%s)", name, dir)
} else if !errors.Is(err, fs.ErrNotExist) {
return err
}
head, err := yaml.Marshal(meta{Name: name, Description: description})
if err != nil {
return err
}
text := "---\n" + string(head) + "---\n\n# " + name + "\n\nWrite what the agent should do when this skill is used.\n"
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(text), 0o644); err != nil {
os.RemoveAll(dir)
return err
}
ag := slices.Clone(agents)
slices.Sort(ag)
l.Skills = append(l.Skills, &Skill{Name: name, Agents: slices.Compact(ag)})
return nil
})
}
// UpdateSkill fetches a skill from GitHub again, in place: the agents'
// links go on pointing at it. One changed here since it was fetched is
// an *EditedError unless replace is set, and then the changed version is
+7 -78
View File
@@ -3,7 +3,6 @@ package provider
import (
"cmp"
"net/url"
"slices"
"strings"
)
@@ -21,16 +20,7 @@ func openCodeRoot(base string) (root, catalogID string) {
if !openCodeHost(u.Hostname()) {
return "", ""
}
path := strings.TrimRight(u.Path, "/")
if r, ok := strings.CutSuffix(path, "/google/v1beta"); ok {
path = r
} else {
path = strings.TrimSuffix(path, "/v1")
for _, api := range []string{"/openai", "/anthropic", "/google"} {
path = strings.TrimSuffix(path, api)
}
}
switch path {
switch path := strings.TrimSuffix(strings.TrimRight(u.Path, "/"), "/v1"); path {
case "/zen/go", "/inference/go":
return u.Scheme + "://" + u.Host + path, "opencode-go"
case "/zen", "/inference":
@@ -73,54 +63,15 @@ func openCodeGateway(base string) string {
// root is: models/{model}:streamGenerateContent is asked under it. Zen's
// /zen/v1 relays it to the inference API's Google route, reading the key
// from x-goog-api-key; Go's /zen/go/v1 has no such route (404), so Go's
// Gemini models are asked at the inference API, where Go's docs give
// their endpoint: /inference/go/google/v1beta/models/{model} (since
// November 2026; before it /inference/go/v1, #2168).
// Gemini models are asked at the inference API's /inference/go/v1, where
// Go's docs give their endpoint (opencode.ai/v2/docs/console/go, #2168).
func openCodeGemini(root string) string {
if r, ok := strings.CutSuffix(root, "/zen/go"); ok {
return r + "/inference/go/google/v1beta"
}
if strings.HasSuffix(root, "/inference/go") {
return root + "/google/v1beta"
return r + "/inference/go/v1"
}
return root + "/v1"
}
// openCodeGoSplit is whether a Go URL names its API in the path, the way
// Go's docs give them since November 2026: …/inference/go/openai/v1 (chat
// and Responses), …/inference/go/anthropic (Messages) and
// …/inference/go/google/v1beta (Gemini).
func openCodeGoSplit(u string) bool {
pu, err := url.Parse(strings.TrimSpace(u))
if err != nil || openCodeGateway(u) != "go" {
return false
}
for _, seg := range strings.Split(pu.Path, "/") {
if seg == "openai" || seg == "anthropic" || seg == "google" {
return true
}
}
return false
}
// openCodeGoOld are the URLs the OpenCode Go preset gave before Go's docs
// named an endpoint per API; a provider of the preset saved with them is
// moved to where the docs have them (openCodeEndpoints).
var openCodeGoOld = map[string]bool{
"https://opencode.ai/zen/go/v1": true,
"https://opencode.ai/zen/go": true,
"https://opencode.ai/inference/go/v1": true,
"https://opencode.ai/inference/go": true,
}
// OpenCodeGo are the URLs Go's docs give each API (opencode.ai/docs/console/go,
// Endpoints).
const (
OpenCodeGoChat = "https://opencode.ai/inference/go/openai/v1"
OpenCodeGoAnthropic = "https://opencode.ai/inference/go/anthropic"
OpenCodeGoGemini = "https://opencode.ai/inference/go/google/v1beta"
)
// openCodeEndpoints fills in the APIs of OpenCode's gateway a provider at
// it was saved without. Zen and Go serve each model on one API of three,
// all under one root — chat completions and Responses at /v1, Anthropic's
@@ -145,31 +96,9 @@ func (p *Provider) openCodeEndpoints() {
if root == "" {
return
}
chat, anthropic := root+"/v1", root
if strings.HasSuffix(root, "/inference/go") && slices.ContainsFunc([]string{p.Chat, p.Responses, p.Anthropic, p.Gemini}, openCodeGoSplit) {
chat, anthropic = root+"/openai/v1", root+"/anthropic"
}
if p.Preset == "opencode-go" {
// the preset's own URLs, saved before Go's docs named one per API
for _, f := range []struct {
have *string
to string
}{{&p.Chat, OpenCodeGoChat}, {&p.Responses, OpenCodeGoChat}, {&p.Anthropic, OpenCodeGoAnthropic}} {
if openCodeGoOld[strings.ToLower(*f.have)] {
*f.have = f.to
}
}
if strings.EqualFold(p.Gemini, "https://opencode.ai/inference/go/v1") {
p.Gemini = OpenCodeGoGemini
}
root, catalogID = openCodeRoot(cmp.Or(p.Chat, p.Responses, p.Anthropic, p.Gemini))
if strings.HasSuffix(root, "/inference/go") {
chat, anthropic = root+"/openai/v1", root+"/anthropic"
}
}
p.Chat = cmp.Or(p.Chat, chat)
p.Responses = cmp.Or(p.Responses, chat)
p.Anthropic = cmp.Or(p.Anthropic, anthropic)
p.Chat = cmp.Or(p.Chat, root+"/v1")
p.Responses = cmp.Or(p.Responses, root+"/v1")
p.Anthropic = cmp.Or(p.Anthropic, root)
p.Gemini = cmp.Or(p.Gemini, openCodeGemini(root))
p.Catalog = cmp.Or(p.Catalog, catalogID)
}
+3 -10
View File
@@ -51,21 +51,14 @@ func TestOpenCodeEndpointsFilledIn(t *testing.T) {
apis map[string]Protocol // "" for none named
}{
{"go, chat alone", Provider{ID: "opencode-go", Chat: zg + "/v1"},
zg + "/v1", zg + "/v1", zg, igo + "/google/v1beta", "opencode-go",
zg + "/v1", zg + "/v1", zg, igo + "/v1", "opencode-go",
map[string]Protocol{"gpt-6-luna": Responses, "minimax-m2.7": Anthropic, "gemini-4-argon-contributor": Gemini, "glm-5.3": ""}},
{"go, anthropic alone with /v1", Provider{ID: "ocgo", Anthropic: zg + "/v1"},
zg + "/v1", zg + "/v1", zg, igo + "/google/v1beta", "opencode-go",
zg + "/v1", zg + "/v1", zg, igo + "/v1", "opencode-go",
map[string]Protocol{"gpt-6-luna": Responses}},
{"go at the inference API", Provider{ID: "ocgo", Chat: igo + "/v1"},
igo + "/v1", igo + "/v1", igo, igo + "/google/v1beta", "opencode-go",
igo + "/v1", igo + "/v1", igo, igo + "/v1", "opencode-go",
map[string]Protocol{"gemini-4-argon-contributor": Gemini, "glm-5.3": ""}},
{"go at the per-API URLs the docs give", Provider{ID: "ocgo", Chat: igo + "/openai/v1"},
igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go",
map[string]Protocol{"gemini-4-argon-contributor": Gemini, "gpt-6-luna": Responses}},
{"go, gemini url alone", Provider{ID: "ocgo", Gemini: igo + "/google/v1beta"},
igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", nil},
{"the go preset saved with its old URLs", Provider{ID: "opencode-go", Preset: "opencode-go", Chat: zg + "/v1", Responses: zg + "/v1", Anthropic: zg},
igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", nil},
{"zen saved with go's catalog", Provider{ID: "opencode-go", Catalog: "opencode-go", Chat: zen + "/v1"},
zen + "/v1", zen + "/v1", zen, zen + "/v1", "opencode-go",
map[string]Protocol{"claude-opus-5": Anthropic, "gemini-3-flash": Gemini, "minimax-m2.7": ""}},
+1 -1
View File
@@ -564,7 +564,7 @@ var presets = []PresetDef{
Chat: "https://api.gmi-serving.com/v1",
Website: "https://www.gmicloud.ai", KeysURL: "https://console.gmicloud.ai"},
{ID: "opencode-go", Name: "OpenCode Go", Icon: "opencode", Kind: KindRelay, Catalog: "opencode-go",
Chat: OpenCodeGoChat, Responses: OpenCodeGoChat, Anthropic: OpenCodeGoAnthropic,
Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go",
Note: "open coding models, $10/month",
Website: "https://opencode.ai/docs/go", KeysURL: "https://opencode.ai/auth"},
// Cline's plan for open models, at the Cline API with a Cline key: the
+12 -32
View File
@@ -15,10 +15,9 @@ import (
// the same account at different hours).
//
// - A card is shown for a Remote only when the Remote is enabled for a
// model of the provider the card is of (remoteCardWanted): the
// card's id is the provider path of one of those models' ids, or a
// parent of it, whole parts only (provider/model, as that remote lists
// them; relay/strata enabled does not tell relay/kiro).
// model of the provider the card is of (remoteCardWanted): the first
// part of the card's id is the first part of those models' ids
// (provider/model, as that remote lists them).
// - A card whose way names a magpie twice, or this one and another, is
// no card (catalog.Loops): it isn't kept (keepRemoteCards) nor told.
// - One account's copies are one card, the newest complete reading
@@ -36,37 +35,18 @@ func remoteCardWanted(p Provider) func(id string) bool {
if len(ms) == 0 {
return func(string) bool { return true }
}
ids := make([]string, len(ms))
for i, m := range ms {
ids[i] = m.ID
}
return cardWantedFor(ids)
}
// cardWantedFor is remoteCardWanted for the enabled model ids as the remote
// lists them: a model's provider path is its id less the last part
// ("relay/strata/m" is of relay/strata). A card is wanted when its id is
// such a path or one of its parents, whole parts only: relay/strata
// enabled tells relay/strata and relay, never relay/kiro or relay/strat.
// A model with no provider before its name leaves it unknown, so wanted.
func cardWantedFor(ids []string) func(id string) bool {
paths := map[string]bool{}
for _, mid := range ids {
i := strings.LastIndex(mid, "/")
if i <= 0 {
heads := map[string]bool{}
for _, m := range ms {
head, _, ok := strings.Cut(m.ID, "/")
if !ok {
return func(string) bool { return true }
}
path := mid[:i]
for {
paths[path] = true
j := strings.LastIndex(path, "/")
if j < 0 {
break
}
path = path[:j]
}
heads[head] = true
}
return func(id string) bool {
head, _, _ := strings.Cut(id, "/")
return heads[head]
}
return func(id string) bool { return paths[id] }
}
// withoutLoops is cards less those whose way comes back to this magpie.
-33
View File
@@ -668,36 +668,3 @@ func TestRemoteCardsFollowEnabledModelsAndDedupe(t *testing.T) {
}
}
}
// @748975219 on X (0.1.3771): with only relay/strata/model enabled, the
// cards of relay/kiro and relay/codex still passed, as only the first part
// of the card's id was compared.
func TestRemoteCardWantedByWholePath(t *testing.T) {
cases := []struct {
name string
ids []string
yes []string
no []string
}{
{"two levels", []string{"relay/strata/m"}, []string{"relay/strata", "relay"}, []string{"relay/kiro", "relay/codex", "kiro", "relay/strata/x"}},
{"three levels", []string{"a/b/c/m"}, []string{"a/b/c", "a/b", "a"}, []string{"a/b/d", "a/x", "a/b/c/d", "b"}},
{"not at a boundary", []string{"relay/kiro/m"}, []string{"relay/kiro"}, []string{"relay/kir", "relay/kiro2", "relay/kiroo", "rel"}},
{"prefix of the other way", []string{"relay/kir/m"}, []string{"relay/kir"}, []string{"relay/kiro"}},
{"several", []string{"relay/strata/m", "relay/kiro/n"}, []string{"relay/strata", "relay/kiro"}, []string{"relay/codex"}},
{"one level", []string{"kiro/m"}, []string{"kiro"}, []string{"codex", "kiro/x"}},
{"unknown provider", []string{"m"}, []string{"anything", "a/b"}, nil},
}
for _, c := range cases {
w := cardWantedFor(c.ids)
for _, id := range c.yes {
if !w(id) {
t.Errorf("%s: %v should tell %q", c.name, c.ids, id)
}
}
for _, id := range c.no {
if w(id) {
t.Errorf("%s: %v should not tell %q", c.name, c.ids, id)
}
}
}
}
-13
View File
@@ -216,16 +216,3 @@ func ReadBlocked(current string) *Blocked {
// ClearBlocked forgets the note: the version started after all.
func ClearBlocked() { os.Remove(blockedFile()) }
// Respawn starts this program again with the arguments it was started
// with and extra (NAME=value) added to its environment, detached. The new
// process waits for this one to exit, as a relaunch does (AwaitPredecessor).
func Respawn(extra ...string) error {
exe, err := os.Executable()
if err != nil {
return err
}
env := append(os.Environ(), "MAGPIE_REPLACES="+strconv.Itoa(os.Getpid()))
_, _, err = launch(exe, os.Args[1:], append(env, extra...))
return err
}