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.
This commit is contained in:
yetone
2026-11-19 01:38:23 +08:00
parent 1622484a86
commit d01e0a465a
8 changed files with 1077 additions and 47 deletions
+16 -10
View File
@@ -140,7 +140,7 @@ line; agents connected to magpie lose it when it quits.
| QwenPaw | each agent's `agent.json` in its workspace (`~/.qwenpaw/workspaces/<agent>`, the agents listed in `config.json`), under `$QWENPAW_WORKING_DIR`, else a legacy `~/.copaw`, else `~/.qwenpaw` | model (a `magpie` custom provider in `providers/custom/magpie.json` under QwenPaw's secret folder, `$QWENPAW_SECRET_DIR` or `~/.qwenpaw.secret`, OpenAI Chat at the gateway with magpie's models; the agent's `active_model` set to it, what was there put back on Disconnect; one row per agent, `qwenpaw` the default and `qwenpaw#<id>` the others; an agent on an ACP backend isn't listed; restart QwenPaw after the first connect), effort (the agent's `thinking_level`; magpie's models with reasoning levels are declared `thinking_param_style: "effort"` so QwenPaw applies it) |
| OpenClaw | `openclaw.json` in `~/.openclaw` (`$OPENCLAW_CONFIG_PATH`, `$OPENCLAW_STATE_DIR`, `~/.openclaw-<profile>` for `$OPENCLAW_PROFILE`, `~` as `$OPENCLAW_HOME`) | model (a `magpie` provider in `models.providers`, `openai-completions`, with magpie's models in it; `agents.defaults.model`'s primary set to it, what was there put back on Disconnect; `magpie/*` added to a `modelPolicy.allow` that would refuse it; the user's own keys in the provider and its models kept; a chat already on a model keeps it until `/model default`) |
| jcode | `config.toml` in `$JCODE_HOME`, else `~/.jcode` | model (a `[providers.magpie]` profile, `openai-compatible`, with magpie's models in it; `[provider] default_provider`/`default_model` set to it, what was there put back on Disconnect; the user's own keys in the profile, such as `headers` and a model's `reasoning_effort`, kept; restart open jcode sessions after connecting) |
| Dim (alpha, `dima`) | none of Dim's: magpie's own `dim.json` beside its settings, and a `dima` function in your shell profiles | model (Dim's documented start-up variables, set only for that run: `DIM_BASE_URL` the gateway's `/v1`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`, `DIM_MODEL` and both token limits; Dim's home (`$DIMCODE_HOME`, else `~/.dimcode-alpha`), saved Providers and account are never read or written. Type `dima` in a new terminal; picking Dim's own again takes the function out) |
| Dim (alpha, `dima`) | Dim's built-in **Magpie** provider, through Dim's own daemon (`$DIMCODE_HOME`, else `~/.dimcode-alpha`), and magpie's own `dim.json` beside its settings | model (Dim's Magpie provider gets the gateway's `/v1` and magpie's key, is turned on and made Dim's model, so a plain `dima` runs on magpie; no other provider is touched, and a key or address you set on the Magpie entry yourself is kept. Picking Dim's own again turns the entry off and puts back the model Dim was on. When Dim's daemon can't be reached, a `dima` function in your shell profiles starts it with `DIM_BASE_URL`, `DIM_API_KEY`, `DIM_MODEL` and the token limits for that run instead) |
| Mistral Vibe | `config.toml` in `$VIBE_HOME`, else `~/.vibe` | model (a `[[providers]]` entry named magpie with the gateway's `/v1` and the key as an `Authorization` header in `extra_headers`, since Vibe reads keys only from the environment; one `[[models]]` entry per model, aliased `magpie/<provider>/<model>`; `active_model` set to the alias, what was there put back on Disconnect; a `thinking` level the user set on a model kept; restart open vibe sessions after connecting) |
| MiniMax Code (mcode) | `~/.minimax/config.yaml` (`$MINIMAX_DATA_DIR`, or the folder the desktop app moved it to) | model (a `magpie` custom provider; magpie's models in its /model) |
| Droid (Factory) | `~/.factory/settings.json` (`$FACTORY_HOME_OVERRIDE`) | model (magpie's models as BYOK `customModels`, in Droid's /model) |
@@ -3351,15 +3351,21 @@ it starts agy untouched. A terminal open already takes the command the
Launch row copies. Stepping out (`magpie agy default`) takes the block out
again. `magpie agy env` prints what `agy run` adds.
**Dim** alpha (`dima`, npm's `dimcode-alpha`) is started on magpie the
way Dim documents for any OpenAI-compatible endpoint: `DIM_BASE_URL`,
`DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`, `DIM_MODEL`,
`DIM_MAX_CONTEXT_TOKENS` and `DIM_MAX_OUTPUT_TOKENS`, for that run only.
Picking a catalog model (`magpie dim <model>`) keeps it in magpie's own
`dim.json` and puts a marked `dima` function in your shell profiles, which
runs `magpie dim run`; Dim's own folder, saved Providers and account are
not touched. `magpie dim default` takes the file and the function out
again, and `magpie dim env` prints what `dim run` adds. No WSL twin.
**Dim** alpha (`dima`, npm's `dimcode-alpha`) has a built-in provider
named Magpie. Picking a catalog model (`magpie dim <model>`) fills it in
through Dim's daemon, the way Dim's own app does: the gateway's `/v1`
(`http://127.0.0.1:3425/v1`, or the port magpie is on), magpie's key, the
provider turned on, and the model made Dim's pick, with its token limits
when the gateway doesn't know them. A plain `dima`, or Dim's app, then runs
on magpie. Dim's other providers are never touched. A key or address you
set on the Magpie entry yourself is kept; magpie only picks the model.
`magpie dim default` turns the entry off, clears the key magpie put there
and puts back the model Dim was on before. The pick is kept in magpie's own
`dim.json`. Only when Dim's daemon can't be reached does magpie fall back to
a marked `dima` function in your shell profiles, which runs `magpie dim run`
with `DIM_BASE_URL`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`,
`DIM_MODEL`, `DIM_MAX_CONTEXT_TOKENS` and `DIM_MAX_OUTPUT_TOKENS` for that
run; `magpie dim env` prints them. No WSL twin.
agy installed in a WSL distro is listed as Antigravity CLI · WSL
<distro>, found by `~/.gemini/antigravity-cli` or the `agy` command there.
File diff suppressed because one or more lines are too long
+276 -33
View File
@@ -1,37 +1,53 @@
package agent
// Dim alpha (arcships/dim, the `dima` command of npm's dimcode-alpha) is
// started on magpie the way Dim documents for any OpenAI-compatible
// endpoint (docs/design/model-startup.md): DIM_BASE_URL with
// DIM_API_FORMAT, DIM_API_KEY, DIM_MODEL, and DIM_MAX_CONTEXT_TOKENS with
// DIM_MAX_OUTPUT_TOKENS for a model Dim doesn't know. Dim reads them for
// that one run only, beside a running daemon, and leaves its saved
// Providers alone; help, version and management commands ignore them.
// The format is openai-compatible, Dim's generic provider, not
// openai-chat, which Dim takes for OpenAI's own.
// Dim alpha (arcships/dim, the `dima` command of npm's dimcode-alpha) has
// a built-in provider named Magpie (default-catalog.json: Responses at
// http://127.0.0.1:3425/v1, an API key, no models until listed). Picking
// one of magpie's models in Dim's row fills that provider in, through the
// API of Dim's daemon (dim_daemon.go), the way Dim's own Providers
// settings do: magpie's key for Dim, the gateway's address when its port
// isn't 3425, on; its models listed from magpie's /v1/models (the limits
// Dim needs given where magpie's list has none); and the model picked
// made Dim's model. So dima, and anything else on Dim's daemon, runs on
// magpie however it is started. No other provider of Dim's is touched,
// and a key, or an address of neither Dim's nor magpie's, the user gave
// the Magpie provider is left as it is: magpie only picks the model on
// it. What was there before is kept in magpie's dim.json, beside the
// model, and Disconnect (or picking Dim's own) puts it back where it is
// still as magpie left it. Nothing reads or uses Dim's own account
// (magpie dropped the DimAgent subscription at its vendor's request,
// v0.1.471).
//
// Nothing of Dim's is written: not its home ($DIMCODE_HOME, else
// ~/.dimcode-alpha), its settings or its database, and nothing reads or
// uses Dim's own account (magpie dropped the DimAgent subscription at its
// vendor's request, v0.1.471). The model picked in Dim's row is in a file
// of magpie's, dim.json in magpie's folder. While it names one of
// magpie's models, magpie puts a function named dima in each shell the
// user has, between "# >>> magpie dima >>>" and "# <<< magpie dima <<<"
// (update.ShellFunction), which runs `magpie dim run` (cli/start_cli.go)
// to start the real dima with the variables; the row gives the command
// for a terminal open before. Picking Dim's own again (or Disconnect)
// removes the file and the function, and dima runs as it did.
// When Dim's daemon can't be reached or doesn't take magpie's model, dima
// is started on magpie the way Dim documents for any OpenAI-compatible
// endpoint (docs/design/model-startup.md) instead: DIM_BASE_URL with
// DIM_API_FORMAT, DIM_API_KEY, DIM_MODEL, and DIM_MAX_CONTEXT_TOKENS with
// DIM_MAX_OUTPUT_TOKENS, read for that one run only. magpie puts a
// function named dima in each shell the user has, between "# >>> magpie
// dima >>>" and "# <<< magpie dima <<<" (update.ShellFunction), which
// runs `magpie dim run` (cli/start_cli.go) to start the real dima with
// them. The format is openai-compatible, Dim's generic provider, not
// openai-chat, which Dim takes for OpenAI's own. Once the daemon is
// reached (a Sync while it runs), the provider is filled in and the
// function goes.
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/update"
)
@@ -109,12 +125,20 @@ func dim(home string) *Agent { return dimIn(here(home)) }
func dimIn(at place) *Agent {
file := dimFile()
dir := dimDir(at)
model := jsonGet(file, "model")
gw, key := gateway.URL, func() string { return agentKey("dim") }
on := func() bool { return usesMagpie(model()) }
spec := func() *launchSpec { return dimLaunch(gw(), key(), model()) }
local := func() bool { h, _ := homes(); return h == at.home }
// wired: Dim's own Magpie provider is on magpie's model, so dima runs
// on it as it is
wired := func() bool {
st := readDimState(file)
return usesMagpie(st.Model) && st.Dim != nil && st.Dim.Picked != "" && st.Dim.Picked == strings.TrimPrefix(st.Model, magpieID+"/")
}
shell := func(set bool) {
if h, _ := homes(); h != at.home {
if !local() {
return
}
if set {
@@ -124,7 +148,7 @@ func dimIn(at place) *Agent {
}
}
shellIn := func() []string {
if h, _ := homes(); h != at.home {
if !local() {
return nil
}
return update.ShellFunctionIn("dima")
@@ -132,15 +156,15 @@ func dimIn(at place) *Agent {
launch := func() string { return dimCommand(gw(), key(), model(), runtime.GOOS == "windows") }
return &Agent{
ID: "dim", Name: "Dim", Icon: "dim-color", Aliases: []string{"dima", "dimcode-alpha"}, Spelled: prefixed, NoNames: true,
Bin: "dima", Dir: dimDir(at), Path: file,
Bin: "dima", Dir: dir, Path: file,
Launch: func() string {
if !on() {
if !on() || wired() {
return ""
}
return launch()
},
Typed: func() string {
if !on() || len(shellIn()) == 0 {
if !on() || wired() || len(shellIn()) == 0 {
return ""
}
return "dima"
@@ -148,16 +172,29 @@ func dimIn(at place) *Agent {
Start: func() Starting {
s := Starting{Bin: "dima"}
if v := model(); on() {
s.Env, s.Model = spec().vars(gw(), key()), v
s.Model = v
if !wired() {
s.Env = spec().vars(gw(), key())
}
}
return s
},
Sync: func() error {
shell(on())
if !on() {
shell(false)
return nil
}
// a running daemon gets magpie's address and key again (a new
// port, a new key), and one a Dim connected before this
// version never had is given them now; none is started here
if local() {
dimWire(dir, file, model(), false, !wired())
}
shell(!wired())
return nil
},
Notice: func() string {
if !on() {
if !on() || wired() {
return ""
}
if in := shellIn(); len(in) > 0 {
@@ -178,16 +215,24 @@ func dimIn(at place) *Agent {
},
Set: func(v string) error {
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil {
st := readDimState(file)
st.Model = v
if err := writeDimState(file, st); err != nil {
return err
}
if err := edit.SetJSON(file, edit.KV{Path: "model", Value: v}); err != nil {
return err
}
shell(true)
// Dim's Magpie provider, else (no Dim daemon to
// reach, the gateway not answering it) the variables
// of a dima function as before
shell(!local() || dimWire(dir, file, v, true, true) != nil)
return nil
}
// Dim's own model is its own to pick: magpie steps out
// and puts back what it changed
if local() {
if err := dimUnwire(dir, file); err != nil {
return err
}
}
if err := os.Remove(file); err != nil && !os.IsNotExist(err) {
return err
}
@@ -200,3 +245,201 @@ func dimIn(at place) *Agent {
}},
}
}
// dimDefault is the base URL of Dim's built-in Magpie provider
// (crates/dim-app-server/resources/default-catalog.json).
const dimDefault = "http://127.0.0.1:3425/v1"
// dimRecord is what magpie changed in Dim, kept in dim.json beside the
// model so Disconnect can put it back.
type dimRecord struct {
// Wrote: magpie gave Dim's Magpie provider its address and key. Not
// when the user had given it a key, or an address of neither Dim's
// nor magpie's, of their own: those are left as they are.
Wrote bool `json:"wrote"`
URL string `json:"url,omitempty"` // the base URL magpie gave it
Key string `json:"key,omitempty"` // a hash of the key magpie gave it
// the provider's base URL before magpie, and Dim's model (on
// Disconnect the provider is turned off: Dim clears a key only so)
BaseURL string `json:"baseUrl,omitempty"`
Selection *dimSelection `json:"selection"`
Picked string `json:"picked,omitempty"` // the model magpie picked in Dim
}
type dimState struct {
Model string `json:"model,omitempty"`
Dim *dimRecord `json:"dim,omitempty"`
}
func readDimState(file string) dimState {
var st dimState
if b, err := os.ReadFile(file); err == nil {
json.Unmarshal(b, &st)
}
return st
}
func writeDimState(file string, st dimState) error {
b, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil {
return err
}
return edit.WriteAtomic(file, append(b, '\n'))
}
func dimKeyHash(k string) string {
s := sha256.Sum256([]byte(k))
return hex.EncodeToString(s[:8])
}
// dimWire puts Dim's built-in Magpie provider on magpie's gateway: its
// base URL (when the port isn't Dim's 3425), magpie's key for Dim, and on;
// and, with pick, lists its models and makes model Dim's model, giving
// it the limits Dim needs when magpie's /v1/models has none. Nothing else
// of Dim's is changed, and a key or address the user gave that provider
// is theirs: magpie only picks the model on it. What was there before is
// kept in dim.json the first time, for dimUnwire.
func dimWire(dir, file, model string, start, pick bool) error {
dimMu.Lock()
defer dimMu.Unlock()
c, err := dimConnect(dir, start)
if err != nil {
return err
}
defer c.close()
st := readDimState(file)
st.Model = model
p, err := c.provider(magpieID)
if err != nil {
return err
}
url, key := gateway.URL()+"/v1", agentKey("dim")
rec := st.Dim
if rec == nil {
was, err := c.selection()
if err != nil {
return err
}
if was != nil {
was = &dimSelection{Provider: was.Provider, Model: was.Model}
}
base := dimURL(p.Connection.BaseURL)
own := p.Connection.CredentialConfigured || (base != dimDefault && base != dimURL(url))
rec = &dimRecord{Wrote: !own, BaseURL: p.Connection.BaseURL, Selection: was}
st.Dim = rec
// kept before Dim is written, so a change cut short is put back
if err := writeDimState(file, st); err != nil {
return err
}
}
if rec.Wrote && (rec.URL == "" || dimURL(p.Connection.BaseURL) == dimURL(rec.URL)) {
patch := map[string]any{}
if dimURL(p.Connection.BaseURL) != dimURL(url) {
patch["baseUrl"] = url
}
if !p.Enabled {
patch["enabled"] = true
}
if !p.Connection.CredentialConfigured || rec.Key != dimKeyHash(key) {
patch["credential"] = map[string]any{"action": "set", "value": key}
}
if len(patch) > 0 {
if err := c.update(p, patch); err != nil {
return err
}
}
rec.URL, rec.Key = url, dimKeyHash(key)
if err := writeDimState(file, st); err != nil {
return err
}
}
if !pick {
return nil
}
ref := strings.TrimPrefix(model, magpieID+"/")
var cat dimCatalog
if err := c.call("provider.refresh", map[string]any{"providerId": magpieID}, &cat); err != nil {
return err
}
i := slices.IndexFunc(cat.Models, func(m dimModel) bool { return m.ID == ref })
if i < 0 {
return fmt.Errorf("Dim's Magpie provider doesn't list %s", ref)
}
if miss := cat.Models[i].MissingLimits; len(miss) > 0 {
// Dim picks no model without both limits (provider.select's
// provider_invalid_config); magpie gives the ones it lacks
ctx, out := dimLimits(model)
e := map[string]any{}
for _, m := range miss {
switch m {
case "contextWindow":
e[m] = ctx
case "maxOutputTokens":
e[m] = out
}
}
if err := c.call("provider.models.edit", map[string]any{"providerId": magpieID, "expectedVersion": cat.Version, "modelId": ref, "edit": e}, nil); err != nil {
return err
}
}
cur, err := c.selection()
if err != nil {
return err
}
if cur == nil || cur.Provider != magpieID || cur.Model != ref {
if err := c.pick(magpieID, ref, cur); err != nil {
return err
}
}
rec.Picked = ref
return writeDimState(file, st)
}
// dimUnwire puts back what dimWire changed, where it is still as magpie
// left it: Dim's model before (Dim can't go back to none: a Dim that had
// none keeps magpie's, which says no model is available once the
// provider is off), and the Magpie provider's address, key (cleared) and
// off. A value the user changed since is theirs and stays.
func dimUnwire(dir, file string) error {
rec := readDimState(file).Dim
if rec == nil {
return nil
}
dimMu.Lock()
defer dimMu.Unlock()
c, err := dimConnect(dir, true)
if errors.Is(err, errDimAway) && proc.FindTool("dima") == "" {
return nil // Dim is gone, its settings with it
}
if err != nil {
return err
}
defer c.close()
if was := rec.Selection; rec.Picked != "" && was != nil && (was.Provider != magpieID || was.Model != rec.Picked) {
if cur, err := c.selection(); err == nil && cur != nil && cur.Provider == magpieID && cur.Model == rec.Picked {
c.pick(was.Provider, was.Model, cur) // a model since gone stays unpicked
}
}
if !rec.Wrote {
return nil
}
p, err := c.provider(magpieID)
if err != nil {
return err
}
if rec.URL == "" || dimURL(p.Connection.BaseURL) != dimURL(rec.URL) {
return nil
}
// Dim clears a key only with the provider turned off in the same patch
patch := map[string]any{"enabled": false}
if p.Connection.CredentialConfigured {
patch["credential"] = map[string]any{"action": "clear"}
}
if b := rec.BaseURL; b != "" && dimURL(b) != dimURL(p.Connection.BaseURL) {
patch["baseUrl"] = b
}
return c.update(p, patch)
}
+228
View File
@@ -0,0 +1,228 @@
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), "/") }
+16
View File
@@ -0,0 +1,16 @@
//go:build !windows
package agent
import (
"io"
"net"
"path/filepath"
"time"
)
// dimDial connects to the socket of Dim's daemon, <home>/rust/daemon.sock
// (dim-cli's connect_inner).
func dimDial(dir string) (io.ReadWriteCloser, error) {
return net.DialTimeout("unix", filepath.Join(dir, "rust", "daemon.sock"), 5*time.Second)
}
+428
View File
@@ -0,0 +1,428 @@
package agent
import (
"bufio"
"encoding/json"
"errors"
"io"
"net"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/update"
)
// fakeDim is Dim alpha's daemon as magpie talks to it: Provider records
// with versions every write is checked against, a key that is stored and
// never read back, provider.refresh listing the models the gateway would,
// and one global model pick with a version of its own, as
// crates/dim-app-server/src/provider.rs has them.
type fakeDim struct {
mu sync.Mutex
providers map[string]*fakeDimProvider
sel *dimSelection
listed []dimModel // what refresh lists for magpie
calls []string
starts int
}
type fakeDimProvider struct {
version int
enabled bool
base string
key string // "" none
models []dimModel
}
func newFakeDim() *fakeDim {
return &fakeDim{providers: map[string]*fakeDimProvider{
"magpie": {version: 1, base: dimDefault},
// one of the user's own, on the user's own key and model
"deepseek": {version: 7, enabled: true, base: "https://api.deepseek.com/v1", key: "sk-users", models: []dimModel{{ID: "deepseek-chat"}}},
}, sel: &dimSelection{Provider: "deepseek", Model: "deepseek-chat", Version: 3}}
}
// use makes f the daemon of every connection magpie opens; away is none.
func (f *fakeDim) use(t *testing.T) {
old := dimOpen
t.Cleanup(func() { dimOpen = old })
dimOpen = func(dir string, start bool) (io.ReadWriteCloser, error) {
a, b := net.Pipe()
go f.serve(b)
return a, nil
}
}
func away(t *testing.T) {
old := dimOpen
t.Cleanup(func() { dimOpen = old })
dimOpen = func(string, bool) (io.ReadWriteCloser, error) { return nil, errDimAway }
}
func (f *fakeDim) serve(c net.Conn) {
defer c.Close()
r := bufio.NewReader(c)
for {
line, err := r.ReadBytes('\n')
if err != nil {
return
}
var m struct {
ID int `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
json.Unmarshal(line, &m)
res, code := f.answer(m.Method, m.Params)
out := map[string]any{"jsonrpc": "2.0", "id": m.ID}
if code != "" {
out["error"] = map[string]any{"code": -32000, "message": code, "data": map[string]any{"appError": code}}
} else {
out["result"] = res
}
b, _ := json.Marshal(out)
if _, err := c.Write(append(b, '\n')); err != nil {
return
}
}
}
func (f *fakeDim) record(id string, p *fakeDimProvider) map[string]any {
return map[string]any{"providerId": id, "version": p.version, "enabled": p.enabled,
"connection": map[string]any{"baseUrl": p.base, "credentialConfigured": p.key != ""}}
}
func (f *fakeDim) answer(method string, raw json.RawMessage) (any, string) {
f.mu.Lock()
defer f.mu.Unlock()
f.calls = append(f.calls, method)
var p struct {
ProviderID string `json:"providerId"`
ModelID string `json:"modelId"`
ExpectedVersion *int `json:"expectedVersion"`
Patch map[string]any `json:"patch"`
Edit map[string]int `json:"edit"`
}
json.Unmarshal(raw, &p)
pr := f.providers[p.ProviderID]
switch method {
case "hello":
return map[string]any{"serverVersion": "0.1.0-alpha.24", "protocolVersion": 4}, ""
case "provider.management":
if pr == nil {
return nil, "provider_not_found"
}
return map[string]any{"providers": []any{f.record(p.ProviderID, pr)}}, ""
case "provider.update":
if pr == nil {
return nil, "provider_not_found"
}
if p.ExpectedVersion == nil || *p.ExpectedVersion != pr.version {
return nil, "provider_conflict"
}
if v, ok := p.Patch["baseUrl"].(string); ok {
pr.base = v
}
if v, ok := p.Patch["enabled"].(bool); ok {
pr.enabled = v
}
if c, ok := p.Patch["credential"].(map[string]any); ok {
switch c["action"] {
case "set":
pr.key, _ = c["value"].(string)
case "clear":
if pr.enabled {
return nil, "provider_invalid_config" // clear goes with enabled:false
}
pr.key = ""
}
}
pr.version++
return f.record(p.ProviderID, pr), ""
case "provider.refresh":
if pr == nil || pr.key == "" || !pr.enabled {
return nil, "provider_invalid_config"
}
pr.models = slices.Clone(f.listed)
pr.version++
return map[string]any{"models": pr.models, "version": pr.version}, ""
case "provider.models.edit":
if p.ExpectedVersion == nil || *p.ExpectedVersion != pr.version {
return nil, "provider_conflict"
}
for i, m := range pr.models {
if m.ID == p.ModelID {
pr.models[i].MissingLimits = slices.DeleteFunc(slices.Clone(m.MissingLimits), func(k string) bool { return p.Edit[k] > 0 })
}
}
pr.version++
return map[string]any{"models": pr.models, "version": pr.version}, ""
case "provider.selection":
return map[string]any{"selection": f.sel}, ""
case "provider.select":
have := (*int)(nil)
if f.sel != nil {
have = &f.sel.Version
}
if (have == nil) != (p.ExpectedVersion == nil) || have != nil && *have != *p.ExpectedVersion {
return nil, "provider_conflict"
}
if pr == nil {
return nil, "provider_not_found"
}
i := slices.IndexFunc(pr.models, func(m dimModel) bool { return m.ID == p.ModelID })
if i < 0 {
return nil, "provider_not_found"
}
if len(pr.models[i].MissingLimits) > 0 {
return nil, "provider_invalid_config"
}
v := 1
if f.sel != nil {
v = f.sel.Version + 1
}
f.sel = &dimSelection{Provider: p.ProviderID, Model: p.ModelID, Version: v}
return f.sel, ""
}
return nil, "method_not_found"
}
func (f *fakeDim) magpie() fakeDimProvider {
f.mu.Lock()
defer f.mu.Unlock()
return *f.providers["magpie"]
}
func dimSandbox(t *testing.T) (home string) {
home = t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("DIMCODE_HOME", "")
t.Setenv("SHELL", "/bin/zsh")
t.Setenv("ZDOTDIR", "")
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(home, ".zshrc"), []byte("export A=1\n"), 0o644)
return home
}
// Connecting Dim fills in Dim's own built-in Magpie provider through its
// daemon: magpie's key for Dim, on, the model listed (its missing limits
// given) and picked as Dim's model, so a plain dima runs on magpie. The
// user's own provider and its key are untouched, no dima function is
// added, and Disconnect puts Dim's pick and the provider back.
func TestDimFillsItsMagpieProvider(t *testing.T) {
home := dimSandbox(t)
f := newFakeDim()
f.listed = []dimModel{{ID: "deepseek/pro", MissingLimits: []string{"contextWindow", "maxOutputTokens"}}, {ID: "deepseek/flash"}}
f.use(t)
a, err := Find("dim")
if err != nil {
t.Fatal(err)
}
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
m := f.magpie()
if m.key != gateway.TokenFor("dim") || !m.enabled || m.base != dimDefault {
t.Fatalf("Dim's Magpie provider: %+v (want key %q)", m, gateway.TokenFor("dim"))
}
if f.sel == nil || f.sel.Provider != "magpie" || f.sel.Model != "deepseek/pro" {
t.Fatalf("Dim's model %+v", f.sel)
}
if !slices.Contains(f.calls, "provider.models.edit") {
t.Fatalf("no limits given: %v", f.calls)
}
if d := f.providers["deepseek"]; d.version != 7 || d.key != "sk-users" || !d.enabled || d.base != "https://api.deepseek.com/v1" {
t.Fatalf("the user's own provider changed: %+v", d)
}
if update.ShellFunctionIn("dima") != nil {
t.Fatalf("dima function added in %v", update.ShellFunctionIn("dima"))
}
if s := a.Start(); s.Bin != "dima" || s.Model != "magpie/deepseek/pro" || len(s.Env) != 0 {
t.Fatalf("start %+v", s)
}
if a.Launch() != "" || a.Typed() != "" || a.Notice() != "" {
t.Fatalf("launch %q typed %q notice %q", a.Launch(), a.Typed(), a.Notice())
}
if got := a.Field("model").Get(); got != "magpie/deepseek/pro" {
t.Fatalf("model %q", got)
}
// another model: picked, the provider's key not set again
updates := strings.Count(strings.Join(f.calls, " "), "provider.update")
if err := a.Apply("model", "magpie/deepseek/flash"); err != nil {
t.Fatal(err)
}
if f.sel.Model != "deepseek/flash" || strings.Count(strings.Join(f.calls, " "), "provider.update") != updates {
t.Fatalf("second pick: %+v %v", f.sel, f.calls)
}
if err := a.Apply("model", ""); err != nil {
t.Fatal(err)
}
if f.sel.Provider != "deepseek" || f.sel.Model != "deepseek-chat" {
t.Fatalf("Dim's model not put back: %+v", f.sel)
}
if m := f.magpie(); m.key != "" || m.enabled || m.base != dimDefault {
t.Fatalf("Dim's Magpie provider not put back: %+v", m)
}
if _, err := os.Stat(dimFile()); !os.IsNotExist(err) {
t.Fatalf("dim.json kept: %v", err)
}
if b, _ := os.ReadFile(filepath.Join(home, ".zshrc")); string(b) != "export A=1\n" {
t.Fatalf(".zshrc:\n%s", b)
}
}
// A gateway on another port than Dim's 3425 is given to the provider, and
// a later port is given to it again while it is as magpie left it.
func TestDimMagpieProviderPort(t *testing.T) {
dimSandbox(t)
t.Setenv("MAGPIE_ADDR", "127.0.0.1:4567")
f := newFakeDim()
f.sel = nil // a Dim with no model picked yet
f.listed = []dimModel{{ID: "deepseek/pro"}}
f.use(t)
a, _ := Find("dim")
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
if m := f.magpie(); m.base != "http://127.0.0.1:4567/v1" || m.key == "" {
t.Fatalf("provider %+v", m)
}
t.Setenv("MAGPIE_ADDR", "127.0.0.1:4568")
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if m := f.magpie(); m.base != "http://127.0.0.1:4568/v1" {
t.Fatalf("new port not given: %+v", m)
}
if err := a.Apply("model", ""); err != nil {
t.Fatal(err)
}
if m := f.magpie(); m.base != dimDefault || m.key != "" || m.enabled {
t.Fatalf("not put back: %+v", m)
}
}
// A key, or an address of the user's own, on Dim's Magpie provider is
// theirs: magpie picks the model on it and leaves it as it was, on
// Disconnect too.
func TestDimMagpieProviderUsersOwn(t *testing.T) {
for _, tc := range []struct {
name, base, key string
}{
{"key", dimDefault, "users-own-key"},
{"address", "http://192.168.1.9:3425/v1", ""},
} {
t.Run(tc.name, func(t *testing.T) {
dimSandbox(t)
f := newFakeDim()
mp := f.providers["magpie"]
mp.base, mp.key, mp.enabled = tc.base, tc.key, true
f.listed = []dimModel{{ID: "deepseek/pro"}}
f.use(t)
a, _ := Find("dim")
before := f.magpie()
if tc.key == "" {
// Dim lists nothing without a key: the pick fails and dima
// is started on magpie's variables instead
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
if m := f.magpie(); m.base != before.base || m.key != "" || m.version != before.version {
t.Fatalf("the user's address changed: %+v", m)
}
if a.Start().Env == nil {
t.Fatalf("no variables with no pick: %+v", a.Start())
}
} else {
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
m := f.magpie()
if m.key != tc.key || m.base != tc.base || slices.Contains(f.calls, "provider.update") {
t.Fatalf("the user's own value changed: %+v %v", m, f.calls)
}
if f.sel.Provider != "magpie" || f.sel.Model != "deepseek/pro" {
t.Fatalf("not picked: %+v", f.sel)
}
}
if err := a.Apply("model", ""); err != nil {
t.Fatal(err)
}
if m := f.magpie(); m.key != before.key || m.base != before.base || !m.enabled || slices.Contains(f.calls, "provider.update") {
t.Fatalf("Disconnect changed the user's own: %+v %v", m, f.calls)
}
if f.sel.Provider != "deepseek" {
t.Fatalf("Dim's model not put back: %+v", f.sel)
}
})
}
}
// A Dim connected before magpie filled its provider in (its dima function
// in the user's shells) is moved onto the provider by a Sync while its
// daemon runs, and the function goes; with no daemon running, the
// function stays and nothing is started.
func TestDimSyncMovesToProvider(t *testing.T) {
home := dimSandbox(t)
away(t)
a, _ := Find("dim")
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
zshrc := filepath.Join(home, ".zshrc")
if b, _ := os.ReadFile(zshrc); !strings.Contains(string(b), "dima() {") {
t.Skipf("no dima function on this system: %s", b)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(zshrc); !strings.Contains(string(b), "dima() {") {
t.Fatalf("function gone with no daemon: %s", b)
}
f := newFakeDim()
f.listed = []dimModel{{ID: "deepseek/pro"}}
f.use(t)
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if f.sel.Provider != "magpie" || f.magpie().key == "" {
t.Fatalf("not moved: %+v %+v", f.sel, f.magpie())
}
if b, _ := os.ReadFile(zshrc); string(b) != "export A=1\n" {
t.Fatalf("function kept:\n%s", b)
}
}
// Dim gone (no daemon, no dima) doesn't keep Disconnect from finishing.
func TestDimDisconnectWithDimGone(t *testing.T) {
dimSandbox(t)
t.Setenv("PATH", t.TempDir())
f := newFakeDim()
f.listed = []dimModel{{ID: "deepseek/pro"}}
f.use(t)
a, _ := Find("dim")
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
old := dimOpen
dimOpen = func(string, bool) (io.ReadWriteCloser, error) { return nil, errors.Join(errDimAway, os.ErrNotExist) }
defer func() { dimOpen = old }()
if err := a.Apply("model", ""); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(dimFile()); !os.IsNotExist(err) {
t.Fatalf("dim.json kept: %v", err)
}
}
+107
View File
@@ -0,0 +1,107 @@
package agent
import (
"bufio"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/proc"
)
// dimPipe is the pipe of the daemon of Dim's native home, as dim-cli's
// connect_inner names it: dim-rust- and the first 32 hex digits of
// sha256("dimcode:" + the home as Rust's canonicalize gives it, \\?\C:\…).
func dimPipe(native string) (string, error) {
p, err := filepath.Abs(native)
if err != nil {
return "", err
}
if p, err = filepath.EvalSymlinks(p); err != nil {
return "", err
}
if rest, ok := strings.CutPrefix(p, `\\`); ok {
p = `\\?\UNC\` + rest
} else {
p = `\\?\` + p
}
sum := sha256.Sum256([]byte("dimcode:" + p))
return `\\.\pipe\dim-rust-` + hex.EncodeToString(sum[:])[:32], nil
}
// dimBridge is the pipe bridge process, its stdout and stdin the
// connection.
type dimBridge struct {
io.Reader
in io.WriteCloser
cmd *exec.Cmd
}
func (b *dimBridge) Write(p []byte) (int, error) { return b.in.Write(p) }
func (b *dimBridge) Close() error {
b.in.Close()
b.cmd.Process.Kill()
b.cmd.Wait()
return nil
}
// dimDial starts Dim's own bridge to its daemon's pipe (dim-client's
// Client::open): the server binary Dim links into its native home, run
// as `app-server --connect-pipe <pipe>`, which says {"status":"ready"}
// on its stderr once the pipe is authenticated.
func dimDial(dir string) (io.ReadWriteCloser, error) {
native := filepath.Join(dir, "rust")
pipe, err := dimPipe(native)
if err != nil {
return nil, err
}
server := filepath.Join(native, "dimcode-server.exe")
if _, err := os.Stat(server); err != nil {
return nil, err
}
cmd := proc.Command(server, "app-server", "--connect-pipe", pipe)
in, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
out, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
errs, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
b := &dimBridge{Reader: out, in: in, cmd: cmd}
ready := make(chan string, 1)
go func() {
line, _ := bufio.NewReader(errs).ReadString('\n')
ready <- line
io.Copy(io.Discard, errs)
}()
var line string
select {
case line = <-ready:
case <-time.After(5 * time.Second):
}
var r struct {
Status string `json:"status"`
Code string `json:"code"`
}
if json.Unmarshal([]byte(line), &r) != nil || r.Status != "ready" {
b.Close()
return nil, errors.New("Dim's pipe bridge isn't ready: " + strings.TrimSpace(line))
}
return b, nil
}
+5 -3
View File
@@ -13,10 +13,12 @@ import (
"github.com/yetone/magpie/internal/update"
)
// Dim alpha is started on magpie through the variables Dim documents for
// an OpenAI-compatible endpoint; the model is in magpie's own file, and
// nothing of Dim's (its home, settings, database or account) is written.
// With no Dim daemon to reach, Dim alpha is started on magpie through the
// variables Dim documents for an OpenAI-compatible endpoint; the model is
// in magpie's own file, and nothing of Dim's (its home, settings,
// database or account) is written.
func TestDim(t *testing.T) {
away(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)