KoiLx0 runs one magpie as a client of another, through a gateway key, and had to switch every agent on by hand on the client before it took the remote's models. A Remote magpie's editor now has "Connect new agents to this remote" (自动接入新 agent) under Advanced, off by default. It is kept per computer in the stash (remote.<id>.connectAgents), not in providers.json, so a synced or shared providers list doesn't turn it on anywhere else. No server-side key permission. With it on, the follow loop (FollowRemotePicks, every 5 minutes, and at once when the switch is turned on) connects an agent installed here that the remote has connected, on the remote's pick (connectFromRemote), and records it as <agent>.remote.auto = on. An agent the user disconnected here is never connected again: - one with the Agents page's Disconnect mark, connected or not before; - one recorded on that is no longer connected (taken out by hand in its file, or by any other route) is recorded off. An agent magpie put back on quit (quit.restored) is left to RewireOnStart and not taken for a disconnect. Connecting it by hand records on again. The follow throttle's time is now under a mutex, since the save handler resets it from another goroutine. The switch shows in /api/providers as connectAgents and is saved as connectAgents (a save that leaves it out keeps it; a provider that isn't a Remote magpie is refused it). Advanced opens on its own while it is on. docs/subsystems/providers-accounts.md says all of this. app.js stays within its budget (TestCoreScriptBudget): the Remote magpie's three ticks (MCP servers, skills and prompts, agents) and their save are one loop, which the new switch costs less than it saves. Run: - mote, go test -tags nogui -count=1 -timeout 45m ./... with the first draft of app.js: every package ok but internal/gui, where only TestCoreScriptBudget failed (1087333 > 1086971). After the loop, rebased on origin/main187d06724(budget passes there alone), at this head: TestCoreScriptBudget, internal/gui, internal/agent and internal/cli ok. - mica: TestRemoteConnectsNewAgents, TestConnectFollowsTheRemoteMagpiesPicks, TestProviderSaveConnectAgents ok. - mote: go vet (darwin), GOOS=linux go vet -tags nogui, GOOS=windows go vet on internal/agent and internal/gui ok; gofmt -l clean. - GUI, mica, both engines, at f261f7ba6 (before the loop and the rebase): remote-connect-agents.test.cjs (new: under Advanced and closed while off, sent as ticked, Advanced opens on it ticked, unticked sent so; en, zh, zh-TW, ja, de at 420px, no sideways scroll) passes, with i18n-keys, i18n-en-no-cjk and every file that reaches the provider editor's Advanced or a Remote magpie (64 files): 1738 pass, 26 fail. The same files at origin/main19794cc10: 1728 pass, 24 fail, the same reds by name (editor-hints webkit #6156, account-arrange #6010, lan-join #6353, vertex-editor #4720, remote-magpie #5013, commented with this sha) except name-suffix-remote (#5147, red at base too on another language) and one count-free browser launch timeout; both files alone: 80 of 80 pass. At this head (rebased, with the loop): remote-connect-agents, library-mcp-on, provider-advanced-fold, i18n-keys, i18n-en-no-cjk pass; remote-magpie red as at base (#5013); editor-advanced-align red once in webkit, 1 of 4 alone (#6421, a Claude Code account's editor this change doesn't reach; it was red at base in the 64-file run). - Real use on mica, sandbox HOMEs, this branch's binary: remote R (`magpie serve`, Claude Code on gpt-5.4-mini) and a fresh client C with Claude Code installed, not connected. Switch off: C's settings.json stayed {}. Switch on, C restarted: "agent: Claude Code connected as the remote magpie's", ANTHROPIC_DEFAULT_SONNET_MODEL office/openai/gpt-5.4-mini, recorded on. `magpie claude default` (disconnect) and C restarted: settings back to the user's, recorded off, not connected again. Broken by hand, each red in TestRemoteConnectsNewAgents: - connectFromRemote returning at once (the old code): "not connected on the remote's group/fast"; - without the on-then-unconnected record: "an agent the user disconnected by hand in its file was connected again"; - without the Disconnect mark check: "an agent marked disconnected, never recorded, was connected"; - without the quit.restored exception: "a quit-restored agent: wired false, recorded off". Not tried: the switch turned on from the real app's window (the GUI test fakes the API; the save handler is covered by TestProviderSaveConnectAgents and real use wrote the stash key); agents other than Claude Code for real (the code is the same ConnectHow for every agent with fields); Windows and Linux runs.
359 lines
10 KiB
Go
359 lines
10 KiB
Go
package agent
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// The models a Remote magpie's agents are on, followed here (KoiLx0 on X:
|
|
// several computers use one remote magpie, and each had every agent's
|
|
// models set again by hand, and again after each change on the remote).
|
|
//
|
|
// - The remote tells, for each agent connected there, the catalog ref of
|
|
// each model field (SharedModels, GET provider.RemoteAgentModelsPath).
|
|
// - An agent connected here starts on the remote's picks, where this
|
|
// magpie lists them (How "remote"), after the models it was on when
|
|
// it was switched off and after a Codex that keeps its own.
|
|
// - A field set from the remote, or found on the remote's pick, is
|
|
// recorded (<agent>.<field>.remote in the stash). While it still holds
|
|
// that value, a change on the remote is followed (FollowRemotePicks,
|
|
// every FollowRemoteEvery). A value the user picks here is theirs:
|
|
// the record goes, and the field is left alone until it is on the
|
|
// remote's pick again.
|
|
|
|
func init() {
|
|
gateway.SharedAgentModels = func() ([]byte, error) {
|
|
return json.Marshal(provider.AgentModels{Agents: SharedModels()})
|
|
}
|
|
}
|
|
|
|
// FollowRemoteEvery is how often a Remote magpie's picks are asked.
|
|
const FollowRemoteEvery = 5 * time.Minute
|
|
|
|
// remoteAsk is how long a connect waits for a Remote magpie's picks it
|
|
// has none of yet.
|
|
const remoteAsk = 4 * time.Second
|
|
|
|
// SharedModels is, by agent id, the catalog ref of each model field of
|
|
// every agent connected here: what another magpie with this one as its
|
|
// provider starts its agents on.
|
|
func SharedModels() map[string]map[string]string {
|
|
out := map[string]map[string]string{}
|
|
for _, a := range DetectedIn(All()) {
|
|
if m := a.sharedModels(); len(m) > 0 {
|
|
out[a.ID] = m
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// sharedModels is SharedModels for one agent: its model fields' refs,
|
|
// none while it isn't connected.
|
|
func (a *Agent) sharedModels() map[string]string {
|
|
if a.Native != nil || !a.Wired() {
|
|
return nil
|
|
}
|
|
out := map[string]string{}
|
|
vals := a.Values()
|
|
for _, f := range a.Fields {
|
|
v := vals[f.Key]
|
|
if f.Own || f.Options == nil || v == "" || v == magpieID {
|
|
continue
|
|
}
|
|
for _, o := range f.Options(vals) {
|
|
if o.Value == v && o.Ref != "" {
|
|
out[f.Key] = o.Ref
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
var remoteCache struct {
|
|
sync.Mutex
|
|
at time.Time
|
|
picks []provider.RemotePicks
|
|
}
|
|
|
|
// remotePicks are the Remote magpies' picks, asked again when older than
|
|
// fresh (0: always). Never asked while there is no Remote magpie.
|
|
func remotePicks(ctx context.Context, fresh time.Duration) []provider.RemotePicks {
|
|
if !provider.HasPickedMagpie() {
|
|
return nil
|
|
}
|
|
remoteCache.Lock()
|
|
at, picks := remoteCache.at, remoteCache.picks
|
|
remoteCache.Unlock()
|
|
if fresh > 0 && !at.IsZero() && time.Since(at) < fresh {
|
|
return picks
|
|
}
|
|
picks, errs := provider.RemoteAgentPicks(ctx)
|
|
for id, err := range errs {
|
|
log.Printf("agent: the models %s's agents are on: %v", id, err)
|
|
}
|
|
remoteCache.Lock()
|
|
remoteCache.at, remoteCache.picks = time.Now(), picks
|
|
remoteCache.Unlock()
|
|
return picks
|
|
}
|
|
|
|
// remotePickFor is the option of opts a Remote magpie's agent of a's id
|
|
// has its field key on, the first remote that has one listed here.
|
|
func remotePickFor(id, key string, opts []Option, picks []provider.RemotePicks) (Option, bool) {
|
|
for _, rp := range picks {
|
|
ref := rp.Agents[id][key]
|
|
if ref == "" {
|
|
continue
|
|
}
|
|
pre := rp.Provider + "/"
|
|
for _, o := range opts {
|
|
if rest, ok := strings.CutPrefix(o.Ref, pre); ok && provider.SameRef(rest, ref) {
|
|
return o, true
|
|
}
|
|
}
|
|
}
|
|
return Option{}, false
|
|
}
|
|
|
|
func remoteKey(id, key string) string { return id + "." + key + ".remote" }
|
|
|
|
// connectRemote starts a on the models a Remote magpie's agent of its id
|
|
// is on. ok is false when no remote has a pick this magpie lists, or the
|
|
// picks leave a not connected.
|
|
func (a *Agent) connectRemote() (c Connection, ok bool, err error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), remoteAsk)
|
|
defer cancel()
|
|
picks := remotePicks(ctx, FollowRemoteEvery)
|
|
if len(picks) == 0 {
|
|
return Connection{}, false, nil
|
|
}
|
|
set := map[string]string{}
|
|
for _, f := range a.Fields {
|
|
if f.Own || f.Options == nil {
|
|
continue
|
|
}
|
|
o, found := remotePickFor(a.ID, f.Key, f.Options(a.Values()), picks)
|
|
if !found {
|
|
continue
|
|
}
|
|
if err := a.Apply(f.Key, o.Value); err != nil {
|
|
return Connection{}, false, err
|
|
}
|
|
if c.Field == "" {
|
|
c = Connection{How: "remote", Field: f.Key, Value: o.Value}
|
|
}
|
|
set[remoteKey(a.ID, f.Key)] = f.Get()
|
|
}
|
|
if len(set) == 0 {
|
|
return Connection{}, false, nil
|
|
}
|
|
stash(set)
|
|
return c, a.Wired(), nil
|
|
}
|
|
|
|
var followed struct {
|
|
sync.Mutex
|
|
last time.Time
|
|
}
|
|
|
|
// FollowRemotePicks puts each connected agent's field that is on a Remote
|
|
// magpie's pick onto that pick's change, at most every FollowRemoteEvery.
|
|
func FollowRemotePicks(ctx context.Context) {
|
|
if !provider.HasPickedMagpie() {
|
|
return
|
|
}
|
|
followed.Lock()
|
|
due := time.Since(followed.last) >= FollowRemoteEvery
|
|
if due {
|
|
followed.last = time.Now()
|
|
}
|
|
followed.Unlock()
|
|
if !due {
|
|
return
|
|
}
|
|
followRemote(ctx)
|
|
}
|
|
|
|
// KeepFollowingRemote runs FollowRemotePicks until ctx ends, for a magpie
|
|
// with no app: the app's Library loop runs it there (library.KeepLinked),
|
|
// and a headless `magpie serve` client of a Remote magpie followed its
|
|
// model list and efforts but never a pick changed on the remote (KoiLx0
|
|
// on X).
|
|
func KeepFollowingRemote(ctx context.Context, interval time.Duration) {
|
|
t := time.NewTicker(interval)
|
|
defer t.Stop()
|
|
for {
|
|
FollowRemotePicks(ctx)
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func followRemote(ctx context.Context) {
|
|
cctx, cancel := context.WithTimeout(ctx, 2*provider.RemoteAgentModelsWait)
|
|
picks := remotePicks(cctx, 0)
|
|
cancel()
|
|
if len(picks) == 0 {
|
|
return
|
|
}
|
|
as := DetectedIn(All())
|
|
connectFromRemote(as, picks)
|
|
for _, a := range as {
|
|
if a.Native != nil || a.Disconnected() || !a.Wired() {
|
|
continue
|
|
}
|
|
a.followRemote(picks)
|
|
}
|
|
}
|
|
|
|
// Connecting new agents from a Remote magpie (KoiLx0 on X: each agent
|
|
// still had to be switched on by hand on every client). The remote's
|
|
// editor, under Advanced, has a switch, off by default and kept on this
|
|
// computer alone (remoteConnectKey). While it is on, an agent installed
|
|
// here that the remote has connected, and that isn't connected here, is
|
|
// connected on the follow loop, on the remote's picks.
|
|
//
|
|
// - An agent the user disconnected here is never connected again: by
|
|
// the Agents page (its disconnectedKey mark), or by any other hand
|
|
// once it was connected (autoKey "off": seen connected, then not).
|
|
// - One a quit put back (RestoreOnQuit) is RewireOnStart's to connect.
|
|
// - Connecting it by hand again ends the "off": it is followed as any
|
|
// other from then on.
|
|
|
|
func remoteConnectKey(provider string) string { return "remote." + provider + ".connectAgents" }
|
|
|
|
// autoKey records, per agent, what the switch saw: "on" while it is
|
|
// connected, "off" once it was disconnected here.
|
|
func autoKey(id string) string { return id + ".remote.auto" }
|
|
|
|
// ConnectsAgents reports, by Remote magpie id, whose switch is on.
|
|
func ConnectsAgents() map[string]bool {
|
|
out := map[string]bool{}
|
|
const pre, suf = "remote.", ".connectAgents"
|
|
for k, v := range stashShared() {
|
|
if v == "1" && strings.HasPrefix(k, pre) && strings.HasSuffix(k, suf) && len(k) > len(pre)+len(suf) {
|
|
out[k[len(pre):len(k)-len(suf)]] = true
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// SetConnectAgents turns the switch of the Remote magpie id on or off. On,
|
|
// the next follow (FollowRemotePicks) is not waited for.
|
|
func SetConnectAgents(id string, on bool) {
|
|
if on {
|
|
stash(map[string]string{remoteConnectKey(id): "1"})
|
|
followed.Lock()
|
|
followed.last = time.Time{}
|
|
followed.Unlock()
|
|
return
|
|
}
|
|
forget(remoteConnectKey(id))
|
|
}
|
|
|
|
func connectFromRemote(as []*Agent, picks []provider.RemotePicks) {
|
|
on := ConnectsAgents()
|
|
if len(on) == 0 {
|
|
return
|
|
}
|
|
var restored []string
|
|
json.Unmarshal([]byte(stashShared()[quitRestoredKey]), &restored)
|
|
for _, a := range as {
|
|
if a.Native != nil || len(a.Fields) == 0 {
|
|
continue
|
|
}
|
|
wanted := false
|
|
for _, rp := range picks {
|
|
if on[rp.Provider] && len(rp.Agents[a.ID]) > 0 {
|
|
wanted = true
|
|
break
|
|
}
|
|
}
|
|
if !wanted {
|
|
continue
|
|
}
|
|
rec := stashShared()[autoKey(a.ID)]
|
|
switch {
|
|
case a.Wired():
|
|
if rec != "on" {
|
|
stash(map[string]string{autoKey(a.ID): "on"})
|
|
}
|
|
continue
|
|
case rec == "on" && !slices.Contains(restored, a.ID):
|
|
// connected, now not: disconnected here, by the user's hand
|
|
stash(map[string]string{autoKey(a.ID): "off"})
|
|
continue
|
|
case rec == "off" || a.Disconnected() || slices.Contains(restored, a.ID):
|
|
continue
|
|
}
|
|
c, err := a.ConnectHow()
|
|
if err != nil {
|
|
log.Printf("agent: %s, connected as the remote magpie's: %v", a.Name, err)
|
|
continue
|
|
}
|
|
if a.Wired() {
|
|
stash(map[string]string{autoKey(a.ID): "on"})
|
|
log.Printf("agent: %s connected as the remote magpie's (%s)", a.Name, c.How)
|
|
}
|
|
}
|
|
}
|
|
|
|
// followRemote is followRemote for one agent.
|
|
func (a *Agent) followRemote(picks []provider.RemotePicks) {
|
|
for _, f := range a.Fields {
|
|
if f.Own || f.Options == nil {
|
|
continue
|
|
}
|
|
vals := a.Values()
|
|
opts := f.Options(vals)
|
|
o, found := remotePickFor(a.ID, f.Key, opts, picks)
|
|
if !found {
|
|
continue
|
|
}
|
|
k := remoteKey(a.ID, f.Key)
|
|
rec, cur := stashShared()[k], vals[f.Key]
|
|
switch {
|
|
case onPick(cur, o, opts):
|
|
// on the remote's pick: followed from now on
|
|
if rec != cur {
|
|
stash(map[string]string{k: cur})
|
|
}
|
|
case rec != "" && cur == rec:
|
|
// still what was taken from the remote: the remote changed it
|
|
if err := a.Apply(f.Key, o.Value); err != nil {
|
|
log.Printf("agent: %s's %s from the remote magpie: %v", a.Name, f.Key, err)
|
|
continue
|
|
}
|
|
stash(map[string]string{k: f.Get()})
|
|
case rec != "":
|
|
// picked here since: the user's own from now on
|
|
forget(k)
|
|
}
|
|
}
|
|
}
|
|
|
|
// onPick reports whether cur, a field's value, is the model o is.
|
|
func onPick(cur string, o Option, opts []Option) bool {
|
|
if cur == o.Value {
|
|
return true
|
|
}
|
|
for _, x := range opts {
|
|
if x.Value == cur && x.Ref != "" {
|
|
return provider.SameRef(x.Ref, o.Ref)
|
|
}
|
|
}
|
|
return false
|
|
}
|