From df55793a912be298e3d1b90eb8ef2f06cb0c997e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Fri, 27 Nov 2026 14:08:15 +0000 Subject: [PATCH] fix(acp): skip server session scope on serve --stdio and deduplicate startup memory read (v2.0.0-beta.17) --- CHANGELOG.md | 18 ++++++++ package.json | 2 +- src/acp/agent.ts | 42 +++++++++++------- src/app.ts | 23 +++++++--- tests/acp-editor.test.ts | 95 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 156 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7613b5..896027f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ All notable changes to LLeMbas CLI. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). +## [2.0.0-beta.17] — 2026-11-27 + +### Fixed + +- **Server memory on `lembas serve --stdio` (VS Code / Neovim):** stopped setting + `_meta.lembas.scope` (and `markRemote`) on local stdio editor sessions in + `session/new` and `_lembas/sessions/resume`. Local editor sessions have no + server-side `Chat` row, so sending a session scope caused the server's `/mcp` + endpoint to reject `lembas://memory` and `memory` tool calls with + `MCP error -32602: not this device's session`. +- **Duplicate `lembas://memory` reads on session start:** `setScope()`, + `resume()`, and `newSession()` now defer to the single initial `mcpReady` + memory read until MCP has connected, preventing duplicate memory reads and + duplicate notices. +- **Autocomplete resilience:** guarded `CompletionContext.gather()` in + `_lembas/complete` so workspace index edge cases fall back to client context + instead of failing the completion request. + ## [2.0.0-beta.16] — 2026-11-26 ### Fixed diff --git a/package.json b/package.json index 78d02c8..a59d430 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lembas-cli", - "version": "2.0.0-beta.16", + "version": "2.0.0-beta.17", "description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.", "license": "MIT", "private": true, diff --git a/src/acp/agent.ts b/src/acp/agent.ts index 17b022e..ed8bf37 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -550,6 +550,10 @@ export class AcpAgent { private get cards() { return this.lembas && this.clientProtocol >= 2 } + /** True when serving a remote LLeMbas web-UI link (not a local `serve --stdio` editor). */ + private get isLink() { + return Boolean(this.instanceConnection || this.limits) + } /** The client shows files (`show: true` in `clientCapabilities._meta.lembas`, spec 3.0.0): the * show tool is offered in the sessions it opens, and nowhere else. */ private shows = false @@ -783,7 +787,7 @@ export class AcpAgent { const effort = effortOf(p?._meta?.effort) try { // A schedule's session uses the directory's model and never becomes it (spec 3.9.0). - session.app = createApp({ cwd, mode, asker: this.asker(session), modelTitles: false, model, ...(effort !== undefined ? { effort } : {}), kind: scheduled ? "scheduled" : this.lembas ? "link" : "stdio", ...(scheduled ? { automated: true as const } : {}) }) + session.app = createApp({ cwd, mode, asker: this.asker(session), modelTitles: false, model, ...(effort !== undefined ? { effort } : {}), kind: scheduled ? "scheduled" : this.isLink ? "link" : "stdio", ...(scheduled ? { automated: true as const } : {}) }) } catch (e) { // Scheduled work never runs on an interactive-only model (interactive.md §2): the sentence, and why. throw new RpcError(INVALID_PARAMS, (e as Error).message, e instanceof InteractiveOnlyError ? { reason: INTERACTIVE_REASON } : undefined) @@ -800,7 +804,7 @@ export class AcpAgent { const id = session.app.engine.sessionId ?? crypto.randomUUID() session.id = id session.turns = turnLog(id) - markRemote(session.app.store, id) + if (this.isLink) markRemote(session.app.store, id) if (scheduled) { try { // How it was opened, kept with the session: opened from the store again — after a restart @@ -810,8 +814,9 @@ export class AcpAgent { // …and the model it is on, kept from here on. session.app.forgetful() } - // The client's chat: its memory calls land in that chat's data group (acp.md *Memory*). - session.app.setScope(id) + // The client's chat on a server link: its memory calls land in that chat's data group (acp.md *Memory*). + // Local `serve --stdio` editor sessions have no server Chat row, so leave scope unset (account default). + if (this.isLink) session.app.setScope(id) this.takeContext(session, p) this.sessions.set(id, session) this.adopt(session) @@ -871,7 +876,7 @@ export class AcpAgent { if (t) return t.client.request("hub/configure", { sessionId: t.sessionId, model: this.refFor(p?.model), effort: p?.effort }, 30_000) const s = this.get(p) if (p?.model !== undefined) { - if (this.instanceConnection || this.limits) { + if (this.isLink) { const ref = this.chatModel(p.model) if (s.app.canonicalRef(ref) !== s.app.engine.model.ref) { const conn = s.app.loaded.connections[this.instanceConnection!] @@ -932,9 +937,9 @@ export class AcpAgent { const L = this.limits const session: Session = { id, cwd: dir, prompting: false, app: undefined as unknown as App, turns: turnLog(id) } // `resume` reads what kind of session it is: a schedule's comes back as one, on its own model. - session.app = createApp({ cwd: dir, ...(L ? { mode: L.maxMode } : {}), asker: this.asker(session), modelTitles: false, resuming: id, kind: "link" }) + session.app = createApp({ cwd: dir, ...(L ? { mode: L.maxMode } : {}), asker: this.asker(session), modelTitles: false, resuming: id, kind: this.isLink ? "link" : "stdio" }) session.app.resume(id) - markRemote(session.app.store, id) + if (this.isLink) markRemote(session.app.store, id) // A schedule's session stays one: nothing in it becomes its directory's model, and its list // of tools is the one it was opened with — report_write for a schedule that notifies // (reports.md §2). `opened` used to live in memory only, so a continuing schedule's next run @@ -943,7 +948,7 @@ export class AcpAgent { const kept = session.app.store?.meta(id, SCHEDULED_META) if (kept && typeof kept === "object") session.opened = kept } catch {} - session.app.setScope(id) + if (this.isLink) session.app.setScope(id) if (L) session.app.engine.mode = clampMode(session.app.engine.mode, L.maxMode) this.sessions.set(id, session) this.adopt(session) @@ -1101,15 +1106,18 @@ export class AcpAgent { .slice(0, 12) .map((x: any) => ({ path: x.path, text: x.text })) : undefined - const gathered = this.completionCtx.gather({ - root, - path: body.path, - language: body.language, - prefix: body.prefix, - suffix: body.suffix, - open, - clientContext: body.context, - }) + let gathered = body.context ?? [] + try { + gathered = this.completionCtx.gather({ + root, + path: body.path, + language: body.language, + prefix: body.prefix, + suffix: body.suffix, + open, + clientContext: body.context, + }) + } catch {} if (gathered.length) body.context = gathered const login = loginOrRefuse((this.login ??= currentLogin())) this.completion?.abort.abort() diff --git a/src/app.ts b/src/app.ts index 718b1f9..5c87c25 100644 --- a/src/app.ts +++ b/src/app.ts @@ -894,19 +894,30 @@ export function createApp(o: AppOptions): App { } }) const mcpReady = mcp.start() + let mcpStarted = false + let memorySeq = 0 /** The server's memory entries for the prompt (`lembas://memory`), read as a session starts, in * the session's scope: in the prompt when it is made after this, else said in a note on the next * user message — the prompt does not change under a session. */ const readServerMemory = async () => { if (!lembasLibrary || !serverMemory) return + const seq = ++memorySeq try { const text = await mcp.readResource(LIBRARY_SERVER, MEMORY_RESOURCE, engine.o.toolCtx.libraryScope) - serverMemory = { text } + if (seq === memorySeq) serverMemory = { text } } catch (e) { - bus.emit({ type: "notice", level: "warn", message: `memory: the server's entries could not be read (${(e as Error).message}); none are in this session's prompt` }) + if (seq === memorySeq) { + bus.emit({ type: "notice", level: "warn", message: `memory: the server's entries could not be read (${(e as Error).message}); none are in this session's prompt` }) + } } } - void mcpReady.then(readServerMemory) + const refreshServerMemory = () => { + if (mcpStarted) void readServerMemory() + } + void mcpReady.then(() => { + mcpStarted = true + return readServerMemory() + }) // small_model when it resolves; a broken one is said once and the session's model used instead. let smallWarned = false @@ -1199,7 +1210,7 @@ export function createApp(o: AppOptions): App { }, setScope(scope) { engine.o.toolCtx.libraryScope = scope - void readServerMemory() + refreshServerMemory() }, rename(title) { const id = engine.sessionId @@ -1209,7 +1220,7 @@ export function createApp(o: AppOptions): App { }, newSession() { frozen = freeze() - void readServerMemory() + refreshServerMemory() named = "no" firstShown = "" const s = store?.createSession(project.root, engine.model.ref) @@ -1230,7 +1241,7 @@ export function createApp(o: AppOptions): App { if (!store) return [] const before = engine.sessionId frozen = freeze() - void readServerMemory() + refreshServerMemory() teamRt.reset(newTeam()) // A session a schedule opened stays one wherever it is opened — in a terminal too // (/sessions, -c): nothing in it becomes its directory's model. diff --git a/tests/acp-editor.test.ts b/tests/acp-editor.test.ts index ead2b47..03c5ecc 100644 --- a/tests/acp-editor.test.ts +++ b/tests/acp-editor.test.ts @@ -876,3 +876,98 @@ test("_lembas/configure on serve --stdio switches the session model without an i // Empty model string is rejected cleanly. expect((await refusal(c.request("_lembas/configure", { sessionId: s.sessionId, model: " " }))).message).toContain("non-empty") }) + +test("library: lembas on serve --stdio reads memory once with no scope, while a link session sends scope once", async () => { + const mcpCalls: { method: string; scope?: string; name?: string }[] = [] + const linkSessions = new Set() + const mcpServer = Bun.serve({ + port: 0, + async fetch(req) { + const u = new URL(req.url) + if (u.pathname !== "/mcp") return new Response("no", { status: 404 }) + if (req.method !== "POST") return new Response(null, { status: 405 }) + const msg = (await req.json()) as any + if (msg.id === undefined) return new Response(null, { status: 202 }) + const reply = (result: unknown) => Response.json({ jsonrpc: "2.0", id: msg.id, result }) + if (msg.method === "initialize") return reply({ protocolVersion: msg.params.protocolVersion, capabilities: { tools: {}, resources: {} }, serverInfo: { name: "lembas", version: "2.0.0" } }) + if (msg.method === "resources/list") return reply({ resources: [{ uri: "lembas://memory", name: "memory" }] }) + if (msg.method === "tools/list") + return reply({ + tools: [ + { name: "memory", description: "The account's memory.", inputSchema: { type: "object", properties: { action: { type: "string" } }, required: ["action"] }, annotations: { readOnlyHint: true } }, + ], + }) + if (msg.method === "resources/read" || msg.method === "tools/call") { + const scope = msg.params?._meta?.lembas?.scope as string | undefined + mcpCalls.push({ method: msg.method, ...(scope ? { scope } : {}), ...(msg.params?.name ? { name: msg.params.name } : {}) }) + if (scope && !linkSessions.has(scope)) { + return Response.json({ jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: "not this device's session" } }) + } + if (msg.method === "resources/read") { + return reply({ contents: [{ uri: msg.params.uri, mimeType: "text/plain", text: "MEMORY\nUses bun." }] }) + } + return reply({ content: [{ type: "text", text: "ok" }], isError: false }) + } + return Response.json({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: "no" } }) + }, + }) + const prevStop = stopServer + stopServer = () => { + mcpServer.stop(true) + prevStop?.() + } + mkdirSync(join(paths.config, "lembas"), { recursive: true }) + writeFileSync(join(paths.config, "lembas", "example.key"), "lmb_key\n", { mode: 0o600 }) + writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { base_url: `http://127.0.0.1:${mcpServer.port}`, connection: "example", scope: "models memory link", logged_in_at: new Date().toISOString() } } })) + + fake = fakeProvider([ + { chunks: [toolCall(0, "m1", "memory", JSON.stringify({ action: "view" }))] }, + { chunks: [delta({ content: "done" })] }, + ]) + config(fake.url, "library: lembas\n") + const root = project() + + // 1. Local `serve --stdio` editor: no scope, single memory read, no -32602 warnings. + const notices: string[] = [] + const [ta, tb] = pair() + new AcpAgent(new Peer(ta)) + const c = new Peer(tb) + c.on("session/update", () => {}) + c.on("_lembas/event", (p: any) => { + if (p?.event?.type === "notice") notices.push(String(p.event.message || "")) + }) + c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } })) + await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { editor: true, protocol: 2 } } } }) + const s: any = await c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await until(() => mcpCalls.some((x) => x.method === "resources/read"), "stdio memory read") + await Bun.sleep(40) + expect(mcpCalls.filter((x) => x.method === "resources/read")).toEqual([{ method: "resources/read" }]) + expect(notices.filter((m) => m.includes("not this device's session"))).toEqual([]) + await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check memory" }] }) + expect(mcpCalls.filter((x) => x.method === "tools/call")).toEqual([{ method: "tools/call", name: "memory" }]) + tb.close() + + // 2. Resuming that session in a fresh `serve --stdio` editor also leaves scope unset and reads once. + mcpCalls.length = 0 + const [ta2, tb2] = pair() + new AcpAgent(new Peer(ta2)) + const c2 = new Peer(tb2) + c2.on("session/update", () => {}) + c2.on("_lembas/event", () => {}) + await c2.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { editor: true, protocol: 2 } } } }) + await c2.request("_lembas/sessions/resume", { sessionId: s.sessionId }) + await until(() => mcpCalls.some((x) => x.method === "resources/read"), "resumed stdio memory read") + await Bun.sleep(40) + expect(mcpCalls.filter((x) => x.method === "resources/read")).toEqual([{ method: "resources/read" }]) + tb2.close() + + // 3. Remote linked session (with limits): sends scope = sessionId, and still reads memory only once on startup. + mcpCalls.length = 0 + const link = await editor({ limits: { roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true } }) + const ls: any = await link.c.request("session/new", { cwd: root }) + linkSessions.add(ls.sessionId) + await until(() => mcpCalls.some((x) => x.method === "resources/read"), "link memory read") + await Bun.sleep(40) + expect(mcpCalls.filter((x) => x.method === "resources/read")).toEqual([{ method: "resources/read", scope: ls.sessionId }]) + link.close() +})