"},
+// or a config.toml itself. The key a provider table reads from an
+// environment variable (env_key) is the computer's own, not the link's, and
+// is never taken.
+func (c ccSwitchCfg) readCodex() (ccSwitchSettings, error) {
+ var s ccSwitchSettings
+ doc := map[string]any(c)
+ if text := c.str("config"); text != "" {
+ doc = nil
+ if err := toml.Unmarshal([]byte(text), &doc); err != nil {
+ return s, errorf("the ccswitch link's codex config is not TOML")
+ }
+ } else if c.obj("auth") != nil {
+ doc = nil
+ }
+ root := ccSwitchCfg(doc)
+ s.key = c.obj("auth").str("OPENAI_API_KEY")
+ s.models[0] = root.str("model")
+ id := root.str("model_provider")
+ var tbl ccSwitchCfg
+ if provs := root.obj("model_providers"); provs != nil {
+ if tbl = provs.obj(id); tbl == nil && len(provs) == 1 {
+ for _, v := range provs {
+ tbl, _ = v.(map[string]any)
+ }
+ }
+ }
+ if tbl != nil {
+ s.endpoint = tbl.str("base_url")
+ if s.key == "" {
+ s.key = tbl.str("experimental_bearer_token")
+ }
+ switch tbl.str("wire_api") {
+ case "chat":
+ s.format = "openai_chat"
+ case "responses":
+ s.format = "openai_responses"
+ }
+ if s.key == "" && tbl.str("env_key") != "" {
+ return s, errorf("the ccswitch link gives its key through the environment variable %s, which a link can't read: add the key yourself", tbl.str("env_key"))
+ }
+ }
+ return s, nil
+}
diff --git a/internal/provider/importccswitch_test.go b/internal/provider/importccswitch_test.go
new file mode 100644
index 000000000..b2e5dd397
--- /dev/null
+++ b/internal/provider/importccswitch_test.go
@@ -0,0 +1,167 @@
+package provider
+
+import (
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+// testdata/ccswitch_links.txt holds CC Switch's own example links, copied
+// as written from its repository (deplink.html and the site integration
+// guide at 3c76d3b), one per line.
+func ccSwitchLinks(t *testing.T) []string {
+ t.Helper()
+ b, err := os.ReadFile("testdata/ccswitch_links.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, l := range strings.Split(string(b), "\n") {
+ if strings.TrimSpace(l) != "" {
+ out = append(out, l)
+ }
+ }
+ return out
+}
+
+func TestCCSwitchOwnExamples(t *testing.T) {
+ type want struct {
+ Name, Chat, Responses, Anthropic, Gemini, Key string
+ Models []string
+ }
+ got := map[string]want{}
+ n := 0
+ for _, l := range ccSwitchLinks(t) {
+ p, err := ParseImport(l)
+ if !strings.Contains(l, "resource=provider") {
+ // prompts, MCP servers and skills are not providers
+ if err == nil || !strings.Contains(err.Error(), "providers") {
+ t.Errorf("%.60s: %v", l, err)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("%.90s: %v", l, err)
+ continue
+ }
+ n++
+ if p.ID != "example-ai" && p.ID != "example-gemini" {
+ t.Errorf("%.90s: id %q", l, p.ID)
+ }
+ app := l[strings.Index(l, "app=")+4:]
+ app = app[:strings.IndexByte(app, '&')]
+ got[app+"/"+map[bool]string{true: "config", false: "params"}[strings.Contains(l, "config=")]+"/"+p.Name+p.Key+strings.Join(p.Models, ",")] = want{p.Name, p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Key, p.Models}
+ }
+ if n != 11 {
+ t.Fatalf("%d provider links in the examples", n)
+ }
+ for _, c := range []struct {
+ key string
+ w want
+ }{
+ // endpoint, apiKey: claude's address is Anthropic's
+ {"claude/params/Example AIsk-test-key123", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123"}},
+ // the config's env, with its three tiers
+ {"claude/config/Example AIsk-test-key123example-chat,example-fast,example-pro", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123", Models: []string{"example-chat", "example-fast", "example-pro"}}},
+ // the key in the URL, the address in the config
+ {"claude/config/Example AIsk-test-key123", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123"}},
+ // codex: config.toml's provider table, wire_api responses
+ {"codex/config/Example AIsk-test-key123example-coder", want{Name: "Example AI", Responses: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-coder"}}},
+ {"codex/params/Example AIsk-test-key123", want{Name: "Example AI", Responses: "https://api.example.com/v1", Key: "sk-test-key123"}},
+ {"gemini/config/Example GeminiAIzaSy-test-key123", want{Name: "Example Gemini", Gemini: "https://api.example.com", Key: "AIzaSy-test-key123"}},
+ // apiFormat names the API an app of any kind speaks
+ {"opencode/params/Example AIsk-test-key123example-chat", want{Name: "Example AI", Anthropic: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-chat"}}},
+ {"pi/params/Example AIsk-test-key123example-chat", want{Name: "Example AI", Chat: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-chat"}}},
+ } {
+ if g, ok := got[c.key]; !ok {
+ t.Errorf("no example gave %q; have %v", c.key, got)
+ } else if !reflect.DeepEqual(g, c.w) {
+ t.Errorf("%s:\n got %+v\nwant %+v", c.key, g, c.w)
+ }
+ }
+}
+
+func TestCCSwitchIconAndUsageDropped(t *testing.T) {
+ for _, l := range ccSwitchLinks(t) {
+ if !strings.Contains(l, "iconUrl=") {
+ continue
+ }
+ p, err := ParseImport(l)
+ if err != nil || p.IconURL == "" {
+ t.Fatalf("iconUrl: %q, %v", p.IconURL, err)
+ }
+ }
+ // a usage script (CC Switch's balance query) is code: never taken
+ p, err := ParseImport("ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example&usageScript=KHsKfSk%3D&usageEnabled=true&usageBaseUrl=https%3A%2F%2Fevil.example")
+ if err != nil || p.BalanceURL != "" {
+ t.Fatalf("%+v %v", p, err)
+ }
+}
+
+func TestCCSwitchRefused(t *testing.T) {
+ const base = "ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example"
+ for name, c := range map[string]struct{ link, why string }{
+ "other version": {strings.Replace(base, "//v1/", "//v2/", 1), "v1"},
+ "other path": {strings.Replace(base, "/import?", "/export?", 1), "/import"},
+ "no resource": {strings.Replace(base, "resource=provider&", "", 1), "resource"},
+ "unknown app": {strings.Replace(base, "app=claude", "app=nope", 1), "app"},
+ "no name": {strings.Replace(base, "name=x&", "", 1), "name"},
+ "plain http": {strings.Replace(base, "https", "http", 1), "https"},
+ "javascript": {strings.Replace(base, "https%3A%2F%2Fa.example", "javascript%3Aalert(1)", 1), "base URL"},
+ "file": {strings.Replace(base, "https%3A%2F%2Fa.example", "file%3A%2F%2F%2Fetc%2Fpasswd", 1), "base URL"},
+ "bad format": {base + "&apiFormat=grpc", "apiFormat"},
+ "remote config": {base + "&configUrl=https%3A%2F%2Fa.example%2Fc.json", "configUrl"},
+ "config not base64": {base + "&config=%25%25%25", "base64"},
+ "config not json": {base + "&config=bm90IGpzb24", "json"},
+ "config huge": {base + "&config=" + strings.Repeat("A", 300<<10), "large"},
+ "claude no env": {base + "&config=e30", "env"},
+ "key with newline": {base + "&apiKey=sk%0Aevil", "key"},
+ "no address": {"ccswitch://v1/import?resource=provider&app=claude&name=x", "base URL"},
+ "codex env_key": {"ccswitch://v1/import?resource=provider&app=codex&name=x&config=" +
+ b64(`{"config":"model_provider=\"p\"\n[model_providers.p]\nbase_url=\"https://a.example/v1\"\nenv_key=\"HOME_SECRET\""}`), "HOME_SECRET"},
+ "name only a symbol": {"ccswitch://v1/import?resource=provider&app=claude&name=%2A%2A&endpoint=https%3A%2F%2Fa.example", "id"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ p, err := ParseImport(c.link)
+ if err == nil {
+ t.Fatalf("accepted: %+v", p)
+ }
+ if !strings.Contains(err.Error(), c.why) {
+ t.Fatalf("%q does not say %q", err, c.why)
+ }
+ })
+ }
+ if _, err := ParseImport("ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example&homepage=javascript%3Aalert(1)"); err != nil {
+ t.Fatalf("a bad homepage turned the link away: %v", err)
+ }
+}
+
+// a ccswitch link is as safe as a magpie one: the balance host rule and
+// the id rules are the shared ones
+func TestCCSwitchNamedAsSubscription(t *testing.T) {
+ p, err := ParseImport("CCSWITCH://V1/import?resource=provider&app=claude&name=claude&endpoint=https%3A%2F%2Fa.example")
+ if err != nil || p.ID == "claude" {
+ t.Fatalf("%+v %v", p, err)
+ }
+}
+
+func b64(s string) string {
+ const a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
+ var out []byte
+ for i := 0; i < len(s); i += 3 {
+ var v uint
+ n := 0
+ for j := 0; j < 3; j++ {
+ v <<= 8
+ if i+j < len(s) {
+ v |= uint(s[i+j])
+ n++
+ }
+ }
+ for j := 0; j <= n; j++ {
+ out = append(out, a[(v>>(18-6*uint(j)))&63])
+ }
+ }
+ return string(out)
+}
diff --git a/internal/provider/importurl.go b/internal/provider/importurl.go
index c306257ec..a92585c9a 100644
--- a/internal/provider/importurl.go
+++ b/internal/provider/importurl.go
@@ -53,6 +53,13 @@ const Scheme = "magpie"
// ParseImport reads an import link into the provider it describes.
func ParseImport(link string) (Provider, error) {
u, err := url.Parse(strings.TrimSpace(link))
+ if err == nil && strings.EqualFold(u.Scheme, CCSwitchScheme) {
+ q, err := ccSwitchQuery(u)
+ if err != nil {
+ return Provider{}, err
+ }
+ return importFromQuery(q)
+ }
if err != nil || !strings.EqualFold(u.Scheme, Scheme) {
return Provider{}, errors.New("not a magpie:// link")
}
@@ -63,7 +70,14 @@ func ParseImport(link string) (Provider, error) {
if action != "import" {
return Provider{}, errorf("magpie://%s is not something magpie knows; links start magpie://import?", action)
}
- q := u.Query()
+ return importFromQuery(u.Query())
+}
+
+// importFromQuery is ParseImport after the link's shape is known: q holds
+// the parameters in the list above, from a magpie:// link or translated from
+// a ccswitch:// one (ccSwitchQuery).
+func importFromQuery(q url.Values) (Provider, error) {
+ var err error
get := func(k string) string { return strings.TrimSpace(q.Get(k)) }
var p Provider
diff --git a/internal/provider/key_balance_own.go b/internal/provider/key_balance_own.go
index a8d94fcd5..e3d5a9e4d 100644
--- a/internal/provider/key_balance_own.go
+++ b/internal/provider/key_balance_own.go
@@ -16,8 +16,9 @@ package provider
// learned (internal/fx, fetched behind the page and cached), and while it
// has never learned one what is left is unknown, never counted at a guess.
// It may refill (the same user: $10 a month from the 1st): at each refill,
-// at midnight local time on a day of the month or of the week, the amount
-// typed is whole again and the spend counted from then.
+// at midnight local time on a day of the month or of the week, or every
+// midnight (Kelen_Yc on X: a relay key with a daily allowance), the
+// amount typed is whole again and the spend counted from then.
// It may have credit that expires on top of it (the same user: some
// vendors split a balance into money that stays and credit good until a
@@ -118,7 +119,7 @@ func (b OwnBalance) Amount() (float64, string) {
// Refill is when a balance typed is whole again: at midnight, local time,
// on Day of each month (1–31, a month without that day on its last) or of
-// each week (1 Monday to 7 Sunday).
+// each week (1 Monday to 7 Sunday), or each day (Day 0).
type Refill struct {
Every string `json:"every"`
Day int `json:"day"`
@@ -128,12 +129,16 @@ type Refill struct {
const (
RefillMonth = "month"
RefillWeek = "week"
+ RefillDay = "day"
)
// Last is the last refill at or before now, in now's location.
func (r Refill) Last(now time.Time) time.Time {
y, m, d := now.Date()
loc := now.Location()
+ if r.Every == RefillDay {
+ return time.Date(y, m, d, 0, 0, 0, 0, loc)
+ }
if r.Every == RefillWeek {
iso := (int(now.Weekday())+6)%7 + 1
return time.Date(y, m, d-(iso-r.Day+7)%7, 0, 0, 0, 0, loc)
@@ -149,6 +154,9 @@ func (r Refill) Last(now time.Time) time.Time {
func (r Refill) Next(now time.Time) time.Time {
l := r.Last(now)
y, m, d := l.Date()
+ if r.Every == RefillDay {
+ return time.Date(y, m, d+1, 0, 0, 0, 0, l.Location())
+ }
if r.Every == RefillWeek {
return time.Date(y, m, d+7, 0, 0, 0, 0, l.Location())
}
@@ -167,14 +175,18 @@ func (r Refill) check() error {
switch {
case r.Every == RefillMonth && r.Day >= 1 && r.Day <= 31:
case r.Every == RefillWeek && r.Day >= 1 && r.Day <= 7:
+ case r.Every == RefillDay && r.Day == 0:
default:
- return fmt.Errorf("a balance refills each month on a day from 1 to 31, or each week on a day from 1 (Monday) to 7 (Sunday), not %s %d", r.Every, r.Day)
+ return fmt.Errorf("a balance refills each month on a day from 1 to 31, each week on a day from 1 (Monday) to 7 (Sunday), or each day (day 0), not %s %d", r.Every, r.Day)
}
return nil
}
-// String is r as the CLI takes and shows it: monthly:1, weekly:mon.
+// String is r as the CLI takes and shows it: monthly:1, weekly:mon, daily.
func (r Refill) String() string {
+ if r.Every == RefillDay {
+ return "daily"
+ }
if r.Every == RefillWeek {
return "weekly:" + strings.ToLower(time.Weekday(r.Day % 7).String()[:3])
}
@@ -746,8 +758,8 @@ func ParseOwnBalance(amount string) (*OwnBalance, error) {
}
// ParseRefill reads a refill as the CLI takes it: monthly (on the 1st),
-// monthly:15, weekly (on Monday), weekly:fri or weekly:5; off or never
-// for none (nil).
+// monthly:15, weekly (on Monday), weekly:fri or weekly:5, daily (each
+// midnight); off or never for none (nil).
func ParseRefill(s string) (*Refill, error) {
a := strings.ToLower(strings.TrimSpace(s))
switch a {
@@ -755,7 +767,7 @@ func ParseRefill(s string) (*Refill, error) {
return nil, nil
}
every, day, _ := strings.Cut(a, ":")
- bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun] or off, not %q", s)
+ bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun], daily or off, not %q", s)
var r Refill
switch every {
case "monthly", "month", "m":
@@ -767,6 +779,11 @@ func ParseRefill(s string) (*Refill, error) {
}
r.Day = n
}
+ case "daily", "day", "d":
+ if day != "" {
+ return nil, bad
+ }
+ r = Refill{Every: RefillDay}
case "weekly", "week", "w":
r = Refill{Every: RefillWeek, Day: 1}
if day != "" {
diff --git a/internal/provider/key_balance_own_test.go b/internal/provider/key_balance_own_test.go
index fd40c5a84..c02df9c0d 100644
--- a/internal/provider/key_balance_own_test.go
+++ b/internal/provider/key_balance_own_test.go
@@ -344,7 +344,7 @@ func TestTypedBalanceRefills(t *testing.T) {
t.Fatalf("no refill: %+v", e)
}
// refused: a refill that isn't one; one for a key with no balance
- for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}} {
+ for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}, {RefillDay, 1}} {
if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), &bad); err == nil {
t.Errorf("%+v taken", bad)
}
@@ -357,6 +357,47 @@ func TestTypedBalanceRefills(t *testing.T) {
}
}
+// A balance that refills each day (Kelen_Yc on X: a relay key with a
+// daily allowance) is whole again at local midnight, not UTC's: held in
+// UTC+14 and UTC-11, where the local day and UTC's differ, the spend is
+// counted from the midnight just past and the next is the one after.
+func TestTypedBalanceRefillsDaily(t *testing.T) {
+ probeSandbox(t)
+ probeLocal = false
+ asked := spentStub(t, map[string]float64{keyID("sk-d"): 2})
+ if err := Save(Provider{ID: "daily", Name: "Daily", Chat: "http://127.0.0.1:1/v1", Key: "sk-d"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, zone := range []string{"Pacific/Kiritimati", "Pacific/Pago_Pago", "UTC"} {
+ loc, err := time.LoadLocation(zone)
+ if err != nil {
+ t.Fatal(err)
+ }
+ typed := time.Date(2026, 11, 12, 9, 0, 0, 0, loc)
+ clockStub(t, typed)
+ if err := SetKeyOwnBalance("daily", keyID("sk-d"), &OwnBalance{USD: 5, Refill: &Refill{Every: RefillDay}}); err != nil {
+ t.Fatal(err)
+ }
+ // the same local day, a minute before midnight: from when typed
+ clockStub(t, time.Date(2026, 11, 12, 23, 59, 0, 0, loc))
+ p, _ := Find("daily")
+ e, _ := p.OwnBalanceEstimate(keyID("sk-d"))
+ if !e.From.Equal(typed) || *e.Left != 3 || !e.Next.Equal(time.Date(2026, 11, 13, 0, 0, 0, 0, loc)) {
+ t.Fatalf("%s before midnight: from %v next %v left %v", zone, e.From, e.Next, *e.Left)
+ }
+ // a minute past local midnight: whole again, counted from then
+ clockStub(t, time.Date(2026, 11, 13, 0, 1, 0, 0, loc))
+ q := ownCards(t)["daily|"]
+ mid := time.Date(2026, 11, 13, 0, 0, 0, 0, loc)
+ if !q.Estimate.From.Equal(mid) || !asked[keyID("sk-d")].Equal(mid) || q.Balance != "≈$3.00" {
+ t.Fatalf("%s after midnight: %+v from %v, asked from %v", zone, q, q.Estimate.From, asked[keyID("sk-d")])
+ }
+ if !q.Estimate.Next.Equal(time.Date(2026, 11, 14, 0, 0, 0, 0, loc)) {
+ t.Errorf("%s next refill %v", zone, q.Estimate.Next)
+ }
+ }
+}
+
// When each refill falls: on the day, at local midnight; a month without
// the day refills on its last; a week from Monday (1) to Sunday (7).
func TestRefillDays(t *testing.T) {
@@ -381,6 +422,12 @@ func TestRefillDays(t *testing.T) {
{Refill{RefillWeek, 1}, at(2026, 11, 8, 10), at(2026, 11, 2, 0), at(2026, 11, 9, 0)},
{Refill{RefillWeek, 7}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 15, 0)},
{Refill{RefillWeek, 5}, at(2026, 11, 8, 10), at(2026, 11, 6, 0), at(2026, 11, 13, 0)},
+ // each day (Kelen_Yc on X): the midnight before, the one after,
+ // across a month's and a year's end
+ {Refill{RefillDay, 0}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 9, 0)},
+ {Refill{RefillDay, 0}, at(2026, 11, 8, 0), at(2026, 11, 8, 0), at(2026, 11, 9, 0)},
+ {Refill{RefillDay, 0}, at(2026, 11, 30, 23), at(2026, 11, 30, 0), at(2026, 12, 1, 0)},
+ {Refill{RefillDay, 0}, at(2026, 12, 31, 23), at(2026, 12, 31, 0), at(2027, 1, 1, 0)},
} {
if l, n := c.r.Last(c.now), c.r.Next(c.now); !l.Equal(c.last) || !n.Equal(c.next) {
t.Errorf("%+v at %v: last %v next %v, want %v and %v", c.r, c.now, l, n, c.last, c.next)
@@ -416,7 +463,7 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
}
}
for in, want := range map[string]Refill{"monthly": {RefillMonth, 1}, "monthly:15": {RefillMonth, 15}, "weekly": {RefillWeek, 1},
- "weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}} {
+ "weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}, "daily": {RefillDay, 0}, "Day": {RefillDay, 0}} {
if r, err := ParseRefill(in); err != nil || r == nil || *r != want {
t.Errorf("%q: %+v %v, want %+v", in, r, err, want)
}
@@ -427,15 +474,18 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
if r, err := ParseRefill("off"); err != nil || r != nil {
t.Errorf("off: %+v %v", r, err)
}
- for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help"} {
+ for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help", "daily:1"} {
if _, err := ParseRefill(in); err == nil {
t.Errorf("%q taken", in)
}
}
- n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}})
+ n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}, "b": {USD: 5, Refill: &Refill{RefillDay, 0}}})
if n["a"].USD != 5 || n["a"].Refill != nil {
t.Errorf("a refill that isn't one, written by hand: %+v", n)
}
+ if n["b"].Refill == nil || *n["b"].Refill != (Refill{RefillDay, 0}) {
+ t.Errorf("a daily refill was dropped as read back: %+v", n["b"])
+ }
}
// spendAt stubs usage.KeySpent with calls at given times: what the key
diff --git a/internal/provider/testdata/ccswitch_links.txt b/internal/provider/testdata/ccswitch_links.txt
new file mode 100644
index 000000000..81a88afbc
--- /dev/null
+++ b/internal/provider/testdata/ccswitch_links.txt
@@ -0,0 +1,14 @@
+ccswitch://v1/import?resource=mcp&apps=claude%2Ccodex&config=eyJtY3BTZXJ2ZXJzIjp7ImNvbnRleHQ3Ijp7ImNvbW1hbmQiOiJucHgiLCJhcmdzIjpbIi15IiwiQHVwc3Rhc2gvY29udGV4dDctbWNwIl0sImVudiI6e319LCJzZXF1ZW50aWFsLXRoaW5raW5nIjp7ImNvbW1hbmQiOiJucHgiLCJhcmdzIjpbIi15IiwiQG1vZGVsY29udGV4dHByb3RvY29sL3NlcnZlci1zZXF1ZW50aWFsLXRoaW5raW5nIl0sImVudiI6e319fX0%3D
+ccswitch://v1/import?resource=prompt&app=claude&name=%E4%BB%A3%E7%A0%81%E5%AE%A1%E6%9F%A5%E4%B8%93%E5%AE%B6&content=IyDku6PnoIHlrqHmn6XkuJPlrrYKCuS9oOaYr%2BS4gOS9jeaciee7j%2BmqjOeahOS7o%2BeggeWuoeafpeWRmOOAguWuoeafpeS7o%2BeggeaXtu%2B8jOWFiOaMh%2BWHuuS8muWvvOiHtOmUmeivr%2BeahOmXrumimO%2B8jOWGjee7meWHuuS%2FruaUueW7uuiuruOAgg%3D%3D&description=%E4%B8%93%E6%B3%A8%E4%BB%A3%E7%A0%81%E8%B4%A8%E9%87%8F
+ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&apiKey=sk-test-key123&configFormat=json&config=eyJlbnYiOnsiQU5USFJPUElDX0JBU0VfVVJMIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJBUElfVElNRU9VVF9NUyI6IjYwMDAwMCJ9fQ%3D%3D
+ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&configFormat=json&config=eyJlbnYiOnsiQU5USFJPUElDX0FVVEhfVE9LRU4iOiJzay10ZXN0LWtleTEyMyIsIkFOVEhST1BJQ19CQVNFX1VSTCI6Imh0dHBzOi8vYXBpLmV4YW1wbGUuY29tIiwiQU5USFJPUElDX01PREVMIjoiZXhhbXBsZS1jaGF0IiwiQU5USFJPUElDX0RFRkFVTFRfSEFJS1VfTU9ERUwiOiJleGFtcGxlLWZhc3QiLCJBTlRIUk9QSUNfREVGQVVMVF9TT05ORVRfTU9ERUwiOiJleGFtcGxlLWNoYXQiLCJBTlRIUk9QSUNfREVGQVVMVF9PUFVTX01PREVMIjoiZXhhbXBsZS1wcm8ifX0%3D
+ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&iconUrl=https%3A%2F%2Fraw.githubusercontent.com%2Ffarion1231%2Fcc-switch%2Fmain%2Fsrc-tauri%2Ficons%2F128x128.png
+ccswitch://v1/import?resource=provider&app=claude&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fS91c2VyL2JhbGFuY2UiLAogICAgbWV0aG9kOiAiR0VUIiwKICAgIGhlYWRlcnM6IHsKICAgICAgIkF1dGhvcml6YXRpb24iOiAiQmVhcmVyIHt7YXBpS2V5fX0iCiAgICB9CiAgfSwKICBleHRyYWN0b3I6IGZ1bmN0aW9uIChyZXNwb25zZSkgewogICAgaWYgKHJlc3BvbnNlLmVycm9yKSB7CiAgICAgIHJldHVybiB7IGlzVmFsaWQ6IGZhbHNlLCBpbnZhbGlkTWVzc2FnZTogU3RyaW5nKHJlc3BvbnNlLmVycm9yLm1lc3NhZ2UgfHwgcmVzcG9uc2UuZXJyb3IpIH07CiAgICB9CiAgICByZXR1cm4gewogICAgICByZW1haW5pbmc6IE51bWJlcihyZXNwb25zZS5iYWxhbmNlKSwKICAgICAgdW5pdDogIlVTRCIKICAgIH07CiAgfQp9KQ
+ccswitch://v1/import?resource=provider&app=claude&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fSIucmVwbGFjZSgvXC8rJC8sICIiKS5yZXBsYWNlKC9cL3YxJC8sICIiKSArICIvdjEvdXNhZ2UiLAogICAgbWV0aG9kOiAiR0VUIiwKICAgIGhlYWRlcnM6IHsKICAgICAgIkF1dGhvcml6YXRpb24iOiAiQmVhcmVyIHt7YXBpS2V5fX0iLAogICAgICAiVXNlci1BZ2VudCI6ICJjYy1zd2l0Y2gvMS4wIgogICAgfQogIH0sCiAgZXh0cmFjdG9yOiBmdW5jdGlvbiAocmVzcG9uc2UpIHsKICAgIHZhciBxdW90YSA9IHJlc3BvbnNlLnF1b3RhIHx8IHt9OwogICAgdmFyIHJlc3VsdCA9IHsKICAgICAgaXNWYWxpZDogcmVzcG9uc2UuaXNWYWxpZCAhPT0gZmFsc2UsCiAgICAgIHVuaXQ6IHJlc3BvbnNlLnVuaXQgfHwgcXVvdGEudW5pdCB8fCAiVVNEIgogICAgfTsKICAgIGlmICh0eXBlb2YgcmVzcG9uc2UucGxhbk5hbWUgPT09ICJzdHJpbmciKSByZXN1bHQucGxhbk5hbWUgPSByZXNwb25zZS5wbGFuTmFtZTsKICAgIGlmICh0eXBlb2YgcmVzcG9uc2UucmVtYWluaW5nID09PSAibnVtYmVyIiAmJiByZXNwb25zZS5yZW1haW5pbmcgPj0gMCkgewogICAgICByZXN1bHQucmVtYWluaW5nID0gcmVzcG9uc2UucmVtYWluaW5nOwogICAgfQogICAgaWYgKHF1b3RhLmxpbWl0ID4gMCkgewogICAgICByZXN1bHQudXNlZCA9IHF1b3RhLnVzZWQ7CiAgICAgIHJlc3VsdC50b3RhbCA9IHF1b3RhLmxpbWl0OwogICAgfQogICAgaWYgKCFyZXN1bHQuaXNWYWxpZCkgewogICAgICByZXN1bHQuaW52YWxpZE1lc3NhZ2UgPSByZXNwb25zZS5zdGF0dXMKICAgICAgICA%2FIFN0cmluZyhyZXNwb25zZS5zdGF0dXMpCiAgICAgICAgOiAi5p%2Bl6K%2Bi5aSx6LSlIjsKICAgIH0KICAgIHJldHVybiByZXN1bHQ7CiAgfSwKfSk%3D&usageAutoInterval=30
+ccswitch://v1/import?resource=provider&app=codex&name=Example%20AI&configFormat=json&config=eyJhdXRoIjp7Ik9QRU5BSV9BUElfS0VZIjoic2stdGVzdC1rZXkxMjMifSwiY29uZmlnIjoibW9kZWxfcHJvdmlkZXIgPSBcImV4YW1wbGVcIlxubW9kZWwgPSBcImV4YW1wbGUtY29kZXJcIlxuXG5bbW9kZWxfcHJvdmlkZXJzLmV4YW1wbGVdXG5uYW1lID0gXCJFeGFtcGxlIEFJXCJcbmJhc2VfdXJsID0gXCJodHRwczovL2FwaS5leGFtcGxlLmNvbS92MVwiXG53aXJlX2FwaSA9IFwicmVzcG9uc2VzXCIifQ%3D%3D
+ccswitch://v1/import?resource=provider&app=codex&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fS9hcGkvdXNlci9zZWxmIiwKICAgIG1ldGhvZDogIkdFVCIsCiAgICBoZWFkZXJzOiB7CiAgICAgICJBdXRob3JpemF0aW9uIjogIkJlYXJlciB7e2FjY2Vzc1Rva2VufX0iLAogICAgICAiTmV3LUFwaS1Vc2VyIjogInt7dXNlcklkfX0iCiAgICB9CiAgfSwKICBleHRyYWN0b3I6IGZ1bmN0aW9uIChyZXNwb25zZSkgewogICAgaWYgKHJlc3BvbnNlLnN1Y2Nlc3MgJiYgcmVzcG9uc2UuZGF0YSkgewogICAgICByZXR1cm4gewogICAgICAgIHBsYW5OYW1lOiByZXNwb25zZS5kYXRhLmdyb3VwLAogICAgICAgIHJlbWFpbmluZzogcmVzcG9uc2UuZGF0YS5xdW90YSAvIDUwMDAwMCwKICAgICAgICB1c2VkOiByZXNwb25zZS5kYXRhLnVzZWRfcXVvdGEgLyA1MDAwMDAsCiAgICAgICAgdW5pdDogIlVTRCIKICAgICAgfTsKICAgIH0KICAgIHJldHVybiB7IGlzVmFsaWQ6IGZhbHNlLCBpbnZhbGlkTWVzc2FnZTogU3RyaW5nKHJlc3BvbnNlLm1lc3NhZ2UgfHwgIuafpeivouWksei0pSIpIH07CiAgfQp9KQ&usageBaseUrl=https%3A%2F%2Fapi.example.com&usageAccessToken=test-access-token&usageUserId=1&usageAutoInterval=30
+ccswitch://v1/import?resource=provider&app=gemini&name=Example%20Gemini&configFormat=json&config=eyJHRU1JTklfQVBJX0tFWSI6IkFJemFTeS10ZXN0LWtleTEyMyIsIkdPT0dMRV9HRU1JTklfQkFTRV9VUkwiOiJodHRwczovL2FwaS5leGFtcGxlLmNvbSJ9
+ccswitch://v1/import?resource=provider&app=opencode&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&apiFormat=anthropic&model=example-chat
+ccswitch://v1/import?resource=provider&app=pi&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&apiFormat=openai_chat&model=example-chat
+ccswitch://v1/import?resource=skill&repo=example%2Fclaude-skills&branch=main
+ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-xxxx
diff --git a/internal/uninstall/system_linux.go b/internal/uninstall/system_linux.go
index 13c45d933..3b5185afa 100644
--- a/internal/uninstall/system_linux.go
+++ b/internal/uninstall/system_linux.go
@@ -1,6 +1,7 @@
package uninstall
import (
+ "errors"
"os"
"path/filepath"
"strings"
@@ -21,26 +22,33 @@ func dataHome() string {
// unregisterScheme takes out the desktop entry the app made for magpie://
// links while it runs exe, or an exe that is gone, and its icon with it.
func unregisterScheme(exe string) error {
- entry := filepath.Join(dataHome(), "applications", "magpie.desktop")
+ _, err := removeEntry("magpie-ccswitch.desktop", exe)
+ gone, err2 := removeEntry("magpie.desktop", exe)
+ if gone {
+ _ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png"))
+ }
+ return errors.Join(err, err2)
+}
+
+// removeEntry takes out one of the app's desktop entries while it runs exe,
+// or an exe that is gone.
+func removeEntry(name, exe string) (bool, error) {
+ entry := filepath.Join(dataHome(), "applications", name)
b, err := os.ReadFile(entry)
if err != nil {
- return nil
+ return false, nil
}
for _, l := range strings.Split(string(b), "\n") {
if run, ok := strings.CutPrefix(l, "Exec="); ok {
run = strings.TrimSuffix(run, " %u")
if run != exe {
if _, err := os.Stat(run); err == nil {
- return nil // another magpie's
+ return false, nil // another magpie's
}
}
}
}
- if err := os.Remove(entry); err != nil {
- return err
- }
- _ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png"))
- return nil
+ return true, os.Remove(entry)
}
// webData is WebKitGTK's folder for the app's pages (named after the
diff --git a/internal/uninstall/system_windows.go b/internal/uninstall/system_windows.go
index b20bea032..795dc3679 100644
--- a/internal/uninstall/system_windows.go
+++ b/internal/uninstall/system_windows.go
@@ -1,6 +1,7 @@
package uninstall
import (
+ "errors"
"os"
"path/filepath"
"strings"
@@ -12,10 +13,14 @@ import (
const schemeKey = `Software\Classes\magpie`
-// unregisterScheme takes out the magpie:// handler the app registered
-// while it opens exe, or an exe that is gone.
+// unregisterScheme takes out the magpie:// and ccswitch:// handlers the app
+// registered while they open exe, or an exe that is gone.
func unregisterScheme(exe string) error {
- k, err := registry.OpenKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.QUERY_VALUE)
+ return errors.Join(removeSchemeKey(schemeKey, exe), removeSchemeKey(`Software\Classes\ccswitch`, exe))
+}
+
+func removeSchemeKey(key, exe string) error {
+ k, err := registry.OpenKey(registry.CURRENT_USER, key+`\shell\open\command`, registry.QUERY_VALUE)
if err != nil {
return nil
}
@@ -27,7 +32,7 @@ func unregisterScheme(exe string) error {
}
}
for _, sub := range []string{`\shell\open\command`, `\shell\open`, `\shell`, `\DefaultIcon`, ``} {
- if err := registry.DeleteKey(registry.CURRENT_USER, schemeKey+sub); err != nil && err != registry.ErrNotExist {
+ if err := registry.DeleteKey(registry.CURRENT_USER, key+sub); err != nil && err != registry.ErrNotExist {
return err
}
}
diff --git a/internal/usage/heat_digest_disk.go b/internal/usage/heat_digest_disk.go
new file mode 100644
index 000000000..c8ceb0aa7
--- /dev/null
+++ b/internal/usage/heat_digest_disk.go
@@ -0,0 +1,195 @@
+package usage
+
+import (
+ "bytes"
+ "cmp"
+ "crypto/sha256"
+ "encoding/binary"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "sync"
+
+ "github.com/yetone/magpie/internal/sessions"
+)
+
+// A session file's chunk is named in the heatmap's key by a digest of its
+// rows (sourceDigest), and each start hashed every chunk's rows again to
+// make them: ~0.15 s of CPU on a real history, and every chunk unpacked
+// for it (#2278). A chunk's serial names its file as read under one root
+// and meta (sourceSerial), the same in every run, so the digests are kept
+// on disk by serial, under the code that makes the rows
+// (requestDiskBinary): another build's rows are hashed again.
+
+// sourceDigestsDisk is what was read of heat-digests.bin. Under
+// sourceDigests' lock.
+var sourceDigestsDisk struct {
+ path string // where kept was read from
+ kept digestList // as read: no map of 17k entries beside sourceDigests'
+ dirty bool // a digest was made that isn't on disk
+}
+
+// sourceDigestsHashed counts the chunks sourceDigest hashed, for tests.
+var sourceDigestsHashed int
+
+func sourceDigestsPath() string {
+ return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-digests.bin")
+}
+
+const sourceDigestsMagic = "magpie-heat-digests-2\n"
+
+// digestList is serials and their digests, each 8+32 bytes, in the
+// serials' order.
+type digestList []byte
+
+const digestLen = 8 + sha256.Size
+
+func (l digestList) len() int { return len(l) / digestLen }
+
+func (l digestList) at(i int) (uint64, []byte) {
+ e := l[i*digestLen : (i+1)*digestLen]
+ return binary.LittleEndian.Uint64(e), e[8:]
+}
+
+func (l digestList) get(serial uint64) (sum [sha256.Size]byte, ok bool) {
+ i := sort.Search(l.len(), func(i int) bool { s, _ := l.at(i); return s >= serial })
+ if i == l.len() {
+ return sum, false
+ }
+ s, b := l.at(i)
+ if s != serial {
+ return sum, false
+ }
+ copy(sum[:], b)
+ return sum, true
+}
+
+// sourceDigestsLoad reads the kept digests, once for each place they are
+// kept in. A file that can't be read, or was written by other row code,
+// is nothing kept. Under sourceDigests' lock.
+func sourceDigestsLoad() {
+ p := sourceDigestsPath()
+ if sourceDigestsDisk.path == p {
+ return
+ }
+ sourceDigestsDisk.path, sourceDigestsDisk.kept, sourceDigestsDisk.dirty = p, nil, false
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return
+ }
+ sourceDigestsDisk.kept = decodeSourceDigests(b, requestDiskBinary())
+}
+
+// decodeSourceDigests is b's digests when b was written for code, nil
+// when not, when b is cut short or out of order.
+func decodeSourceDigests(b []byte, code string) digestList {
+ if !bytes.HasPrefix(b, []byte(sourceDigestsMagic)) {
+ return nil
+ }
+ b = b[len(sourceDigestsMagic):]
+ n, k := binary.Uvarint(b)
+ if k <= 0 || uint64(len(b)-k) < n || string(b[k:k+int(n)]) != code {
+ return nil
+ }
+ l := digestList(b[k+int(n):])
+ if len(l)%digestLen != 0 {
+ return nil
+ }
+ for i := 1; i < l.len(); i++ {
+ if a, _ := l.at(i - 1); a >= binary.LittleEndian.Uint64(l[i*digestLen:]) {
+ return nil
+ }
+ }
+ return l
+}
+
+// encodeSourceDigests writes the sets' digests and kept's for code, the
+// first set's first, at most limit of them.
+func encodeSourceDigests(code string, limit int, kept digestList, sets ...map[uint64][sha256.Size]byte) []byte {
+ type one struct {
+ serial uint64
+ sum []byte
+ }
+ var all []one
+ seen := map[uint64]bool{}
+ for _, s := range sets {
+ for serial, sum := range s {
+ if !seen[serial] && len(all) < limit {
+ seen[serial] = true
+ all = append(all, one{serial, append([]byte(nil), sum[:]...)})
+ }
+ }
+ }
+ for i := 0; i < kept.len() && len(all) < limit; i++ {
+ if serial, sum := kept.at(i); !seen[serial] {
+ all = append(all, one{serial, sum})
+ }
+ }
+ slices.SortFunc(all, func(a, b one) int { return cmp.Compare(a.serial, b.serial) })
+ b := make([]byte, 0, len(sourceDigestsMagic)+binary.MaxVarintLen64+len(code)+len(all)*digestLen)
+ b = append(b, sourceDigestsMagic...)
+ b = binary.AppendUvarint(b, uint64(len(code)))
+ b = append(b, code...)
+ for _, e := range all {
+ b = binary.LittleEndian.AppendUint64(b, e.serial)
+ b = append(b, e.sum...)
+ }
+ return b
+}
+
+// sourceDigestWrites puts the writes in order: one encoded before the
+// last written is not written over it.
+var sourceDigestWrites struct {
+ sync.Mutex
+ made, wrote int // generations: under sourceDigests' lock, and under the Mutex
+}
+
+// sourceDigestsSave writes the digests of this run, when one was made that
+// isn't on disk: those of the chunks hashed or used since the last turn
+// and before it. Encoded under sourceDigests' lock, written behind it, as
+// heat-v1.json is: once a start, and again when a file changed.
+func sourceDigestsSave() {
+ d := &sourceDigests
+ d.Lock()
+ if !sourceDigestsDisk.dirty || sourceDigestsDisk.path == "" {
+ d.Unlock()
+ return
+ }
+ sourceDigestsDisk.dirty = false
+ // this run's first, then those kept from before it it hasn't met (a
+ // query of a few files keeps the rest): a file gone falls out once
+ // two turns' worth are made
+ b := encodeSourceDigests(requestDiskBinary(), 2*sourceDigestsKept, sourceDigestsDisk.kept, d.by, d.last)
+ p := sourceDigestsDisk.path
+ w := &sourceDigestWrites
+ w.made++
+ gen := w.made
+ d.Unlock()
+ w.Lock()
+ defer w.Unlock()
+ if gen < w.wrote {
+ return
+ }
+ w.wrote = gen
+ writeFileRenamed(p, b)
+}
+
+// writeFileRenamed writes b to p through a temp file renamed over it.
+func writeFileRenamed(p string, b []byte) {
+ dir := filepath.Dir(p)
+ if os.MkdirAll(dir, 0o700) != nil {
+ return
+ }
+ tmp, err := os.CreateTemp(dir, ".heat-digests-*")
+ if err != nil {
+ return
+ }
+ _, err = tmp.Write(b)
+ if cerr := tmp.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil || os.Rename(tmp.Name(), p) != nil {
+ os.Remove(tmp.Name())
+ }
+}
diff --git a/internal/usage/heat_digest_disk_test.go b/internal/usage/heat_digest_disk_test.go
new file mode 100644
index 000000000..38b580c52
--- /dev/null
+++ b/internal/usage/heat_digest_disk_test.go
@@ -0,0 +1,97 @@
+package usage
+
+import (
+ "crypto/sha256"
+ "fmt"
+ "os"
+ "testing"
+ "time"
+)
+
+// A start takes a session file's chunk's digest from the last run's, kept
+// by its serial, and hashes its rows only when the file or the row code
+// changed (#2278).
+func TestSourceDigestsKeptAcrossStarts(t *testing.T) {
+ pageHome(t)
+ cut := time.Date(2026, 9, 28, 0, 0, 0, 0, time.UTC)
+ d := heatDiskRef{root: "r", meta: "m"}
+ chunk := func(serial uint64, input int) *rowChunk {
+ c := &rowChunk{serial: serial}
+ c.Source.Agent, c.Source.Key, c.Source.Path = "codex", "k", fmt.Sprint("/s/", serial)
+ for i := 1; i <= 3; i++ {
+ c.add(Row{Record: Record{Time: cut.Add(-time.Duration(i) * time.Hour), Agent: "codex", Model: "m", Input: i * input}}, fmt.Sprint("msg", i), int64(i), false)
+ }
+ return c
+ }
+ restart := func() {
+ sourceDigests.Lock()
+ sourceDigests.by, sourceDigests.last = nil, nil
+ sourceDigestsDisk.path, sourceDigestsDisk.kept = "", nil
+ sourceDigests.Unlock()
+ }
+ key := func(cs ...*rowChunk) (string, int) {
+ sourceDigests.Lock()
+ was := sourceDigestsHashed
+ sourceDigests.Unlock()
+ k, ok := heatSettledKey(d, cut, time.Time{}, Filter{}, nil, [3][]*rowChunk{cs}, heatSum{})
+ if !ok {
+ t.Fatal("not named")
+ }
+ sourceDigests.Lock()
+ defer sourceDigests.Unlock()
+ return k, sourceDigestsHashed - was
+ }
+ restart()
+ first, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20))
+ if n != 2 {
+ t.Fatalf("a first start hashed %d chunks, want 2", n)
+ }
+ restart()
+ if again, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20)); n != 0 || again != first {
+ t.Fatalf("started again, hashed %d chunks, key %s, was %s", n, again, first)
+ }
+ // a start that met one file keeps the other's for the next
+ restart()
+ if _, n := key(chunk(1<<63|1, 10)); n != 0 {
+ t.Fatalf("hashed %d", n)
+ }
+ restart()
+ if _, n := key(chunk(1<<63|3, 30)); n != 1 {
+ t.Fatalf("a new file hashed %d, want 1", n)
+ }
+ restart()
+ if again, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20)); n != 0 || again != first {
+ t.Fatalf("after a start of other files, hashed %d chunks, key %s, was %s", n, again, first)
+ }
+
+ // another build's row code: hashed again
+ b, err := os.ReadFile(sourceDigestsPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ other := encodeSourceDigests(requestDiskBinary()+"x", 10, decodeSourceDigests(b, requestDiskBinary()))
+ if decodeSourceDigests(b, requestDiskBinary()).len() != 3 {
+ t.Fatalf("kept %d, want 3", decodeSourceDigests(b, requestDiskBinary()).len())
+ }
+ if err := os.WriteFile(sourceDigestsPath(), other, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ restart()
+ if _, n := key(chunk(1<<63|1, 10), chunk(1<<63|2, 20)); n != 2 {
+ t.Fatalf("other row code: hashed %d chunks, want 2", n)
+ }
+ // a file cut short is nothing kept
+ b, _ = os.ReadFile(sourceDigestsPath())
+ os.WriteFile(sourceDigestsPath(), b[:len(b)-1], 0o600)
+ restart()
+ if _, n := key(chunk(1<<63|1, 10)); n != 1 {
+ t.Fatalf("a cut file: hashed %d, want 1", n)
+ }
+ if got := decodeSourceDigests([]byte(sourceDigestsMagic), requestDiskBinary()); got != nil {
+ t.Fatalf("no code: %v", got)
+ }
+ var sum [sha256.Size]byte
+ if got := decodeSourceDigests(encodeSourceDigests("c", 1, nil, map[uint64][sha256.Size]byte{1: sum, 2: sum}), "c"); got.len() != 1 {
+ t.Fatalf("limit 1 kept %d", len(got))
+ }
+}
diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go
index 413cfe186..625766ac9 100644
--- a/internal/usage/heat_disk.go
+++ b/internal/usage/heat_disk.go
@@ -143,6 +143,7 @@ func heatSettledKey(d heatDiskRef, cut, since time.Time, f Filter, identities ma
hashRows(h, rows.of(c))
}
}
+ sourceDigestsSave()
return fmt.Sprintf("%x", h.Sum(nil)), true
}
@@ -172,14 +173,23 @@ func sourceDigest(c *rowChunk, rows *chunkRows) [sha256.Size]byte {
if !ok {
sum, ok = d.last[c.serial]
}
- d.Unlock()
if !ok {
+ sourceDigestsLoad()
+ sum, ok = sourceDigestsDisk.kept.get(c.serial)
+ }
+ d.Unlock()
+ made := !ok
+ if made {
h := sha256.New()
io.WriteString(h, c.Source.Agent+"\x00"+c.Source.Key+"\x00")
hashRows(h, rows.of(c))
copy(sum[:], h.Sum(nil))
}
d.Lock()
+ if made {
+ sourceDigestsHashed++
+ sourceDigestsDisk.dirty = true
+ }
if d.by == nil || len(d.by) >= sourceDigestsKept {
d.last, d.by = d.by, map[uint64][sha256.Size]byte{}
}
diff --git a/site/files.js b/site/files.js
index ac643d6be..1b1de1331 100644
--- a/site/files.js
+++ b/site/files.js
@@ -148,7 +148,20 @@ export async function mirror(env, rels, open, now = Date.now, attest = null) {
else done.failed.push(`${tag}/${BUNDLES}`);
}
}
- await prune(env, tags);
+ const kept = await prune(env, tags);
+ // a release the feeds named for one run only (the next tag came minutes
+ // later) can leave that run with its files copied and its budget spent;
+ // its bundles are filled in from the files R2 holds of it, while kept
+ for (const tag of kept) {
+ if (!attest || byVersion(tag, "v" + ATTESTED) < 0 || now() > until) continue;
+ const have = await held(env, tag);
+ if (!have || BUNDLES in have) continue;
+ const assets = {};
+ for (const [name, sha256] of Object.entries(have)) if (sha256) assets[name] = { sha256 };
+ if (!Object.keys(assets).length) continue;
+ if (await keepBundles(env, tag, { assets }, attest)) done.copied.push(`${tag}/${BUNDLES}`);
+ else done.failed.push(`${tag}/${BUNDLES}`);
+ }
return done;
}
@@ -157,8 +170,12 @@ export async function mirror(env, rels, open, now = Date.now, attest = null) {
// the next run asks again rather than keep a list with holes in it.
async function keepBundles(env, tag, rel, attest) {
const lines = new Set();
+ // release CI signs every file in one statement, so the first answer
+ // covers the rest: GitHub's API is asked once a release, not once a file
+ // (unsigned, it allows 60 an hour to an IP the worker shares)
+ const covered = new Set();
for (const [name, a] of Object.entries(rel.assets)) {
- if (!a.sha256) continue;
+ if (!a.sha256 || covered.has(a.sha256)) continue;
let got = null;
try {
got = await attest(a.sha256);
@@ -169,7 +186,10 @@ async function keepBundles(env, tag, rel, attest) {
console.log("r2 attest: none for", tag, name);
return false;
}
- for (const b of got) lines.add(JSON.stringify(b));
+ for (const b of got) {
+ lines.add(JSON.stringify(b));
+ for (const h of subjects(b)) covered.add(h);
+ }
}
if (!lines.size) return false;
try {
@@ -183,6 +203,16 @@ async function keepBundles(env, tag, rel, attest) {
}
}
+// subjects is the sha256 of each file a Sigstore bundle's statement names.
+export function subjects(b) {
+ try {
+ const st = JSON.parse(atob(b.dsseEnvelope.payload));
+ return (st.subject || []).map((x) => x.digest && x.digest.sha256).filter(Boolean);
+ } catch {
+ return [];
+ }
+}
+
async function copy(env, tag, name, a, open) {
let res = null;
try {
@@ -216,7 +246,8 @@ async function copy(env, tag, name, a, open) {
}
}
-// prune deletes every tag but keep and the KEEP newest besides.
+// prune deletes every tag but keep and the KEEP newest besides, and
+// returns those KEEP newest.
async function prune(env, keep) {
let tags = [], cursor;
try {
@@ -227,7 +258,7 @@ async function prune(env, keep) {
} while (cursor);
} catch (e) {
console.log("r2 prune: list", String(e));
- return;
+ return [];
}
const rest = tags.filter((t) => !keep.includes(t)).sort((a, b) => byVersion(b, a));
for (const tag of rest.slice(KEEP)) {
@@ -240,6 +271,7 @@ async function prune(env, keep) {
console.log("r2 prune: delete", tag, String(e));
}
}
+ return rest.slice(0, KEEP);
}
function byVersion(a, b) {
diff --git a/site/files.test.mjs b/site/files.test.mjs
index b9b70509a..10ede69a4 100644
--- a/site/files.test.mjs
+++ b/site/files.test.mjs
@@ -179,6 +179,45 @@ test("mirror: a release's attestation bundles land in R2 as attestations.jsonl,
assert.deepEqual(asked, []);
});
+test("mirror: a kept release the feeds no longer name still gets its bundles, for the files R2 holds of it (v0.1.3978)", async () => {
+ const env = { RELEASES: bucket() };
+ // v0.1.3978 was the newest for one run, which copied its files and spent
+ // its budget; by the next run v0.1.3979 had taken its place in the feed
+ await hold(env.RELEASES, "v0.1.3978", "a", "A");
+ await hold(env.RELEASES, "v0.1.3978", "b", "B");
+ await hold(env.RELEASES, "v0.1.3890", "a", "old");
+ const rel = { version: "0.1.3979", assets: { c: { sha256: sha("C") } } };
+ const asked = [];
+ const attest = async (h) => (asked.push(h), [{ for: h }]);
+ const done = await mirror(env, [rel], async () => new Response("C"), Date.now, attest);
+ assert.deepEqual(done.copied.sort(), ["v0.1.3978/attestations.jsonl", "v0.1.3979/attestations.jsonl", "v0.1.3979/c"]);
+ const res = await ask(env, "/files/v0.1.3978/attestations.jsonl");
+ assert.equal(res.status, 200);
+ const lines = (await res.text()).trimEnd().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(lines.map((l) => l.for).sort(), [sha("A"), sha("B")].sort());
+ // a kept release from before the attestations is not asked
+ assert.equal(asked.includes(sha("old")), false);
+ // written once: the next run asks nothing more
+ asked.length = 0;
+ await mirror(env, [rel], async () => new Response("C"), Date.now, attest);
+ assert.deepEqual(asked, []);
+});
+
+test("mirror: one statement signing every file is asked for once a release, not once a file", async () => {
+ const env = { RELEASES: bucket() };
+ const names = ["a", "b", "c"];
+ const rel = { version: "0.1.3982", assets: Object.fromEntries(names.map((n) => [n, { sha256: sha(n) }])) };
+ const statement = { subject: names.map((n) => ({ name: n, digest: { sha256: sha(n) } })) };
+ const bundle = { dsseEnvelope: { payload: btoa(JSON.stringify(statement)) } };
+ const asked = [];
+ const attest = async (h) => (asked.push(h), [bundle]);
+ const done = await mirror(env, [rel], async (n) => new Response(n), Date.now, attest);
+ assert.ok(done.copied.includes("v0.1.3982/attestations.jsonl"));
+ assert.equal(asked.length, 1);
+ const res = await ask(env, "/files/v0.1.3982/attestations.jsonl");
+ assert.deepEqual((await res.text()).trimEnd().split("\n").map((l) => JSON.parse(l)), [bundle]);
+});
+
test("mirror: a release from before the attestations is not asked for any", async () => {
const env = { RELEASES: bucket() };
const rel = { version: "0.1.3890", assets: { a: { sha256: sha("A") } } };
diff --git a/site/public/docs/import.html b/site/public/docs/import.html
index b65399754..2f330d0e0 100644
--- a/site/public/docs/import.html
+++ b/site/public/docs/import.html
@@ -318,6 +318,7 @@ href = "https://usemagpie.ai/import#" + urlencode({
| Linux | By a desktop entry (x-scheme-handler/magpie), written by the installer and again on first run. |
| Terminal | magpie import <link> shows the same summary and asks before adding. |
+ CC Switch links. magpie also opens the ccswitch://v1/import?resource=provider&… links relays make for CC Switch (app, name, endpoint, apiKey, apiFormat, model, or a base64 config), with the same confirmation. Only providers are taken, not prompts, MCP servers or skills. magpie claims the scheme only when no other app has it, so CC Switch, if installed, keeps its links (on macOS, where both can claim it, the system picks).
Import links need magpie 0.1.8 or later. When magpie is already running, the link goes to that instance and its window comes forward.