fix(acp): skip server session scope on serve --stdio and deduplicate startup memory read (v2.0.0-beta.17)
ci / check (push) Canceled after 0s

This commit is contained in:
Homer committed 2026-11-27 14:08:15 +00:00
1 parent 6caa0dcbc1
commit df55793a91
5 files changed
+156 -24

No files matched your search

+18
View File
@@ -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 [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[Semantic Versioning](https://semver.org/). [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 ## [2.0.0-beta.16] — 2026-11-26
### Fixed ### Fixed
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "lembas-cli", "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.", "description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.",
"license": "MIT", "license": "MIT",
"private": true, "private": true,
+25 -17
View File
@@ -550,6 +550,10 @@ export class AcpAgent {
private get cards() { private get cards() {
return this.lembas && this.clientProtocol >= 2 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 /** 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. */ * show tool is offered in the sessions it opens, and nowhere else. */
private shows = false private shows = false
@@ -783,7 +787,7 @@ export class AcpAgent {
const effort = effortOf(p?._meta?.effort) const effort = effortOf(p?._meta?.effort)
try { try {
// A schedule's session uses the directory's model and never becomes it (spec 3.9.0). // 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) { } catch (e) {
// Scheduled work never runs on an interactive-only model (interactive.md §2): the sentence, and why. // 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) 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() const id = session.app.engine.sessionId ?? crypto.randomUUID()
session.id = id session.id = id
session.turns = turnLog(id) session.turns = turnLog(id)
markRemote(session.app.store, id) if (this.isLink) markRemote(session.app.store, id)
if (scheduled) { if (scheduled) {
try { try {
// How it was opened, kept with the session: opened from the store again — after a restart // 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. // …and the model it is on, kept from here on.
session.app.forgetful() session.app.forgetful()
} }
// The client's chat: its memory calls land in that chat's data group (acp.md *Memory*). // The client's chat on a server link: its memory calls land in that chat's data group (acp.md *Memory*).
session.app.setScope(id) // 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.takeContext(session, p)
this.sessions.set(id, session) this.sessions.set(id, session)
this.adopt(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) 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) const s = this.get(p)
if (p?.model !== undefined) { if (p?.model !== undefined) {
if (this.instanceConnection || this.limits) { if (this.isLink) {
const ref = this.chatModel(p.model) const ref = this.chatModel(p.model)
if (s.app.canonicalRef(ref) !== s.app.engine.model.ref) { if (s.app.canonicalRef(ref) !== s.app.engine.model.ref) {
const conn = s.app.loaded.connections[this.instanceConnection!] const conn = s.app.loaded.connections[this.instanceConnection!]
@@ -932,9 +937,9 @@ export class AcpAgent {
const L = this.limits const L = this.limits
const session: Session = { id, cwd: dir, prompting: false, app: undefined as unknown as App, turns: turnLog(id) } 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. // `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) 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 // 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 // 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 // (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<ScheduledTurn | true>(id, SCHEDULED_META) const kept = session.app.store?.meta<ScheduledTurn | true>(id, SCHEDULED_META)
if (kept && typeof kept === "object") session.opened = kept if (kept && typeof kept === "object") session.opened = kept
} catch {} } 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) if (L) session.app.engine.mode = clampMode(session.app.engine.mode, L.maxMode)
this.sessions.set(id, session) this.sessions.set(id, session)
this.adopt(session) this.adopt(session)
@@ -1101,15 +1106,18 @@ export class AcpAgent {
.slice(0, 12) .slice(0, 12)
.map((x: any) => ({ path: x.path, text: x.text })) .map((x: any) => ({ path: x.path, text: x.text }))
: undefined : undefined
const gathered = this.completionCtx.gather({ let gathered = body.context ?? []
root, try {
path: body.path, gathered = this.completionCtx.gather({
language: body.language, root,
prefix: body.prefix, path: body.path,
suffix: body.suffix, language: body.language,
open, prefix: body.prefix,
clientContext: body.context, suffix: body.suffix,
}) open,
clientContext: body.context,
})
} catch {}
if (gathered.length) body.context = gathered if (gathered.length) body.context = gathered
const login = loginOrRefuse((this.login ??= currentLogin())) const login = loginOrRefuse((this.login ??= currentLogin()))
this.completion?.abort.abort() this.completion?.abort.abort()
+17 -6
View File
@@ -894,19 +894,30 @@ export function createApp(o: AppOptions): App {
} }
}) })
const mcpReady = mcp.start() 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 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 * 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. */ * user message — the prompt does not change under a session. */
const readServerMemory = async () => { const readServerMemory = async () => {
if (!lembasLibrary || !serverMemory) return if (!lembasLibrary || !serverMemory) return
const seq = ++memorySeq
try { try {
const text = await mcp.readResource(LIBRARY_SERVER, MEMORY_RESOURCE, engine.o.toolCtx.libraryScope) const text = await mcp.readResource(LIBRARY_SERVER, MEMORY_RESOURCE, engine.o.toolCtx.libraryScope)
serverMemory = { text } if (seq === memorySeq) serverMemory = { text }
} catch (e) { } 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. // small_model when it resolves; a broken one is said once and the session's model used instead.
let smallWarned = false let smallWarned = false
@@ -1199,7 +1210,7 @@ export function createApp(o: AppOptions): App {
}, },
setScope(scope) { setScope(scope) {
engine.o.toolCtx.libraryScope = scope engine.o.toolCtx.libraryScope = scope
void readServerMemory() refreshServerMemory()
}, },
rename(title) { rename(title) {
const id = engine.sessionId const id = engine.sessionId
@@ -1209,7 +1220,7 @@ export function createApp(o: AppOptions): App {
}, },
newSession() { newSession() {
frozen = freeze() frozen = freeze()
void readServerMemory() refreshServerMemory()
named = "no" named = "no"
firstShown = "" firstShown = ""
const s = store?.createSession(project.root, engine.model.ref) const s = store?.createSession(project.root, engine.model.ref)
@@ -1230,7 +1241,7 @@ export function createApp(o: AppOptions): App {
if (!store) return [] if (!store) return []
const before = engine.sessionId const before = engine.sessionId
frozen = freeze() frozen = freeze()
void readServerMemory() refreshServerMemory()
teamRt.reset(newTeam()) teamRt.reset(newTeam())
// A session a schedule opened stays one wherever it is opened — in a terminal too // 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. // (/sessions, -c): nothing in it becomes its directory's model.
+95
View File
@@ -876,3 +876,98 @@ test("_lembas/configure on serve --stdio switches the session model without an i
// Empty model string is rejected cleanly. // Empty model string is rejected cleanly.
expect((await refusal(c.request("_lembas/configure", { sessionId: s.sessionId, model: " " }))).message).toContain("non-empty") 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<string>()
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()
})