Files
magpie/internal/agent/dim_daemon.go
T
yetone d01e0a465a agent: Dim's built-in Magpie provider is filled in, so a plain dima runs on magpie (T_t__biu on X)
T_t__biu on X: Dim alpha has a provider named Magpie built in, and
magpie's one-click connect left it empty, relying on DIM_* variables a
shell function set for each run. Dim launched any other way (its app, a
terminal opened before, an IDE) was not on magpie.

Dim keeps providers in a database only its daemon writes, so magpie now
talks to the daemon the way Dim's own clients do (JSON-RPC 2.0 after a
hello of protocol 4, on <home>/rust/daemon.sock, or on Windows through
Dim's pipe bridge `dimcode-server app-server --connect-pipe`; read from
Dim's crates/dim-app-server and dim-client source). Picking a magpie
model:
- writes the gateway's /v1 (the port magpie is on), magpie's key and
  enabled onto the `magpie` provider only, each against the record's
  version (provider.update);
- refreshes it, gives a model its token limits when the gateway doesn't
  know them (provider.models.edit), and makes it Dim's pick
  (provider.select against the pick's version);
- records first, in magpie's own dim.json (temp+rename), what was there
  and the pick to give back.
A key or address the user set on that entry themselves is kept: magpie
writes nothing to the provider and only picks the model. Sync writes the
port and key again when they change. Disconnect (`magpie dim default`
or the switch) turns the entry off with the key cleared (Dim clears a
key only on a provider turned off), puts the address back, and puts
back the model Dim was on. No other provider is read or written. The
per-run env and shell function stay only as the fallback when Dim's
daemon can't be reached or started.

Run at this commit's tree (on origin/main d048939da, then rebased over
3 commits that touch neither internal/agent nor the docs here):
- go test -run TestDim ./internal/agent on mica: 8 ok. Red on the old
  dim.go (with a stub for the new test helpers): FillsItsMagpieProvider
  (key empty), MagpieProviderPort, MagpieProviderUsersOwn/key (not
  picked), SyncMovesToProvider.
