The Memory tab gets a second row under Learn from conversations. It is
off by default. Switched on, the first tidy is due at the next 03:00.
Tidy now runs one at once, and Undo puts the last one back. While
distillation is off, the row has its own model picker; both rows share
one model.
Routes: POST /api/memory/dream {on}, /dream/run and /dream/undo.
GET /api/memory/distill carries "dreaming", so a tidy no longer shows
as conversations being read.
The prompt's stale rule is narrower. On the first real run it set aside
two decisions because "the work is done". Now only a note that later
notes contradict, one past its date, or one about a finished one-off
task is stale; a decision, direction or preference stays.
docs/subsystems/memory.md gets a Dreaming section.
Real run: a sandbox memory.json of 62 real distilled memories, 12 active
and one each user-written and pinned, with auto/claude-haiku-5-5 through
the live gateway.
- Before the prompt change: 12 changes in 48s, 10 merges and 2 set aside.
Both set-aside notes were decisions.
- After: 12 merges in 46s, none set aside. Each merge joins real
duplicates (three ~/.codex/sessions cleanup rules into one, the
TestFlight 1.66/1.68 pair). One went into the fixed memory, whose text
was kept word for word.
- Undo: 25 restored. memory.json's ids and statuses equal the backup
taken before the run, and every merged memory is gone.
Broken by hand, each red:
- Undo not reloading the list: library-memory 22 failed.
- Ignoring DreamSince: TestDreamsOnceANight.
- A plan applied after an error: TestDreamFailureChangesNothing.
- Tidy's fixed guard and Untidy's status check: their memory tests.
Run on mote at this tree:
- go test internal/memory, memdistill, library: ok.
- internal/gui -run 'Distill|Dream|I18n|Budget': ok.
- library-memory.test.cjs: 22/22 in both engines.
- i18n-keys and i18n-en-no-cjk: 4/4 each.
- go vet (darwin), GOOS=linux -tags nogui, GOOS=windows: ok.
Not run yet: the full suite at this head.
221 lines
6.2 KiB
Go
221 lines
6.2 KiB
Go
package gui
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/memdistill"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// distillView is the Memory tab's "learn from conversations" row: the
|
|
// switch, the model picked and the automatic one, the models to pick
|
|
// from, the last run, and whether one is going.
|
|
type distillView struct {
|
|
memdistill.State
|
|
Auto string `json:"auto"`
|
|
Models []modelRef `json:"models"`
|
|
Running bool `json:"running"`
|
|
// Dreaming is a tidy going (Running is conversations being read)
|
|
Dreaming bool `json:"dreaming"`
|
|
}
|
|
|
|
func readDistill() (*distillView, error) {
|
|
st, err := memdistill.Load()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
st.Done = nil // the marks are the run's, not the page's
|
|
v := &distillView{State: st, Auto: distillAuto(), Models: []modelRef{}, Running: memdistill.Running() && !memdistill.Dreaming(), Dreaming: memdistill.Dreaming()}
|
|
for _, e := range provider.Served() {
|
|
if e.Group != "" || e.Provider.Ready() && !e.Provider.DecideOnly() {
|
|
m := modelRef{ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon}
|
|
if e.Group != "" {
|
|
m.Provider, m.PName = "", e.Group
|
|
}
|
|
v.Models = append(v.Models, m)
|
|
}
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
// distillAuto is the model conversations are read with when none is
|
|
// picked: the small model magpie picks to describe images, one of the
|
|
// user's own subscriptions first (gateway.AutoVision).
|
|
func distillAuto() string { return gateway.AutoVision() }
|
|
|
|
// distillComplete sends one request through the gateway this process
|
|
// serves, as any agent's goes: routed, masked and counted, under the
|
|
// memory agent's name.
|
|
func distillComplete(ctx context.Context, model, system, user string) (string, error) {
|
|
gw := served.Load()
|
|
if gw == nil {
|
|
return "", errors.New("the gateway isn't served by this magpie")
|
|
}
|
|
body, err := json.Marshal(map[string]any{
|
|
"model": model, "max_tokens": 4096, "system": system,
|
|
"messages": []map[string]any{{"role": "user", "content": user}},
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, "POST", gateway.URL()+"/v1/messages", strings.NewReader(string(body)))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.RemoteAddr = "127.0.0.1:0"
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("anthropic-version", "2023-06-01")
|
|
req.Header.Set("x-api-key", gateway.TokenFor(memdistill.Agent))
|
|
rec := httptest.NewRecorder()
|
|
gw.Handler().ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
msg := strings.TrimSpace(rec.Body.String())
|
|
var e struct {
|
|
Error struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
if json.Unmarshal(rec.Body.Bytes(), &e) == nil && e.Error.Message != "" {
|
|
msg = e.Error.Message
|
|
}
|
|
if len(msg) > 300 {
|
|
msg = msg[:300] + "…"
|
|
}
|
|
return "", fmt.Errorf("%d: %s", rec.Code, msg)
|
|
}
|
|
var out struct {
|
|
Content []struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
} `json:"content"`
|
|
}
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
|
return "", fmt.Errorf("a reply that isn't a message: %w", err)
|
|
}
|
|
var b strings.Builder
|
|
for _, c := range out.Content {
|
|
if c.Type == "text" {
|
|
b.WriteString(c.Text)
|
|
}
|
|
}
|
|
return b.String(), nil
|
|
}
|
|
|
|
// keepDistilling reads conversations into memory while the backend runs:
|
|
// a few minutes after start, then every hour.
|
|
func keepDistilling(ctx context.Context) {
|
|
memdistill.Keep(ctx, 5*time.Minute, time.Hour, distillAuto, distillComplete)
|
|
}
|
|
|
|
// distillNow starts a run in the background, for the switch turned on
|
|
// and the Read now button; the tab polls while it runs.
|
|
var distillNow = func() {
|
|
go memdistill.Run(backendCtx, distillAuto(), distillComplete)
|
|
}
|
|
|
|
func memoryDistillRoutes(mux *http.ServeMux) {
|
|
mux.HandleFunc("GET /api/memory/distill", func(rw http.ResponseWriter, r *http.Request) {
|
|
v, err := readDistill()
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, v)
|
|
})
|
|
// {on, model}: switched or a model picked; switched on, it reads at once
|
|
mux.HandleFunc("POST /api/memory/distill", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
On bool `json:"on"`
|
|
Model string `json:"model"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if in.Model != "" && !strings.Contains(in.Model, "/") {
|
|
fail(rw, fmt.Errorf("a model's id such as codex/gpt-5.5, not %q", in.Model))
|
|
return
|
|
}
|
|
was, _ := memdistill.Load()
|
|
if _, err := memdistill.Set(in.On, in.Model); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if in.On && (!was.On || was.Model != in.Model) {
|
|
distillNow()
|
|
}
|
|
v, err := readDistill()
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
v.Running = v.Running || in.On && (!was.On || was.Model != in.Model)
|
|
writeJSON(rw, v)
|
|
})
|
|
mux.HandleFunc("POST /api/memory/distill/run", func(rw http.ResponseWriter, r *http.Request) {
|
|
distillNow()
|
|
v, err := readDistill()
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
v.Running = true
|
|
writeJSON(rw, v)
|
|
})
|
|
// {on}: the nightly tidy switched; the first is due at the next night
|
|
mux.HandleFunc("POST /api/memory/dream", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
On bool `json:"on"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if _, err := memdistill.SetDream(in.On); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
v, err := readDistill()
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, v)
|
|
})
|
|
mux.HandleFunc("POST /api/memory/dream/run", func(rw http.ResponseWriter, r *http.Request) {
|
|
dreamNow()
|
|
v, err := readDistill()
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
v.Dreaming, v.Running = true, false
|
|
writeJSON(rw, v)
|
|
})
|
|
mux.HandleFunc("POST /api/memory/dream/undo", func(rw http.ResponseWriter, r *http.Request) {
|
|
if _, err := memdistill.Undo(); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
v, err := readDistill()
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, v)
|
|
})
|
|
}
|
|
|
|
// dreamNow tidies memory in the background, for the Tidy now button.
|
|
var dreamNow = func() {
|
|
go memdistill.Dream(backendCtx, distillAuto(), distillComplete)
|
|
}
|