diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index 3095dca9a..cf21f46aa 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -104,11 +104,21 @@ failed. The tab is in [plugins/library/client.js](../../internal/gui/assets/plug `internal/memdistill` reads finished conversations into candidate memories. It is off until switched on under Memory → Learn from conversations; switched on, it looks back seven days (`Back`) and no -further (`State.Since`). +further (`State.Since`), unless a range is picked. +- How far back (`State.Days`, `SetRange`): 7, 30, 90 or 365 days, or All + (`memdistill.All`, -1); 0 is the 7-day default, so a state from before + the picker keeps its own `Since` until a range is picked + (`TestRangePicked`). Every range reads from the latest 400 conversations + (`Listed`) at 10 an hour (`PerRun`), so All costs at most ~240 requests + a day until the backlog is read; the picker's All says so. - State is `distill.json` beside `memory.json` (`memdistill.Path`): - the switch, the model, the conversations done (kept 30 days), and the - last run's time, counts and error. It is written through temp-and-rename + the switch, the model, the reasoning level, the range, the + conversations done, and the last run's time, counts and error. A + conversation's mark is dropped once it is before `Since`, or older + than 30 days and past the oldest conversation listed; before that a + conversation older than 30 days was read again every hour + (`TestOldConversationReadOnce`). It is written through temp-and-rename under a file lock; an unreadable file runs nothing (`TestUnreadableStateRunsNothing`). - `Keep` runs 5 minutes after the GUI backend starts, then hourly @@ -126,7 +136,11 @@ further (`State.Since`). (`distillComplete`), as `x-api-key: magpie-memory`, so it is routed, masked and counted in Usage under the agent `memory` (`TestDistillCompleteThroughGateway`). With no model picked it uses - `gateway.AutoVision()`. + `gateway.AutoVision()`. A reasoning level picked (`State.Effort`, + `SetEffort`) is fitted to the model's levels and sent as thinking with + room for it (`gateway.WithSideEffort`, as Vision and Searcher do); + Default sends none. Run and the nightly tidy both use it + (`TestEffortPicked`). - Each proposal is saved as an inferred candidate (To review) with its conversation as the source and the quote it rests on; at most 5 per conversation. A proposal whose quote isn't in what the user wrote @@ -137,7 +151,9 @@ further (`State.Since`). leaves the conversation to be read again next time (`TestFailureAndCap`). - Routes: `GET /api/memory/distill`, `POST /api/memory/distill` - `{on, model}` (switching on, or a new model, reads at once) and + `{on, model, effort?, days?}` (switching on, a new model, or a longer + range reads at once; a bad level or range is a 400, + `TestDistillRangeAndEffortRoutes`) and `POST /api/memory/distill/run`. The row polls every 2s while a run goes and reloads the memories when it ends. diff --git a/internal/gateway/side_effort.go b/internal/gateway/side_effort.go index af6a06b5d..0d2bb98d1 100644 --- a/internal/gateway/side_effort.go +++ b/internal/gateway/side_effort.go @@ -117,3 +117,29 @@ func replyRoom(usual int, effort string) int { } return usual + budgetOf(effortOf(effort)) } + +// SideEffort is the level a call magpie makes on its own with model is +// asked at when want is picked for it: want fitted to the model's own +// levels, "" when none is picked or its levels aren't known. +func SideEffort(model, want string) string { return sideEffort(model, want) } + +// WithSideEffort is an Anthropic Messages request magpie makes on its own +// with model (memory's reading of conversations and its nightly tidy) +// asked to reason at want, fitted to the model's levels as SideEffort +// fits it, as a group's member fixed at a level is asked (withFixedEffort): +// none turns thinking off, any other level asks for it, with room above +// the reply's usual limit to think in (replyRoom). Nothing picked, or a +// model whose levels aren't known: the body as it was. +func WithSideEffort(body []byte, model, want string) []byte { + e := sideEffort(model, want) + if e == "" { + return body + } + var v struct { + MaxTokens int `json:"max_tokens"` + } + if decodeJSON(body, &v) == nil && v.MaxTokens > 0 { + body = withFields(body, map[string]any{"max_tokens": replyRoom(v.MaxTokens, e)}) + } + return withFixedEffort(provider.Anthropic, body, e) +} diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 3c100d296..a71532307 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -1116,6 +1116,29 @@ magpie.plugin("library", (ctx) => { d.model || "", (v) => distChange("memory/distill", { on: d.on, model: v }), "Model", "", "left", false, d.models.length > 8 ? "Search models" : "")); return pick; } + // the reasoning level the model reads and tidies at, when its levels + // are known: Default sends none (RealZeroP27 on X) + function memEffortPick(d) { + if (!d.efforts?.length) return null; + const shown = d.effort ? d.effortNow || d.effort : ""; + const b = menuButton(shown ? t(shown) : t("Default"), "lib-disteffort", () => openProtoMenu(b, + [{ v: "", name: "Default", note: "The model's own" }, ...d.efforts.map((l) => ({ v: l, name: l, note: "" }))], + shown, (v) => v !== (d.effort || "") && distChange("memory/distill", { on: d.on, model: d.model || "", effort: v }), "Thinking")); + b.prepend(effortIcon({ options: d.efforts.map((l) => ({ value: l })), value: shown })); + b.title = t("How hard this model thinks"); + return b; + } + // how far back conversations are read: 7 days unless picked, All the + // latest 400 (memdistill.Listed), PerRun an hour like any other + const rangeName = (n) => n === -1 ? t("All") : n === 365 ? t("1 year") : t("{n} days", { n }); + function memRangePick(d) { + const cur = d.days || 7; + const b = menuButton(rangeName(cur), "lib-distrange", () => openProtoMenu(b, + (d.ranges || [7, 30, 90, 365, -1]).map((n) => ({ v: String(n), name: rangeName(n), literalName: true, note: n === -1 ? "The latest 400 conversations, read 10 an hour" : "" })), + String(cur), (v) => +v !== cur && distChange("memory/distill", { on: d.on, model: d.model || "", days: +v }), "How far back it reads")); + b.title = t("How far back it reads"); + return b; + } // Conversations read into memory (internal/memdistill): what the // agents' finished sessions say worth keeping waits under To review. // Off until switched on; the model is the automatic one or one picked. @@ -1133,7 +1156,7 @@ magpie.plugin("library", (ctx) => { w.append(el("div", "sub" + (err ? " err" : ""), line)); const acts = el("div", "lib-acts"); if (d.on) { - acts.append(memModelPick(d)); + acts.append(memModelPick(d), ...[memEffortPick(d)].filter(Boolean), memRangePick(d)); if (!d.running) acts.append(button(t("Read now"), "action lib-distnow", () => distChange("memory/distill/run", {}))); } acts.append(toggle(d.on, t("Learn from conversations"), (on) => distChange("memory/distill", { on, model: d.model || "" }))); @@ -1160,7 +1183,7 @@ magpie.plugin("library", (ctx) => { w.append(el("div", "sub" + (err ? " err" : ""), line)); const acts = el("div", "lib-acts"); if (ch.length && !d.undone && !d.dreaming) acts.append(button(t("Undo"), "action lib-dreamundo", () => distChange("memory/dream/undo", {}, true))); - if (d.dream && !d.on) acts.append(memModelPick(d)); + if (d.dream && !d.on) acts.append(memModelPick(d), ...[memEffortPick(d)].filter(Boolean)); if (d.dream && !d.dreaming && !d.running) acts.append(button(t("Tidy now"), "action lib-dreamnow", () => distChange("memory/dream/run", {}))); acts.append(toggle(d.dream, t("Tidy up every night"), (on) => distChange("memory/dream", { on }))); r.append(glyph(GLYPH.backup), w, acts); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index c3ff23b59..c530a710f 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,10 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "The model's own": "模型自己的默认", + "1 year": "1 年", + "How far back it reads": "读取多久以前的对话", + "The latest 400 conversations, read 10 an hour": "最近 400 个对话,每小时读 10 个", "Turn {name} on or off": "开启或关闭 {name}", "{name} is on again": "{name} 已重新开启", "{name} is off; its settings are kept": "{name} 已关闭,设置都已保留", @@ -900,6 +904,10 @@ magpie.strings({ "billion-context is installed — switch it on for your agents below": "billion-context 已安装 — 在下方为你的 Agent 打开它", }, "zh-TW": { + "The model's own": "模型自己的預設", + "1 year": "1 年", + "How far back it reads": "讀取多久以前的對話", + "The latest 400 conversations, read 10 an hour": "最近 400 個對話,每小時讀 10 個", "Turn {name} on or off": "開啟或關閉 {name}", "{name} is on again": "{name} 已重新開啟", "{name} is off; its settings are kept": "{name} 已關閉,設定都已保留", @@ -1798,6 +1806,10 @@ magpie.strings({ "billion-context is installed — switch it on for your agents below": "billion-context 已安裝 — 在下方為你的 Agent 開啟它", }, ja: { + "The model's own": "モデル自身の既定", + "1 year": "1 年", + "How far back it reads": "どこまで遡って読むか", + "The latest 400 conversations, read 10 an hour": "最新の 400 件の会話を 1 時間に 10 件ずつ読みます", "Turn {name} on or off": "{name} のオン/オフ", "{name} is on again": "{name} を再びオンにしました", "{name} is off; its settings are kept": "{name} をオフにしました。設定は残っています", @@ -2696,6 +2708,10 @@ magpie.strings({ "billion-context is installed — switch it on for your agents below": "billion-context をインストールしました — 下でエージェントごとにオンにしてください", }, de: { + "The model's own": "Die Vorgabe des Modells", + "1 year": "1 Jahr", + "How far back it reads": "Wie weit zurück gelesen wird", + "The latest 400 conversations, read 10 an hour": "Die neuesten 400 Unterhaltungen, 10 pro Stunde", "Turn {name} on or off": "{name} ein- oder ausschalten", "{name} is on again": "{name} ist wieder an", "{name} is off; its settings are kept": "{name} ist aus; seine Einstellungen bleiben", diff --git a/internal/gui/memory_distill.go b/internal/gui/memory_distill.go index d8bbff38c..d5ddb2757 100644 --- a/internal/gui/memory_distill.go +++ b/internal/gui/memory_distill.go @@ -25,6 +25,13 @@ type distillView struct { Running bool `json:"running"` // Dreaming is a tidy going (Running is conversations being read) Dreaming bool `json:"dreaming"` + // Efforts are the reasoning levels of the model in use (picked or + // automatic), weakest first, none when they aren't known; EffortNow + // the picked Effort fitted to them + Efforts []string `json:"efforts,omitempty"` + EffortNow string `json:"effortNow,omitempty"` + // Ranges are the ranges, in days, reading can look back (All -1) + Ranges []int `json:"ranges"` } func readDistill() (*distillView, error) { @@ -33,7 +40,14 @@ func readDistill() (*distillView, error) { 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()} + v := &distillView{State: st, Auto: distillAuto(), Models: []modelRef{}, Running: memdistill.Running() && !memdistill.Dreaming(), Dreaming: memdistill.Dreaming(), Ranges: memdistill.Ranges} + inUse := st.Model + if inUse == "" { + inUse = v.Auto + } + if inUse != "" { + v.Efforts, v.EffortNow = gateway.ModelEfforts(inUse), gateway.SideEffort(inUse, st.Effort) + } 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} @@ -53,8 +67,9 @@ 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) { +// memory agent's name, asked to reason at effort when one is picked +// (gateway.WithSideEffort; RealZeroP27 on X). +func distillComplete(ctx context.Context, model, effort, system, user string) (string, error) { gw := served.Load() if gw == nil { return "", errors.New("the gateway isn't served by this magpie") @@ -66,6 +81,7 @@ func distillComplete(ctx context.Context, model, system, user string) (string, e if err != nil { return "", err } + body = gateway.WithSideEffort(body, model, effort) req, err := http.NewRequestWithContext(ctx, "POST", gateway.URL()+"/v1/messages", strings.NewReader(string(body))) if err != nil { return "", err @@ -130,11 +146,16 @@ func memoryDistillRoutes(mux *http.ServeMux) { } writeJSON(rw, v) }) - // {on, model}: switched or a model picked; switched on, it reads at once + // {on, model, effort?, days?}: switched or a model picked; switched + // on, it reads at once. effort and days, when sent, pick the + // reasoning level and how far back it reads; a longer range reads at + // once too mux.HandleFunc("POST /api/memory/distill", func(rw http.ResponseWriter, r *http.Request) { var in struct { - On bool `json:"on"` - Model string `json:"model"` + On bool `json:"on"` + Model string `json:"model"` + Effort *string `json:"effort"` + Days *int `json:"days"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) @@ -145,11 +166,27 @@ func memoryDistillRoutes(mux *http.ServeMux) { return } was, _ := memdistill.Load() + if in.Effort != nil { + if _, err := memdistill.SetEffort(*in.Effort); err != nil { + fail(rw, err) + return + } + } + longer := false + if in.Days != nil { + st, err := memdistill.SetRange(*in.Days) + if err != nil { + fail(rw, err) + return + } + longer = st.Since.Before(was.Since) + } if _, err := memdistill.Set(in.On, in.Model); err != nil { fail(rw, err) return } - if in.On && (!was.On || was.Model != in.Model) { + read := in.On && (!was.On || was.Model != in.Model || longer) + if read { distillNow() } v, err := readDistill() @@ -157,7 +194,7 @@ func memoryDistillRoutes(mux *http.ServeMux) { fail(rw, err) return } - v.Running = v.Running || in.On && (!was.On || was.Model != in.Model) + v.Running = v.Running || read writeJSON(rw, v) }) mux.HandleFunc("POST /api/memory/distill/run", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/memory_distill_test.go b/internal/gui/memory_distill_test.go index 4b268565a..3803ae201 100644 --- a/internal/gui/memory_distill_test.go +++ b/internal/gui/memory_distill_test.go @@ -9,6 +9,8 @@ import ( "strings" "testing" + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/memdistill" "github.com/yetone/magpie/internal/memory" @@ -42,13 +44,13 @@ func TestDistillCompleteThroughGateway(t *testing.T) { } prev := served.Swap(nil) t.Cleanup(func() { served.Store(prev) }) - if _, err := distillComplete(context.Background(), "dt/m1", "sys", "conv"); err == nil || !strings.Contains(err.Error(), "isn't served") { + if _, err := distillComplete(context.Background(), "dt/m1", "", "sys", "conv"); err == nil || !strings.Contains(err.Error(), "isn't served") { t.Fatalf("no gateway: %v", err) } gw := gateway.New() served.Store(gw) - reply, err := distillComplete(context.Background(), "dt/m1", "Write down what lasts.", "Conversation:\n\nUser: use tabs") + reply, err := distillComplete(context.Background(), "dt/m1", "", "Write down what lasts.", "Conversation:\n\nUser: use tabs") if err != nil || reply != `[{"text":"Likes tabs"}]` { t.Fatalf("%q %v", reply, err) } @@ -61,8 +63,35 @@ func TestDistillCompleteThroughGateway(t *testing.T) { t.Fatalf("counted as %+v", rs) } + // the gateway's own choice for a model it knows no levels of, as before + if gjson.GetBytes(b, "thinking.type").String() == "enabled" || got["max_tokens"] != float64(4096) { + t.Fatalf("no level picked, but sent %s", b) + } + + // a level picked (RealZeroP27 on X) is asked for, fitted to the + // model's own, with room to think above the reply; none turns + // thinking off; one whose levels aren't known is sent as before + if err := catalog.SaveLive("dt", up.URL, []catalog.Model{{ID: "m1", Efforts: []string{"none", "low", "medium", "high"}}}); err != nil { + t.Fatal(err) + } + if lv := gateway.ModelEfforts("dt/m1"); len(lv) != 4 { + t.Fatalf("levels %q", lv) + } + if _, err := distillComplete(context.Background(), "dt/m1", "xhigh", "s", "u"); err != nil { + t.Fatal(err) + } + if b, _ := json.Marshal(got); gjson.GetBytes(b, "thinking.type").String() != "enabled" || gjson.GetBytes(b, "thinking.budget_tokens").Int() != 24000 || gjson.GetBytes(b, "max_tokens").Int() != 4096+24000 { + t.Fatalf("high sent %s", b) + } + if _, err := distillComplete(context.Background(), "dt/m1", "none", "s", "u"); err != nil { + t.Fatal(err) + } + if b, _ := json.Marshal(got); gjson.GetBytes(b, "thinking.type").String() != "disabled" || gjson.GetBytes(b, "max_tokens").Int() != 4096 { + t.Fatalf("none sent %s", b) + } + refuse = true - if _, err := distillComplete(context.Background(), "dt/m1", "s", "u"); err == nil || !strings.Contains(err.Error(), "model not allowed on this plan") { + if _, err := distillComplete(context.Background(), "dt/m1", "", "s", "u"); err == nil || !strings.Contains(err.Error(), "model not allowed on this plan") { t.Fatalf("refused: %v", err) } } @@ -96,7 +125,7 @@ func TestDreamRoutes(t *testing.T) { if _, _, err := memory.Save(memory.Input{Text: &text2, Kind: &kind, Scope: &scope, Status: &st}, memory.FromInferred, nil, nil); err != nil { t.Fatal(err) } - cs, err := memdistill.Dream(context.Background(), "a/m", func(context.Context, string, string, string) (string, error) { + cs, err := memdistill.Dream(context.Background(), "a/m", func(context.Context, string, string, string, string) (string, error) { return `{"stale":[{"id":"n1"}]}`, nil }) if err != nil || len(cs) != 1 { @@ -115,3 +144,47 @@ func TestDreamRoutes(t *testing.T) { t.Fatalf("off: %+v", v.State) } } + +// The row's route picks how far back reading looks and the level its +// model is asked at, each only when sent: the switch's own {on, model} +// keeps both. A longer range reads at once; a range or level not +// offered is refused, and the view offers the ranges and the model's +// levels. +func TestDistillRangeAndEffortRoutes(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + reads := 0 + prev := distillNow + distillNow = func() { reads++ } + t.Cleanup(func() { distillNow = prev }) + mux := http.NewServeMux() + memoryDistillRoutes(mux) + post := func(body string) (int, distillView) { + t.Helper() + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/memory/distill", strings.NewReader(body))) + var v distillView + json.Unmarshal(rec.Body.Bytes(), &v) + return rec.Code, v + } + if _, v := post(`{"on":true,"model":""}`); !v.On || v.Days != 0 || v.Effort != "" || reads != 1 || len(v.Ranges) != 5 { + t.Fatalf("on: %+v %d", v, reads) + } + if _, v := post(`{"on":true,"model":"","days":90,"effort":"high"}`); v.Days != 90 || v.Effort != "high" || reads != 2 || !v.Running { + t.Fatalf("90 days, high: %+v %d", v.State, reads) + } + if _, v := post(`{"on":true,"model":""}`); v.Days != 90 || v.Effort != "high" || reads != 2 { + t.Fatalf("the switch's body changed them: %+v %d", v.State, reads) + } + if _, v := post(`{"on":true,"model":"","days":30}`); v.Days != 30 || reads != 2 { + t.Fatalf("a shorter range read again: %+v %d", v.State, reads) + } + if _, v := post(`{"on":true,"model":"","effort":""}`); v.Effort != "" { + t.Fatalf("default: %+v", v.State) + } + for _, bad := range []string{`{"on":true,"days":12}`, `{"on":true,"effort":"hard"}`} { + if code, _ := post(bad); code == 200 { + t.Fatalf("%s taken", bad) + } + } +} diff --git a/internal/gui/tests/library-memory.test.cjs b/internal/gui/tests/library-memory.test.cjs index 7a3240997..7989f0e84 100644 --- a/internal/gui/tests/library-memory.test.cjs +++ b/internal/gui/tests/library-memory.test.cjs @@ -40,6 +40,7 @@ function memories() { function distill() { return { on: false, model: "", auto: "dt/small", running: false, gets: 0, + efforts: ["low", "medium", "high"], effort: "", effortNow: "", days: 0, ranges: [7, 30, 90, 365, -1], models: [{ id: "dt/small", name: "Small", providerName: "DT" }, { id: "dt/m1", name: "Model One", providerName: "DT" }], }; } @@ -75,6 +76,8 @@ function server(lang, state, sent, dist) { const body = route.request().postDataJSON(); sent.push({ path: url.pathname, body }); if (url.pathname === "/api/memory/distill/run") Object.assign(dist, { running: false, error: "429: too many requests", last: new Date().toISOString() }); + else if ("effort" in body) Object.assign(dist, { effort: body.effort, effortNow: body.effort }); + else if ("days" in body) Object.assign(dist, { days: body.days === 7 ? 0 : body.days, running: body.days === -1 || body.days > (dist.days || 7), gets: 0 }); else Object.assign(dist, { on: body.on, model: body.model, running: body.on, gets: 0, error: "" }); } else if (dist.running && ++dist.gets > 1) { // the run ends: it read three and proposed one @@ -252,6 +255,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await drow.locator(".lib-distmodel").textContent(), /Small/); assert.equal(await trow.locator(".lib-distmodel").count(), 0, "a model picked on both rows"); assert.equal(await drow.locator(".lib-distnow").count(), 0, "Read now while reading"); + assert.equal(await drow.locator(".lib-disteffort").count(), 1, "no reasoning level"); + const rangeShown = await drow.locator(".lib-distrange").textContent(); + assert.match(rangeShown, /7/); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "the row scrolls sideways"); const card = await page.locator(`${view} .lib-memcard`).boundingBox(); for (const b of await drow.locator(".lib-acts > *").all()) { @@ -273,6 +279,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/distill").body, { on: true, model: "dt/m1" }); assert.equal(await page.locator(`${view} select`).count(), 0, "a native select"); await drow.locator(".lib-distnow").waitFor({ timeout: 8000 }); + // a reasoning level picked: the model's own levels, Default first + assert.equal(await drow.locator(".lib-disteffort .effort-ic").count(), 1); + await drow.locator(".lib-disteffort").click(); + assert.equal(await page.locator(".proto-menu .pm-item").count(), 4); + await page.locator(".proto-menu .pm-item").nth(3).click(); + await page.waitForFunction(() => document.querySelector("#view-library .lib-disteffort")?.textContent.trim() !== "" && !document.querySelector(".proto-menu")); + assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/distill").body, { on: true, model: "dt/m1", effort: "high" }); + // how far back: 7 days unless picked; All reads at once + await drow.locator(".lib-distrange").click(); + assert.equal(await page.locator(".proto-menu .pm-item").count(), 5); + await page.locator(".proto-menu .pm-item").nth(4).click(); + assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/distill").body, { on: true, model: "dt/m1", days: -1 }); + await page.waitForFunction((was) => document.querySelector("#view-library .lib-distrange")?.textContent !== was, rangeShown); + await drow.locator(".lib-distnow").waitFor({ timeout: 8000 }); // a run that stopped says why await drow.locator(".lib-distnow").click(); await drow.locator(".sub.err").waitFor(); diff --git a/internal/memdistill/dream.go b/internal/memdistill/dream.go index 8bca9c8ca..9c640f81f 100644 --- a/internal/memdistill/dream.go +++ b/internal/memdistill/dream.go @@ -87,7 +87,7 @@ func Dream(ctx context.Context, auto string, complete Complete) ([]memory.Change if model == "" { model = auto } - plan, err := ask(ctx, model, complete) + plan, err := ask(ctx, model, st.Effort, complete) var cs []memory.Change if err == nil { plan.Before = now().Add(-Unreviewed) @@ -125,7 +125,7 @@ func Undo() (int, error) { // ask shows the model each scope's memories that could change, perAsk at // a time, and gathers what it names. A scope with fewer than two, or with // only the user's own, isn't sent. -func ask(ctx context.Context, model string, complete Complete) (memory.Plan, error) { +func ask(ctx context.Context, model, effort string, complete Complete) (memory.Plan, error) { var p memory.Plan all, _, err := memory.All() if err != nil { @@ -164,7 +164,7 @@ func ask(ctx context.Context, model string, complete Complete) (memory.Plan, err if ctx.Err() != nil { return p, ctx.Err() } - reply, err := complete(ctx, model, dreamPrompt, listing(chunk)) + reply, err := complete(ctx, model, effort, dreamPrompt, listing(chunk)) if err != nil { return p, fmt.Errorf("%s: %w", model, err) } diff --git a/internal/memdistill/dream_test.go b/internal/memdistill/dream_test.go index 4c5581e79..7eb72d76c 100644 --- a/internal/memdistill/dream_test.go +++ b/internal/memdistill/dream_test.go @@ -45,7 +45,7 @@ func TestDreamTidiesAndUndoes(t *testing.T) { u := note(t, "Use tabs", memory.Global, memory.FromUser) p := note(t, "Alone in its project", "project:github.com/a/b", memory.FromInferred) var asked []string - cs, err := Dream(context.Background(), "auto/m", func(_ context.Context, model, system, user string) (string, error) { + cs, err := Dream(context.Background(), "auto/m", func(_ context.Context, model, _, system, user string) (string, error) { asked = append(asked, model+"\n"+user) return "Sure:\n```json\n" + `{"merge":[{"ids":["n1","n2","x9"],"text":"Releases ship on Tuesdays","kind":"FACT"}],"stale":[{"id":"n3","why":"date passed"},{"id":"n4"},{"id":"n99"}]}` + "\n```", nil }) @@ -91,7 +91,7 @@ func TestDreamFailureChangesNothing(t *testing.T) { if _, err := Dream(context.Background(), "", nil); err == nil || !strings.Contains(err.Error(), "no model") { t.Fatalf("no model: %v", err) } - _, err := Dream(context.Background(), "a/m", func(context.Context, string, string, string) (string, error) { + _, err := Dream(context.Background(), "a/m", func(context.Context, string, string, string, string) (string, error) { return "", errors.New("429: slow down") }) if err == nil || status(t, a.ID) != memory.Candidate { diff --git a/internal/memdistill/memdistill.go b/internal/memdistill/memdistill.go index babf77a4e..0c204a266 100644 --- a/internal/memdistill/memdistill.go +++ b/internal/memdistill/memdistill.go @@ -35,9 +35,10 @@ import ( "github.com/yetone/magpie/internal/sessions" ) -// Complete sends one request to model: a system text and one user -// message, and returns the reply's text. -type Complete func(ctx context.Context, model, system, user string) (string, error) +// Complete sends one request to model, asked to reason at effort ("" the +// model's own default): a system text and one user message, and returns +// the reply's text. +type Complete func(ctx context.Context, model, effort, system, user string) (string, error) const ( // Quiet is how long a session has had no turn before it is read: one @@ -45,8 +46,15 @@ const ( Quiet = 30 * time.Minute // PerRun caps the sessions one run sends to the model PerRun = 10 - // Back is how far back a run looks the first time it is switched on + // Back is how far back a run looks the first time it is switched on, + // when no range is picked (State.Days 0) Back = 7 * 24 * time.Hour + // All is State.Days for every conversation listed: the latest + // Listed, read PerRun an hour like any other, so a long history is + // read over days, not at once + All = -1 + // Listed is how many of the latest sessions a run looks through + Listed = 400 // MinTurns is the fewest things the user said for a session to be read MinTurns = 2 // MaxPerSession caps what one session may propose @@ -66,7 +74,15 @@ type State struct { On bool `json:"on,omitempty"` // Model is the model picked; "" is the automatic choice Model string `json:"model,omitempty"` - // Since is when it was switched on, less Back: older sessions aren't read + // Days is how far back reading looks, in days, from when it was + // switched on or the range was picked: 0 is Back, All every + // conversation listed (Ranges) + Days int `json:"days,omitempty"` + // Effort is the reasoning level the model is asked at, reading and + // tidying, fitted to its own levels as it is sent; "" its default + Effort string `json:"effort,omitempty"` + // Since is when it was switched on or the range picked, less the + // range: older sessions aren't read. Zero with All Since time.Time `json:"since,omitzero"` // Done is each read session's last turn when it was read, by // agent/id @@ -95,7 +111,7 @@ var Path = func() string { return appdir.Join(appdir.Config(), "distill.json") } var ( now = time.Now - list = func() []sessions.Session { return sessions.List(400) } + list = func() []sessions.Session { return sessions.List(Listed) } read = sessions.TranscriptOf // running is held through a run in this process, and the file lock // across magpies @@ -161,17 +177,62 @@ func change(fn func(*State)) (State, error) { return s, save(s) } +// Ranges are the ranges, in days, reading can be set to look back: Back's +// seven first, All last. +var Ranges = []int{7, 30, 90, 365, All} + +// since is the oldest a session read may be when days is picked at t. +func since(days int, t time.Time) time.Time { + switch days { + case All: + return time.Time{} + case 0: + return t.Add(-Back).UTC() + } + return t.Add(-time.Duration(days) * 24 * time.Hour).UTC() +} + // Set switches distilling on or off and picks its model ("" automatic). -// Switched on from off, it looks back Back from now. +// Switched on from off, it looks back the range picked (Back by default) +// from now. func Set(on bool, model string) (State, error) { return change(func(s *State) { if on && !s.On { - s.Since = now().Add(-Back).UTC() + s.Since = since(s.Days, now()) } s.On, s.Model = on, strings.TrimSpace(model) }) } +// SetRange picks how far back reading looks: one of Ranges, from now. A +// conversation read already isn't read again for a longer range; one +// older than a shorter range isn't read. +func SetRange(days int) (State, error) { + if !slices.Contains(Ranges, days) { + return State{}, fmt.Errorf("a range of %v days, not %d", Ranges, days) + } + return change(func(s *State) { + if days == 7 { + days = 0 // Back, kept as before a range could be picked + } + s.Days, s.Since = days, since(days, now()) + }) +} + +// SetEffort picks the reasoning level the model is asked at, "" for its +// own default. A level the model doesn't have is fitted to the nearest it +// has when sent. +func SetEffort(effort string) (State, error) { + effort = strings.ToLower(strings.TrimSpace(effort)) + if effort != "" && !slices.Contains(efforts, effort) { + return State{}, fmt.Errorf("a reasoning level of %v, not %q", efforts, effort) + } + return change(func(s *State) { s.Effort = effort }) +} + +// efforts are the levels SetEffort takes (gateway's effortRank). +var efforts = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max"} + // Result is what one run did. type Result struct { Read int @@ -206,7 +267,7 @@ func Run(ctx context.Context, auto string, complete Complete) (Result, error) { if model == "" { runErr = errors.New("no model to read conversations with: pick one") } else { - res, runErr = run(ctx, st, model, complete) + res, runErr = run(ctx, st, model, st.Effort, complete) } _, err = change(func(s *State) { s.Last, s.LastModel, s.Read, s.Added, s.Error = now().UTC(), model, res.Read, res.Added, "" @@ -220,7 +281,7 @@ func Run(ctx context.Context, auto string, complete Complete) (Result, error) { s.Done[k] = at } for k, at := range s.Done { - if now().Sub(at) > keepMarks { + if forget(at, s.Since, res.oldest) { delete(s.Done, k) } } @@ -231,12 +292,30 @@ func Run(ctx context.Context, auto string, complete Complete) (Result, error) { type ran struct { Result done map[string]time.Time + // oldest is the last turn of the oldest session listed, zero when + // none was + oldest time.Time } -// due are the sessions to read now, the latest first. -func due(st State, t time.Time) []sessions.Session { +// forget says a read session's mark, its last turn at, can go: the +// session is older than since, so it is never read again, or older than +// keepMarks and than every session listed (oldest), so it was deleted or +// fell off the listing, which it comes back to only with a turn after +// the mark. A mark kept only keepMarks would have a session older than +// that, inside the range, read again every hour. +func forget(at, since, oldest time.Time) bool { + return at.Before(since) || now().Sub(at) > keepMarks && !oldest.IsZero() && at.Before(oldest) +} + +// due are the sessions to read now, the latest first, and the last turn +// of the oldest listed. +func due(st State, t time.Time) ([]sessions.Session, time.Time) { var out []sessions.Session + var oldest time.Time for _, s := range list() { + if oldest.IsZero() || s.Last.Before(oldest) { + oldest = s.Last + } switch { case s.Agent == Agent, s.Gateway, s.ReadOnly, !s.Transcript, s.ParentSession != "", @@ -249,14 +328,16 @@ func due(st State, t time.Time) []sessions.Session { out = append(out, s) } slices.SortStableFunc(out, func(a, b sessions.Session) int { return b.Last.Compare(a.Last) }) - return out + return out, oldest } func key(s sessions.Session) string { return s.Agent + "/" + s.ID } -func run(ctx context.Context, st State, model string, complete Complete) (ran, error) { +func run(ctx context.Context, st State, model, effort string, complete Complete) (ran, error) { r := ran{done: map[string]time.Time{}} - for _, s := range due(st, now()) { + ss, oldest := due(st, now()) + r.oldest = oldest + for _, s := range ss { if r.Read >= PerRun { break } @@ -275,7 +356,7 @@ func run(ctx context.Context, st State, model string, complete Complete) (ran, e continue } proj := memory.ProjectOf(s.Cwd) - reply, err := complete(ctx, model, prompt, request(text, known(proj), proj)) + reply, err := complete(ctx, model, effort, prompt, request(text, known(proj), proj)) if err != nil { return r, fmt.Errorf("%s: %w", model, err) } diff --git a/internal/memdistill/memdistill_test.go b/internal/memdistill/memdistill_test.go index db1428c40..e282324bb 100644 --- a/internal/memdistill/memdistill_test.go +++ b/internal/memdistill/memdistill_test.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -61,9 +62,12 @@ func (sb *sandbox) session(id string, ago time.Duration, said ...string) *sessio return &sb.list[len(sb.list)-1] } -func (sb *sandbox) complete(_ context.Context, model, system, user string) (string, error) { +func (sb *sandbox) complete(_ context.Context, model, effort, system, user string) (string, error) { _, conv, _ := strings.Cut(user, "Conversation:\n\n") first, _, _ := strings.Cut(conv, "\n") + if effort != "" { + model += ":" + effort + } sb.asked = append(sb.asked, model+" "+first) if sb.reply == nil { return "[]", nil @@ -187,7 +191,7 @@ func TestWhatIsSent(t *testing.T) { } sb.session("s", time.Hour, "first", "second") var sys, user string - complete := func(_ context.Context, _, s, u string) (string, error) { sys, user = s, u; return "[]", nil } + complete := func(_ context.Context, _, _, s, u string) (string, error) { sys, user = s, u; return "[]", nil } if _, err := Run(context.Background(), "a/m", complete); err != nil { t.Fatal(err) } @@ -296,3 +300,133 @@ func TestUnreadableStateRunsNothing(t *testing.T) { t.Fatalf("%s", b) } } + +// How far back reading looks is picked (RealZeroP27 on X: only the last +// 7 days were read): 7 days by default, as before; a longer range reads +// the older conversations in it, All every one listed, PerRun a run all +// the same. What was read already isn't read again. A state written +// before ranges could be picked keeps its own Since. A range or level not +// offered is refused. +func TestRangePicked(t *testing.T) { + sb := newSandbox(t) + // a state from before: switched on two days ago, so looking back to + // nine days ago, and nothing else + was := sb.at.Add(-9 * 24 * time.Hour).UTC() + if err := os.WriteFile(Path(), []byte(`{"on":true,"since":"`+was.Format(time.RFC3339)+`"}`), 0o600); err != nil { + t.Fatal(err) + } + sb.session("d1", 24*time.Hour, "d1", "x") + sb.session("d8", 8*24*time.Hour, "d8", "x") + sb.session("d20", 20*24*time.Hour, "d20", "x") + sb.session("d200", 200*24*time.Hour, "d200", "x") + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil { + t.Fatal(err) + } + if st, _ := Load(); !st.Since.Equal(was) || st.Days != 0 || !slices.Equal(sb.asked, []string{"a/m User: d1", "a/m User: d8"}) { + t.Fatalf("an old state read %q, since %v", sb.asked, st.Since) + } + + sb.asked = nil + if _, err := SetRange(30); err != nil { + t.Fatal(err) + } + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil || !slices.Equal(sb.asked, []string{"a/m User: d20"}) { + t.Fatalf("30 days read %q %v", sb.asked, err) + } + sb.asked = nil + if st, err := SetRange(All); err != nil || !st.Since.IsZero() || st.Days != All { + t.Fatalf("%+v %v", st, err) + } + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil || !slices.Equal(sb.asked, []string{"a/m User: d200"}) { + t.Fatalf("all read %q %v", sb.asked, err) + } + // back to 7: nothing older is read, and switched off and on it looks + // back 7 days again + if st, _ := SetRange(7); st.Days != 0 || !st.Since.Equal(sb.at.Add(-Back)) { + t.Fatalf("%+v", st) + } + if _, err := SetRange(10); err == nil { + t.Fatal("10 days taken") + } + if _, err := SetEffort("hard"); err == nil { + t.Fatal("a level not known taken") + } + if st, _ := Load(); st.Days != 0 || st.Effort != "" { + t.Fatalf("a refusal changed %+v", st) + } + + // a fresh switch-on with All picked reads everything + sb2 := newSandbox(t) + sb2.session("old", 300*24*time.Hour, "old", "x") + if _, err := SetRange(All); err != nil { + t.Fatal(err) + } + on(t, "") + if _, err := Run(context.Background(), "a/m", sb2.complete); err != nil || !slices.Equal(sb2.asked, []string{"a/m User: old"}) { + t.Fatalf("%q %v", sb2.asked, err) + } +} + +// The reasoning level picked is what the model is asked at, reading and +// tidying alike; none picked, it is asked at its own default. +func TestEffortPicked(t *testing.T) { + sb := newSandbox(t) + on(t, "") + sb.session("a", time.Hour, "a", "x") + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil || sb.asked[0] != "a/m User: a" { + t.Fatalf("%q %v", sb.asked, err) + } + if st, err := SetEffort(" High "); err != nil || st.Effort != "high" { + t.Fatalf("%+v %v", st, err) + } + sb.session("b", time.Hour, "b", "x") + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil || sb.asked[1] != "a/m:high User: b" { + t.Fatalf("%q %v", sb.asked, err) + } + note(t, "One", memory.Global, memory.FromInferred) + note(t, "Two", memory.Global, memory.FromInferred) + var asked string + if _, err := Dream(context.Background(), "a/m", func(_ context.Context, _, effort, _, _ string) (string, error) { + asked = effort + return "{}", nil + }); err != nil || asked != "high" { + t.Fatalf("tidied at %q: %v", asked, err) + } +} + +// A conversation read once isn't read again when it is more than a month +// old but inside the range: its mark was kept 30 days, so a session +// older than that, read when reading was switched on two months back, +// was read again every hour. +func TestOldConversationReadOnce(t *testing.T) { + sb := newSandbox(t) + if _, err := SetRange(90); err != nil { + t.Fatal(err) + } + on(t, "") + sb.session("old", 40*24*time.Hour, "old", "x") + sb.session("new", time.Hour, "new", "x") + for range 3 { + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil { + t.Fatal(err) + } + sb.at = sb.at.Add(time.Hour) + } + if !slices.Equal(sb.asked, []string{"a/m User: new", "a/m User: old"}) { + t.Fatalf("read %q", sb.asked) + } + // a mark goes once its session is over a month old and has left the + // listing + if st, _ := Load(); len(st.Done) != 2 { + t.Fatalf("%+v", st.Done) + } + sb.at = sb.at.Add(60 * 24 * time.Hour) + sb.list = sb.list[1:] + sb.list[0].Last = sb.at.Add(-time.Hour) + if _, err := Run(context.Background(), "a/m", sb.complete); err != nil { + t.Fatal(err) + } + if st, _ := Load(); len(st.Done) != 1 || st.Done["codex/new"].IsZero() { + t.Fatalf("%+v", st.Done) + } +}