- Real Dim 0.1.0-alpha.24 (npm dimcode-alpha) in a sandbox HOME on
  mote, with a sandbox `magpie serve` on 38725 and a fake upstream:
  the user's own deepseek provider set and picked first. `magpie dim
  up/m1` left deepseek at v3 untouched, set magpie to on, 38725/v1, a
  key, and picked magpie/up/m1; a plain `dima exec -p` with no DIM_*
  set answered PONG-FROM-UPSTREAM through the gateway. `magpie dim
  default` turned magpie off, no key, 3425/v1, pick back to
  deepseek/fake/known. With a key and address set on the Magpie entry
  by hand first, connect wrote nothing to it (wrote:false) and only
  picked; disconnect gave the pick back and left the entry as set.
- Windows (xiaomi-gpu, real Dim alpha.24 in a sandbox DIMCODE_HOME):
  dimConnect through the pipe bridge did the hello and read the magpie
  provider and selection (a throwaway probe test, not committed).
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... on mote: clean.
- go test -tags nogui -count=1 -timeout 45m ./... on mote (suite.lock):
  every package ok (internal/agent 372 s) except 6 reds, each red the
  same on a clean origin/main d048939da copy and already filed:
  internal/cli TestHealthcheckFindsTheRunningGatewayWithoutMagpieAddr,
  TestUpdateRestartsTheGatewayItFindsWithoutMagpieAddr,
  TestUpdateFindsAMagpieThatWroteNoRecord (#6223); internal/gateway
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117),
  TestLaneLimitRoutes (#5150); internal/gui
  TestSettingsSaveKeepsWhatItDoesNotSend (#7127).

Not tried: a full connect/disconnect on Windows or Linux with a real
magpie serve (only the Windows pipe read); Dim's desktop app (the CLI
and daemon only); a UNC or symlinked DIMCODE_HOME on Windows.
2026-11-19 01:38:23 +08:00

229 lines
6.5 KiB
Go

package agent
// Dim alpha keeps its Providers in a database its daemon owns
// (<home>/rust/dimcode.sqlite, with a version per record that every write
// is checked against), and changes them only through the daemon's
// JSON-RPC API, the one Dim's own CLI and desktop app use
// (crates/dim-app-server/src/provider/management.rs,
// docs/design/appserver/provider-management.md). magpie talks to the
// daemon the same way: newline-delimited JSON-RPC 2.0 after a hello of
// protocol 4, on <home>/rust/daemon.sock on macOS and Linux, and on
// Windows through the authenticated pipe bridge Dim's client starts
// (`dimcode-server app-server --connect-pipe <pipe>`, dim-client's
// Client::open). Without a daemon, `dima models magpie` starts one, as
// any dima command does, and lists nothing.
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/proc"
)
// errDimAway is Dim's daemon not reachable, and none started.
var errDimAway = errors.New("Dim's daemon isn't running")
// dimOpen connects to the daemon of Dim's home dir, starting it when
// start and it isn't running; tests swap it for a fake daemon.
var dimOpen = openDimDaemon
func openDimDaemon(dir string, start bool) (io.ReadWriteCloser, error) {
c, err := dimDial(dir)
if err == nil || !start || proc.Isolated() {
if err != nil {
return nil, fmt.Errorf("%w: %v", errDimAway, err)
}
return c, nil
}
bin := proc.FindTool("dima")
if bin == "" {
return nil, fmt.Errorf("%w: dima isn't installed", errDimAway)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
// any dima command starts the daemon; this one lists the Magpie
// provider's models and changes nothing
cmd := proc.CommandContext(ctx, bin, "models", "magpie")
cmd.Env = append(os.Environ(), "DIMCODE_HOME="+dir)
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("%w: dima models: %v", errDimAway, err)
}
for end := time.Now().Add(10 * time.Second); ; time.Sleep(200 * time.Millisecond) {
if c, err = dimDial(dir); err == nil || time.Now().After(end) {
break
}
}
if err != nil {
return nil, fmt.Errorf("%w: %v", errDimAway, err)
}
return c, nil
}
// dimConn is one connection to Dim's daemon, greeted.
type dimConn struct {
rw io.ReadWriteCloser
r *bufio.Reader
id int
stop *time.Timer
}
// dimError is an error the daemon answered, with Dim's own code
// (provider_conflict, provider_not_found, provider_invalid_config…).
type dimError struct {
Message string `json:"message"`
Data struct {
AppError string `json:"appError"`
} `json:"data"`
}
func (e *dimError) Error() string { return "Dim: " + e.Message }
func dimCode(err error) string {
var e *dimError
if errors.As(err, &e) {
return e.Data.AppError
}
return ""
}
// dimConnect is a greeted connection, closed after a minute at most
// whatever it waits on.
func dimConnect(dir string, start bool) (*dimConn, error) {
rw, err := dimOpen(dir, start)
if err != nil {
return nil, err
}
c := &dimConn{rw: rw, r: bufio.NewReaderSize(rw, 64<<10)}
c.stop = time.AfterFunc(time.Minute, func() { rw.Close() })
var hello struct {
ProtocolVersion int `json:"protocolVersion"`
}
if err := c.call("hello", map[string]any{"protocolVersion": 4, "clientKind": "other", "clientName": "magpie"}, &hello); err != nil {
c.close()
return nil, err
}
return c, nil
}
func (c *dimConn) close() {
c.stop.Stop()
c.rw.Close()
}
// call sends method and reads its answer into out (nil to drop it);
// notifications and other answers on the way are skipped.
func (c *dimConn) call(method string, params, out any) error {
c.id++
b, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": c.id, "method": method, "params": params})
if err != nil {
return err
}
if _, err := c.rw.Write(append(b, '\n')); err != nil {
return fmt.Errorf("Dim %s: %w", method, err)
}
for {
line, err := c.r.ReadBytes('\n')
if err != nil {
return fmt.Errorf("Dim %s: %w", method, err)
}
var m struct {
ID *int `json:"id"`
Result json.RawMessage `json:"result"`
Error *dimError `json:"error"`
}
if json.Unmarshal(line, &m) != nil || m.ID == nil || *m.ID != c.id {
continue
}
if m.Error != nil {
return m.Error
}
if out == nil {
return nil
}
return json.Unmarshal(m.Result, out)
}
}
// dimProvider is the part of a Provider record (provider.management)
// magpie reads.
type dimProvider struct {
ID string `json:"providerId"`
Version int `json:"version"`
Enabled bool `json:"enabled"`
Connection struct {
BaseURL string `json:"baseUrl"`
CredentialConfigured bool `json:"credentialConfigured"`
} `json:"connection"`
}
// dimModel is a model of a provider's catalog (provider.refresh).
type dimModel struct {
ID string `json:"id"`
MissingLimits []string `json:"missingLimits"`
}
type dimCatalog struct {
Models []dimModel `json:"models"`
Version int `json:"version"`
}
// dimSelection is Dim's picked model (provider.selection).
type dimSelection struct {
Provider string `json:"provider_id"`
Model string `json:"model_id"`
Version int `json:"version,omitempty"`
}
func (c *dimConn) provider(id string) (*dimProvider, error) {
var r struct {
Providers []dimProvider `json:"providers"`
}
if err := c.call("provider.management", map[string]any{"providerId": id}, &r); err != nil {
return nil, err
}
for i := range r.Providers {
if r.Providers[i].ID == id {
return &r.Providers[i], nil
}
}
return nil, fmt.Errorf("Dim has no %s provider", id)
}
func (c *dimConn) update(p *dimProvider, patch map[string]any) error {
return c.call("provider.update", map[string]any{"providerId": p.ID, "expectedVersion": p.Version, "patch": patch}, nil)
}
func (c *dimConn) selection() (*dimSelection, error) {
var r struct {
Selection *dimSelection `json:"selection"`
}
if err := c.call("provider.selection", map[string]any{}, &r); err != nil {
return nil, err
}
return r.Selection, nil
}
// pick makes provider/model Dim's model, over the pick of version was
// (nil: none yet).
func (c *dimConn) pick(provider, model string, was *dimSelection) error {
p := map[string]any{"providerId": provider, "modelId": model}
if was != nil {
p["expectedVersion"] = was.Version
}
return c.call("provider.select", p, nil)
}
// dimMu keeps one change of Dim's providers at a time.
var dimMu sync.Mutex
// dimURL is a base URL as Dim compares it.
func dimURL(u string) string { return strings.TrimRight(strings.TrimSpace(u), "/") }