Compare commits

...
Author SHA1 Message Date
Homer df55793a91 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
2026-11-27 14:08:15 +00:00
Homer 6caa0dcbc1 fix(acp): allow _lembas/configure model switch on serve --stdio (v2.0.0-beta.16)
ci / check (push) Canceled after 0s
2026-11-26 21:32:48 +00:00
5 changed files with 201 additions and 32 deletions

No files matched your search

+27
View File
@@ -4,6 +4,33 @@ 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
- **IDE model switching on `lembas serve --stdio`** (`_lembas/configure`): no
longer requires a linked server instance connection when changing the active
session's model from an editor client (VS Code / VSCodium / Neovim), resolving
against the device's signed-in server models instead.
## [2.0.0-beta.15] — 2026-11-26
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "lembas-cli",
"version": "2.0.0-beta.15",
"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,
+46 -25
View File
@@ -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)
@@ -870,15 +875,28 @@ export class AcpAgent {
const t = this.terminalFor(p)
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 ref = p?.model !== undefined ? this.chatModel(p.model) : undefined
if (ref && s.app.canonicalRef(ref) !== s.app.engine.model.ref) {
const conn = s.app.loaded.connections[this.instanceConnection!]
const id = s.app.canonicalRef(ref)
if (!conn) throw new RpcError(INVALID_PARAMS, `this device is not logged in to ${this.instanceConnection}, so it cannot run ${p.model}`)
if (Object.keys(conn.models).length && !conn.models[id]) throw new RpcError(INVALID_PARAMS, `${conn.webui?.name ?? this.instanceConnection} does not serve ${p.model} to this device`)
// The person's change is the directory's model from now (spec 3.9.0) — a schedule's session
// apart, which the app was told never to remember.
s.app.chooseModel(ref)
if (p?.model !== undefined) {
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!]
const id = s.app.canonicalRef(ref)
if (!conn) throw new RpcError(INVALID_PARAMS, `this device is not logged in to ${this.instanceConnection}, so it cannot run ${p.model}`)
if (Object.keys(conn.models).length && !conn.models[id]) throw new RpcError(INVALID_PARAMS, `${conn.webui?.name ?? this.instanceConnection} does not serve ${p.model} to this device`)
// The person's change is the directory's model from now (spec 3.9.0) — a schedule's session
// apart, which the app was told never to remember.
s.app.chooseModel(ref)
}
} else {
// Local stdio editor client: resolve against the device's own signed-in models.
const raw = typeof p.model === "string" ? p.model.trim() : ""
if (!raw) throw new RpcError(INVALID_PARAMS, "model must be a non-empty string")
try {
if (s.app.canonicalRef(raw) !== s.app.engine.model.ref) s.app.chooseModel(raw)
} catch (e) {
throw new RpcError(INVALID_PARAMS, (e as Error).message)
}
}
}
const effort = effortOf(p?.effort)
// A level the model does not offer is read as its start level; the answer says the one used.
@@ -919,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
@@ -930,7 +948,7 @@ export class AcpAgent {
const kept = session.app.store?.meta<ScheduledTurn | true>(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)
@@ -1088,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()
+17 -6
View File
@@ -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.
+110
View File
@@ -861,3 +861,113 @@ test("a client that writes puts the text into its buffer and saves before answer
expect(readFileSync(file, "utf8")).toBe("a third\n")
expect(readFileSync(join(root, "b.txt"), "utf8")).toBe("new\n")
})
test("_lembas/configure on serve --stdio switches the session model without an instance device link", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "switched" })] }])
config(fake.url)
const root = project()
const { c } = await editor()
const s: any = await c.request("session/new", { cwd: root })
expect(s._meta.lembas.model).toBe("f/m")
const res: any = await c.request("_lembas/configure", { sessionId: s.sessionId, model: "f/deep" })
expect(res.model).toBe("f/deep")
await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] })
expect(fake.requests.at(-1).model).toBe("f/deep")
// 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<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()
})