Files
HomerandClaude Opus 5.5 2b1d42b976 Neovim plugin: only project files go along, the shared rules held by shared cases, review fixes
Privacy: pieces of other open files with a suggestion, and the names of other open files with a
message, now come only from files inside the working directory, never from a file that looks
like it holds secrets (one table, tests/rules/private_files.json, which the VS Code extension
reads too), and never from one the project's .gitignore leaves out. In a file that looks secret
no suggestion is asked for; said once. :help llembas-privacy says what is and is not sent.

- require("llembas").cli(): the one function that decides where the LLeMbas CLI is (PATH, then
  ~/.local/bin); LLeMbas IDE and its launcher follow it.
- A late answer from an agent that was replaced (:LLeMbasNew!, :LLeMbasRestart) no longer ends
  the new turn.
- :LLeMbasOpen judges a file by its first bytes and its name (llembas.shown), as VS Code does.
- The existing sign-in is read by whole lines; an address that reads as an option is refused.
- A protocol line over the limit is dropped whole, not the message after it; a notification
  that fails is noted in :LLeMbasLog.
- After :cd the remembered settings of the new directory hold.
- Versions: "1.2.3junk" is no version, as in VS Code.
- tests/rules/: versions, private files, server addresses, sign-in lines, protocol lines and
  openable files, as data both editors' suites read (scripts/test-nvim.sh rules).
- The stand-in agent answers _lembas/session/delete as the CLI does ({deleted}, no notification
  on serve --stdio).
- Texts: one sentence for "still working" and one for "this CLI is too old"; plain words in
  :LLeMbasStatus and the length presets; the help card is "LLeMbas — commands and keys".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:14 +00:00

986 lines
48 KiB
Python
Executable File

#!/usr/bin/env python3
"""A stand-in for `lembas serve --stdio`, for the tests of both editors.
It answers in the shapes of the LLeMbas CLI (2.0.0-beta.17, `src/acp/agent.ts`, harness spec
3.11.0) and in no other: every result, refusal, notification and request it sends is written as
the CLI writes it, and what it is sent is checked as the CLI checks it. A client that reads an
older or an invented shape fails here, as it would against the CLI. When the CLI's protocol
changes, this file changes with it -- it is the one place the tests learn the protocol from.
A turn is steered by words in the prompt's last text block:
PERM an approval for a command (`session/request_permission`)
SETTLE an approval that is then withdrawn (`_lembas/permission/settled`)
DIFFPERM <path> an approval for an edit, carrying ACP diff items; the file is written when allowed
READ <path> the read tool: the client's text when it gives one, else the disk's
PUT <path> the write tool: "put by the agent" + a line break becomes the file's text
EDIT <path> the edit tool: the file's first line in capitals, the rest as it is
WRITE <path> the agent writes the disk itself (a session whose client offers no `fs`)
SHOW <path> the show tool (text with its content; anything else by a handle); `AT <n>`: a line
BADHASH with SHOW: the handle's hash is not the file's
QUESTION `_lembas/question` (MULTI: a question that takes several options)
PLANCARD `_lembas/plan`
TOOL a tool call with its events (phase, tool_end with ms, usage)
DENIED a call that was refused
PLAN a `plan` update
TEAM a `team` event
NOTICE a `notice` event
META says back the editor context the prompt carried
FAIL the turn fails: an `error` event, and the answer's `_meta.lembas.error`
FAILFIELD the same, said by the answer alone
SLOW waits to be cancelled
CRASH writes to stderr and exits 3
A prompt that is `/compact` is the command, as the CLI runs it. A completion is steered by words
in its prefix (SLOWC waits to be cancelled, FAILC is a server failure, BUSYC is `busy`), a rewrite
by words in its instruction (SLOWE waits to be cancelled, `REPLACE <text>` answers that text,
SAME answers the selection, ADDLINE puts the first line in capitals and adds a line after the second,
EMPTYE is a model that answered nothing; anything else answers the selection in capitals).
Environment:
FAKE_AGENT_LOG every message received is appended, one JSON object a line
FAKE_AGENT_VERSION the version it says (default 2.0.0-beta.17); before 2.0.0-beta.14 it
has no editor methods, before 2.0.0-beta.15 no `_lembas/sessions/*`
FAKE_AGENT_LOGIN=none this computer is not logged in to a server
FAKE_AGENT_AUTOCOMPLETE the saved autocomplete model; "none": nobody has chosen one
FAKE_AGENT_HANG=<method> that request is never answered
FAKE_AGENT_MIN_CLIENT `_meta.lembas.min_client` of the hello: the oldest version of this client
the signed-in server works with
"""
import base64
import hashlib
import json
import os
import re
import sys
import threading
import time
import uuid
LOG = os.environ.get("FAKE_AGENT_LOG")
VERSION = os.environ.get("FAKE_AGENT_VERSION", "2.0.0-beta.17")
LOGGED_IN = os.environ.get("FAKE_AGENT_LOGIN") != "none"
HANG = os.environ.get("FAKE_AGENT_HANG", "")
INVALID_PARAMS = -32602
METHOD_NOT_FOUND = -32601
INTERNAL_ERROR = -32603
MODES = ["manual", "edit", "auto", "plan"]
NOT_LOGGED_IN_SESSION = ("Not logged in to a LLeMbas server. LLeMbas CLI uses the models of the server it is logged in to: "
"lembas login <address> (e.g. lembas login ai.example.org).")
NOT_LOGGED_IN_EDITOR = "this computer is not logged in to a LLeMbas server (lembas login <address>)"
CAPABILITIES = [
"directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands",
"attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show",
"progress", "tree", "agents", "scheduled", "reports", "directory_model", "harness_turns", "editor", "media",
]
COMMANDS = [
{"name": "compact", "description": "summarise the conversation to free context", "_meta": {"lembas": {"kind": "builtin"}}},
{"name": "plan", "description": "plan mode — read, investigate, write a plan for approval; with a task, start on it",
"input": {"hint": "task"}, "_meta": {"lembas": {"kind": "builtin"}}},
{"name": "undo", "description": "take back the last prompt: its file changes and its conversation", "_meta": {"lembas": {"kind": "builtin"}}},
{"name": "review", "description": "a read-only review of this session's changes (or since the last commit, or against a branch)",
"input": {"hint": "head | <branch>"}, "_meta": {"lembas": {"kind": "builtin"}}},
{"name": "bake", "description": "a skill of the project", "input": {"hint": "instruction"}, "_meta": {"lembas": {"kind": "skill"}}},
]
MODELS = [
{"id": "example/model-a", "name": "Model A", "for": ["main", "autocomplete"], "default": True},
{"id": "example/model-b", "name": "Model B", "for": ["main", "autocomplete"]},
{"id": "example/model-c", "name": "Model C", "for": ["main"]},
]
ALLOWED = ["example/model-a", "example/model-b"]
def version_key(v):
"""2.0.0-beta.10 sorts above 2.0.0-beta.9, and a release above its betas."""
core, _, pre = v.split("+")[0].partition("-")
nums = [int(x) for x in core.split(".")[:3]]
n = re.search(r"(\d+)$", pre)
return nums + [0 if pre else 1, int(n.group(1)) if n else 0]
HAS_EDITOR = version_key(VERSION) >= version_key("2.0.0-beta.14")
HAS_SESSIONS = version_key(VERSION) >= version_key("2.0.0-beta.15")
lock = threading.Lock()
waiting = {} # our request id -> [Event, result, error]
next_id = [0]
client = {"lembas": False, "protocol": 1, "editor": False, "show": False, "media": False, "read": False, "write": False}
sessions = {} # id -> {cwd, mode, model, working, cancel: Event, seen: {path: sha}}
saved = os.environ.get("FAKE_AGENT_AUTOCOMPLETE", "example/model-a")
settings = {"autocomplete_model": None if saved == "none" else saved, "main_model": None}
completion = [None] # (client id, Event) of the one completion under way
complete_lock = threading.Lock()
rewrites = {} # Event -> client id
handles = {} # handle -> bytes
deleted = {} # ids of stored sessions that were deleted
PREVIOUS = {"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000100000, "created": 1700000000000}
class Refusal(Exception):
def __init__(self, code, message, reason=None):
super().__init__(message)
self.code, self.message, self.reason = code, message, reason
def out(msg):
with lock:
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
def notify(method, params):
out({"jsonrpc": "2.0", "method": method, "params": params})
def result(msg, value):
out({"jsonrpc": "2.0", "id": msg["id"], "result": value})
def refuse(msg, code, message, reason=None):
error = {"code": code, "message": message}
if reason:
error["data"] = {"reason": reason}
out({"jsonrpc": "2.0", "id": msg["id"], "error": error})
def ask(method, params, wait=30):
"""A request to the client: (result, None), (None, error), or (None, 'timeout')."""
with lock:
next_id[0] += 1
rid = next_id[0]
entry = [threading.Event(), None, None]
waiting[rid] = entry
out({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
if not entry[0].wait(wait):
waiting.pop(rid, None)
return None, "timeout"
waiting.pop(rid, None)
return entry[1], entry[2]
def sha(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def read_disk(path):
with open(path, "rb") as f:
return f.read().decode("utf-8")
def write_disk(path, text):
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "wb") as f:
f.write(text.encode("utf-8"))
def word_after(text, word):
return text.split(word + " ", 1)[1].split()[0]
# ---- what the CLI sends about a session ---------------------------------------------------
def update(sid, body):
notify("session/update", {"sessionId": sid, "update": body})
def event(sid, body):
if client["lembas"]:
notify("_lembas/event", {"sessionId": sid, "event": body})
def say(sid, text):
event(sid, {"type": "text", "text": text})
update(sid, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})
def think(sid, text):
event(sid, {"type": "reasoning", "text": text})
update(sid, {"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": text}})
def phase(sid, name, **data):
event(sid, {"type": "phase", "progress": {"phase": name, "since": int(time.time() * 1000), **data} if name else None})
def set_mode(sid, mode):
sessions[sid]["mode"] = mode
event(sid, {"type": "mode", "mode": mode})
update(sid, {"sessionUpdate": "current_mode_update", "currentModeId": mode})
def tool_start(sid, call, name, kind, title, args):
phase(sid, "running_tool", tool=name, what=title)
event(sid, {"type": "tool_start", "id": call, "name": name, "args": args, "title": title})
update(sid, {"sessionUpdate": "tool_call", "toolCallId": call, "title": title, "kind": kind, "status": "in_progress", "rawInput": args})
def tool_end(sid, call, name, output, failed=False, files=None, ms=42):
event(sid, {"type": "tool_end", "id": call, "name": name, "result": {"output": output, **({"isError": True} if failed else {})}, "ms": ms})
content = [{"type": "content", "content": {"type": "text", "text": output[:20000]}}]
if files and not failed and client["editor"]:
content += diff_items(files)
update(sid, {"sessionUpdate": "tool_call_update", "toolCallId": call, "status": "failed" if failed else "completed", "content": content})
def tool_denied(sid, call, name, kind, title, args, reason):
event(sid, {"type": "tool_denied", "id": call, "name": name, "reason": reason, "args": args, "title": title})
update(sid, {"sessionUpdate": "tool_call", "toolCallId": call, "title": title, "kind": kind, "status": "failed", "rawInput": args,
"content": [{"type": "content", "content": {"type": "text", "text": reason}}], "_meta": {"lembas": {"denied": True}}})
def diff_items(files):
return [{"type": "diff", "path": f["path"], "oldText": f["oldText"], "newText": f["newText"] if f["newText"] is not None else "",
**({"_meta": {"lembas": {"deleted": True}}} if f["newText"] is None else {})} for f in files]
def approval(sid, tool, kind, title, args, reason, files=None, always=True):
"""`session/request_permission`, and the answer as the CLI reads it: once, session or deny."""
call = str(uuid.uuid4())
tool_call = {"toolCallId": call, "title": title, "kind": kind, "status": "pending", "rawInput": args}
if files:
if client["editor"]:
tool_call["content"] = diff_items(files)
else:
tool_call["content"] = [{"type": "content", "content": {"type": "text", "text": "--- a\n+++ b\n(the change as a unified diff)"}}]
options = [{"optionId": "once", "kind": "allow_once", "name": "Allow once"}]
if always:
options.append({"optionId": "session", "kind": "allow_always", "name": "Always, this session"})
options.append({"optionId": "deny", "kind": "reject_once", "name": "Deny"})
phase(sid, "waiting_for_person")
answer, error = ask("session/request_permission", {
"sessionId": sid, "toolCall": tool_call, "options": options,
"_meta": {"lembas": {"tool": tool, "reason": reason, "purpose": "what the model says the call is for"}}})
if error:
notify("_lembas/permission/settled", {"sessionId": sid, "toolCallId": call})
return "deny"
outcome = (answer or {}).get("outcome") or {}
chosen = str(outcome.get("optionId")) if outcome.get("outcome") == "selected" else "deny"
if chosen == "once" or (chosen == "session" and always):
return chosen
return "deny"
# ---- the file tools, with the client's buffers (acp.md *Unsaved text*, src/tool/buffers.ts) ----
def client_read(sid, path):
if not client["read"]:
return None
answer, error = ask("fs/read_text_file", {"sessionId": sid, "path": path}, 10)
if error or not isinstance((answer or {}).get("content"), str):
return None
return answer["content"]
def tool_read(sid, path):
"""The read tool: what the client gives is what "read" means from then on."""
text = client_read(sid, path)
if text is not None:
sessions[sid]["seen"][path] = sha(text)
return text
return read_disk(path)
def file_text(sid, path):
"""A file's text for a tool that changes it: the client's, else the disk's -- never the disk's
for a file the session read through the client."""
text = client_read(sid, path)
if text is not None:
return text
if path in sessions[sid]["seen"]:
raise Refusal(0, f"{path} is open in the editor, and the editor did not give its text just now. Read it again before changing it.")
return read_disk(path)
def guard(sid, path):
seen = sessions[sid]["seen"].get(path)
if seen is None or not client["read"]:
return
now = client_read(sid, path)
if now is None:
raise Refusal(0, f"{path} is open in the editor, and the editor did not give its text just now. Read it again before changing it.")
if sha(now) != seen:
raise Refusal(0, f"{path} changed since you last read it. Read it again before changing it.")
def put_text(sid, path, content):
"""Write through the client where it takes the text, else to the disk. True: the client took it."""
seen = sessions[sid]["seen"]
tracked = path in seen
if not client["write"]:
write_disk(path, content)
if tracked:
seen[path] = sha(content)
return False
answer, error = ask("fs/write_text_file", {"sessionId": sid, "path": path, "content": content}, 10)
if error == "timeout":
seen[path] = "unknown"
raise Refusal(0, f"The editor did not confirm writing {path}; it may or may not have been written. Read it again to see what is there before going on.")
if not error:
seen[path] = sha(content)
return True
if tracked:
raise Refusal(0, f"{path} is open in the editor, which refused the write. Nothing was written; tell the user, or read it again.")
write_disk(path, content)
return False
# ---- a turn ---------------------------------------------------------------------------------
def prompt(msg, s, text):
p = msg["params"]
sid = s["id"]
turn = str((((p.get("_meta") or {}).get("lembas") or {}).get("turnId")) or uuid.uuid4())
done = {"turnId": turn}
s["working"] = True
def answer(value):
# The turn is over before its answer is on the wire: a request that follows the answer
# at once (a compact, a delete) must not find the session still working.
s["working"] = False
return result(msg, value)
try:
if text.startswith("/compact"):
event(sid, {"type": "compacted", "summary": "Compacted 2 turns."})
return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}})
event(sid, {"type": "prompt", "text": text, "turnId": turn})
event(sid, {"type": "task", "state": "start", "turnId": turn})
phase(sid, "waiting_for_model", model=s["model"])
phase(sid, "thinking")
think(sid, "hidden thought")
phase(sid, "writing")
say(sid, "Hello ")
say(sid, "there.\nSecond line")
stop = turn_body(sid, s, p, text)
# A subagent's usage counts toward the task, and says nothing about the session's own.
event(sid, {"type": "usage", "usage": {"input": 700000, "output": 9000}, "child": True})
event(sid, {"type": "usage", "usage": {"input": 1200, "output": 34, "cached": 1000}, "context": 32768, "used": 1234, "rate": 41.5})
if "FAIL" in text.replace("FAILC", ""):
# A turn that fails ends as any other (`end_turn`): the `error` event says why, the phase
# is `failed`, and the answer carries the same in `_meta.lembas.error`.
why = "the server answered 502: the model is not loaded"
if "FAILFIELD" not in text:
event(sid, {"type": "error", "message": why})
phase(sid, "failed", reason=why)
event(sid, {"type": "task", "state": "end", "turnId": turn})
event(sid, {"type": "done", "reason": "error"})
return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}})
phase(sid, None)
event(sid, {"type": "task", "state": "end", "turnId": turn})
event(sid, {"type": "done", "reason": "cancelled" if stop == "cancelled" else "stop"})
answer({"stopReason": stop, "_meta": {"lembas": done}})
finally:
s["working"] = False
def run_tool(sid, name, kind, title, args, fn, files=None):
call = "call_" + uuid.uuid4().hex[:8]
tool_start(sid, call, name, kind, title, args)
try:
output = fn()
except Refusal as e:
return tool_end(sid, call, name, e.message, failed=True)
except OSError as e:
return tool_end(sid, call, name, str(e), failed=True)
tool_end(sid, call, name, output, files=files() if callable(files) else files)
def turn_body(sid, s, p, text):
if "META" in text:
say(sid, "\neditor=" + json.dumps(((p.get("_meta") or {}).get("lembas") or {}).get("editor"), sort_keys=True))
if "NOTICE" in text:
event(sid, {"type": "notice", "level": "warn", "message": "the server is slow to answer; trying again"})
if "TEAM" in text:
event(sid, {"type": "team", "tree": {"min": 1, "max": 3, "size": 1, "open_slots": 2, "ended": [], "agents": [
{"id": "a1", "name": "scout", "position": "1", "parent": None, "state": "working", "model": s["model"], "mode": "plan",
"request": [], "manager": False, "task": "read the tests", "progress": None, "findings": 0, "messages": 0}]}})
if "PLAN" in text.replace("PLANCARD", ""):
plan = {"version": 1, "title": "Upgrade", "summary": "", "findings": [], "objectives": [],
"phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "done"}, {"text": "Step 2", "status": "doing"}, {"text": "Step 3", "status": "todo"}]}]}
event(sid, {"type": "plan", "plan": plan})
update(sid, {"sessionUpdate": "plan", "entries": [
{"content": "Step 1", "status": "completed", "priority": "medium"},
{"content": "Step 2", "status": "in_progress", "priority": "medium"},
{"content": "Step 3", "status": "pending", "priority": "medium"}], "_meta": {"lembas": {"plan": plan}}})
if "TOOL" in text:
run_tool(sid, "grep", "search", "grep waybread", {"pattern": "waybread"}, lambda: "src/oven.py:3: waybread = bake()")
if "DENIED" in text:
tool_denied(sid, "call_denied", "bash", "execute", "rm -rf /", {"command": "rm -rf /"}, "The hardline never allows this command.")
if "DIFFPERM " in text:
path = word_after(text, "DIFFPERM")
old = file_text(sid, path) if os.path.exists(path) else None
new = "rewritten by the agent\n"
files = [{"path": path, "oldText": old, "newText": new}]
args = {"path": path, "content": new}
title = "write " + os.path.basename(path)
got = approval(sid, "write", "edit", title, args, "manual mode asks about every edit", files)
if got == "deny":
tool_denied(sid, "call_w", "write", "edit", title, args, "The user denied this call.")
else:
run_tool(sid, "write", "edit", title, args, lambda: (put_text(sid, path, new), "Wrote " + path)[1], files)
say(sid, "\nanswer=" + got)
elif "SETTLE" in text:
call = str(uuid.uuid4())
with lock:
next_id[0] += 1
rid = next_id[0]
entry = [threading.Event(), None, None]
waiting[rid] = entry
out({"jsonrpc": "2.0", "id": rid, "method": "session/request_permission", "params": {
"sessionId": sid,
"toolCall": {"toolCallId": call, "title": "make build", "kind": "execute", "status": "pending", "rawInput": {"command": "make build"}},
"options": [{"optionId": "once", "kind": "allow_once", "name": "Allow once"},
{"optionId": "session", "kind": "allow_always", "name": "Always, this session"},
{"optionId": "deny", "kind": "reject_once", "name": "Deny"}],
"_meta": {"lembas": {"tool": "bash", "reason": "the rules ask about this command"}}}})
# The device stops waiting (its time ran out, or it was answered at a terminal): the card is taken down.
def settle():
# Whatever the client answers from here on is not read: the call was refused already.
waiting.pop(rid, None)
notify("_lembas/permission/settled", {"sessionId": sid, "toolCallId": call})
entry[0].set()
threading.Timer(0.2, settle).start()
entry[0].wait(30)
say(sid, "\nanswer=deny (Nobody answered the approval in time, so it was refused.)")
elif "PERM" in text:
args = {"command": "rm -r build"}
got = approval(sid, "bash", "execute", "rm -r build", args, "deletes files")
if got == "deny":
tool_denied(sid, "call_p", "bash", "execute", "rm -r build", args, "The user denied this call.")
say(sid, "\nanswer=" + got)
if "WRITE " in text:
path = word_after(text, "WRITE")
old = read_disk(path) if os.path.exists(path) else None
new = "rewritten by the agent\n"
run_tool(sid, "write", "edit", "write " + os.path.basename(path), {"path": path, "content": new},
lambda: (write_disk(path, new), "Wrote " + path)[1], [{"path": path, "oldText": old, "newText": new}])
if "READ " in text:
path = word_after(text, "READ")
got = {}
def read():
got["text"] = tool_read(sid, path)
return got["text"]
run_tool(sid, "read", "read", "read " + os.path.basename(path), {"path": path}, read)
say(sid, "\nread=" + json.dumps(got.get("text")))
if "PUT " in text:
path = word_after(text, "PUT")
got = {}
def put():
if os.path.exists(path):
guard(sid, path)
got["by"] = "client" if put_text(sid, path, "put by the agent\n") else "disk"
return "Wrote " + path
run_tool(sid, "write", "edit", "write " + os.path.basename(path), {"path": path, "content": "put by the agent\n"}, put)
say(sid, "\nput=" + got.get("by", "refused"))
if "EDIT " in text:
path = word_after(text, "EDIT")
got = {}
def edit():
guard(sid, path)
before = file_text(sid, path)
first, sep, rest = before.partition("\n")
after = first.upper() + sep + rest
got["files"] = [{"path": path, "oldText": before, "newText": after}]
got["by"] = "client" if put_text(sid, path, after) else "disk"
return "Edited " + path
run_tool(sid, "edit", "edit", "edit " + os.path.basename(path), {"path": path}, edit, lambda: got.get("files"))
say(sid, "\nedit=" + got.get("by", "refused"))
if "SHOW " in text:
say(sid, "\nshown=" + json.dumps(show(sid, s, text), sort_keys=True))
if "QUESTION" in text:
say(sid, "\nquestion=" + json.dumps(question(sid, "MULTI" in text), sort_keys=True))
if "PLANCARD" in text:
say(sid, "\nplan=" + json.dumps(plan_card(sid), sort_keys=True))
if "CRASH" in text:
sys.stderr.write("error: the session store could not be opened\n")
sys.stderr.flush()
os._exit(3)
if "SLOW" in text.replace("SLOWC", "").replace("SLOWE", ""):
got = s["cancel"].wait(10)
s["cancel"].clear()
return "cancelled" if got else "end_turn"
return "end_turn"
TEXT_KINDS = {"md": ("markdown", None), "html": ("html", None), "py": ("code", "python"), "js": ("code", "javascript"),
"ts": ("code", "typescript"), "lua": ("code", "lua"), "csv": ("table", None), "svg": ("svg", None)}
MEDIA = {"png": ("image", "image/png"), "jpg": ("image", "image/jpeg"), "gif": ("image", "image/gif"), "pdf": ("pdf", "application/pdf"),
"mp3": ("audio", "audio/mpeg"), "mp4": ("video", "video/mp4"), "zip": ("archive", "application/zip")}
def show(sid, s, text):
"""The show tool: a text file with its content, any other file by a handle (and, on stdio, where it is)."""
if not client["show"]:
return {"shown": False, "reason": "the show tool is not offered to this client"}
path = word_after(text, "SHOW")
with open(path, "rb") as f:
data = f.read()
rel = os.path.relpath(path, s["root"])
ext = os.path.splitext(path)[1][1:].lower()
call = "call_show_" + uuid.uuid4().hex[:6]
if b"\0" not in data and ext not in MEDIA:
kind, language = TEXT_KINDS.get(ext, ("text", None))
if not client["media"] and kind in ("table", "svg"):
kind = "text"
params = {"sessionId": sid, "toolCallId": call, "path": rel, "kind": kind, "text": data.decode("utf-8")}
if language:
params["language"] = language
if " AT " in text:
params["line"] = int(word_after(text, "AT"))
answer, error = ask("_lembas/show", params, 30)
else:
if not client["media"]:
return {"shown": False, "reason": "not a text file"}
kind, mime = MEDIA.get(ext, ("binary", "application/octet-stream"))
handle = "h_" + str(uuid.uuid4())
handles[handle] = data
digest = "0" * 64 if "BADHASH" in text else hashlib.sha256(data).hexdigest()
answer, error = ask("_lembas/show", {
"sessionId": sid, "toolCallId": call, "path": rel, "kind": kind, "mimeType": mime, "size": len(data),
"hash": "sha256:" + digest, "handle": handle, "uri": "file://" + "/".join(quote(x) for x in os.path.abspath(path).split("/"))}, 30)
handles.pop(handle, None)
if error or not isinstance(answer, dict):
return {"shown": False, "reason": "the client did not show it"}
if answer.get("shown") is True:
return {"shown": True}
reason = answer.get("reason")
return {"shown": False, "reason": reason if isinstance(reason, str) and reason else "the client did not show it"}
def quote(part):
from urllib.parse import quote as q
return q(part, safe="")
def question(sid, multiple):
"""`_lembas/question`, and its answer as the CLI reads it (`questionReplyFrom`)."""
questions = [{"header": "Database", "question": "Which backend?", "multiple": multiple, "options": [
{"label": "SQLite", "description": "local file", "recommended": True}, {"label": "Postgres", "description": "server"}]},
{"header": "Name", "question": "What is it called?", "multiple": False, "options": []}]
phase(sid, "waiting_for_person")
answer, error = ask("_lembas/question", {"sessionId": sid, "toolCallId": "call_q_" + uuid.uuid4().hex[:6], "why": "Need a choice",
"questions": questions, "_meta": {"lembas": {}}})
if error or not isinstance(answer, dict) or answer.get("outcome") != "answered" or not isinstance(answer.get("answers"), list):
return {"dismissed": True}
answers = []
for i, a in enumerate(answer["answers"]):
if i >= len(questions):
break
if isinstance(a, dict) and a.get("kind") == "options" and isinstance(a.get("labels"), list):
answers.append({"kind": "options", "labels": [x for x in a["labels"] if isinstance(x, str)]})
elif isinstance(a, dict) and a.get("kind") in ("custom", "back") and isinstance(a.get("text"), str):
answers.append({"kind": a["kind"], "text": a["text"]})
elif a is None or (isinstance(a, dict) and a.get("kind") == "skipped"):
answers.append(None)
else:
return {"dismissed": True}
return {"answers": answers}
def plan_card(sid):
"""`_lembas/plan`, and its answer as the CLI reads it (`planReplyFrom`)."""
plan = {"version": 1, "title": "Upgrade", "summary": "", "findings": [], "objectives": [],
"phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "todo"}]}]}
phase(sid, "waiting_for_person")
answer, error = ask("_lembas/plan", {"sessionId": sid, "toolCallId": "call_plan_" + uuid.uuid4().hex[:6], "path": ".agent/plans/upgrade.md",
"text": "# Upgrade\n\n- Step 1\n- Step 2", "plan": plan, "_meta": {"lembas": {}}})
a = answer if isinstance(answer, dict) and not error else {}
if a.get("outcome") == "approve":
mode = "manual" if a.get("mode") == "manual" else "edit"
set_mode(sid, mode)
return {"kind": "approve", "mode": mode}
if a.get("outcome") == "revise" and isinstance(a.get("feedback"), str) and a["feedback"].strip():
return {"kind": "revise", "feedback": a["feedback"].strip()}
return {"kind": "dismissed"}
# ---- the editor's methods (acp.md *An editor as the client*) ----------------------------------
def login_or_refuse():
if not LOGGED_IN:
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_EDITOR, "not_logged_in")
def editor_settings():
return {"autocomplete": {"model": settings["autocomplete_model"], "source": "person" if settings["autocomplete_model"] else None, "allowed": ALLOWED},
"main": {"model": settings["main_model"]}}
def complete(msg):
p = msg["params"]
cid = p.get("id") if isinstance(p.get("id"), str) and p.get("id") else None
mine = threading.Event()
with complete_lock:
before = completion[0]
completion[0] = (cid, mine)
if before:
before[1].set() # a newer request stops the older, which is answered as cancelled
try:
model = p.get("model") or settings["autocomplete_model"]
if not model:
return refuse(msg, INVALID_PARAMS, "No autocomplete model is chosen. Choose one in your settings on the server.", "no_model")
if model not in [m["id"] for m in MODELS]:
return refuse(msg, INVALID_PARAMS, f"{model} is not a model of this account.", "unknown_model")
if model not in ALLOWED:
return refuse(msg, INVALID_PARAMS, "Model C is not allowed for autocomplete.", "not_allowed")
prefix = p["prefix"]
if "FAILC" in prefix:
return refuse(msg, INTERNAL_ERROR, "autocomplete failed on the server (502)")
if "BUSYC" in prefix:
return refuse(msg, INVALID_PARAMS, "too many completions at once — the next keystroke will try again", "busy")
mine.wait(10 if "SLOWC" in prefix else 0.05)
if mine.is_set():
return result(msg, {"text": "", "cancelled": True})
if "TWO" in prefix:
text = "tail()\n second line"
else:
last = prefix.split()[-1] if prefix.split() else ""
text = "<" + last + "|" + model + ">"
result(msg, {"text": text, "model": model, "finish": "stop"})
finally:
with complete_lock:
if completion[0] and completion[0][1] is mine:
completion[0] = None
def edit(msg):
p = msg["params"]
eid = p.get("id") if isinstance(p.get("id"), str) and p.get("id") else None
mine = threading.Event()
rewrites[mine] = eid
try:
if "EMPTYE" in p["instruction"]:
return refuse(msg, INTERNAL_ERROR, "the model answered with no text for this selection — try again, or say more in the instruction")
if "SLOWE" in p["instruction"]:
mine.wait(10)
if mine.is_set():
return result(msg, {"text": "", "cancelled": True})
text = p["text"]
if p["instruction"].startswith("REPLACE "):
new = p["instruction"][len("REPLACE "):].replace("\\n", "\n")
elif "SAME" in p["instruction"]:
new = text
elif "ADDLINE" in p["instruction"]:
# The first line in capitals, a line added after the second, the rest as it was.
lines = text.split("\n")
new = "\n".join([lines[0].upper()] + lines[1:2] + [" # added by the rewrite"] + lines[2:])
else:
new = text.upper()
# The text ends with a line break exactly when the selection did.
new = new.rstrip("\n") + ("\n" if text.endswith("\n") else "")
if eid:
half = len(new) // 2
for piece in (new[:half], new[half:]):
if piece:
notify("_lembas/edit/delta", {"id": eid, "delta": piece})
model = p.get("model") or (sessions[p["sessionId"]]["model"] if p.get("sessionId") else settings["main_model"] or "example/model-a")
result(msg, {"text": new, "model": model})
finally:
rewrites.pop(mine, None)
def list_files(root, query, limit):
"""The project's files and folders matching `query`; an empty query gives the recent ones, and nothing is recent here."""
if not query:
return []
q = query.lower()
found = []
for base, dirs, names in os.walk(root):
dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d != "node_modules")
rel = os.path.relpath(base, root)
for d in dirs:
found.append((os.path.join(rel, d) if rel != "." else d, "dir"))
for n in sorted(names):
if not n.startswith("."):
found.append((os.path.join(rel, n) if rel != "." else n, "file"))
return [{"path": path.replace(os.sep, "/"), "kind": kind} for path, kind in found if q in path.lower()][:limit]
def directory_of(p):
"""A session's directory, or `cwd`: absolute and a directory, as `session/new` asks."""
sid = p.get("sessionId") if isinstance(p.get("sessionId"), str) else ""
if sid:
if sid not in sessions:
raise Refusal(INVALID_PARAMS, "no such session")
return sessions[sid]["cwd"]
cwd = p.get("cwd").strip() if isinstance(p.get("cwd"), str) else ""
if not cwd or not os.path.isabs(cwd):
raise Refusal(INVALID_PARAMS, "a sessionId, or a cwd that is an absolute path")
if not os.path.isdir(cwd):
raise Refusal(INVALID_PARAMS, f"{cwd} is not a directory on this machine")
return cwd
def session_of(p):
s = sessions.get(str(p.get("sessionId") or ""))
if not s:
raise Refusal(INVALID_PARAMS, "no such session")
return s
def session_result(s, extra=None):
return {"sessionId": s["id"], **(extra or {}),
"modes": {"currentModeId": s["mode"], "availableModes": [{"id": m, "name": m} for m in MODES]},
"_meta": {"lembas": {"model": s["model"], "mode": s["mode"], "effort": "default", "instance": False}}}
def open_session(sid, cwd, mode, model):
s = {"id": sid, "cwd": cwd, "root": cwd, "mode": mode, "model": model, "working": False, "cancel": threading.Event(), "seen": {}}
sessions[sid] = s
return s
def after_answer(fn):
threading.Timer(0.01, fn).start()
def handle(msg):
method = msg.get("method")
p = msg.get("params")
p = p if isinstance(p, dict) else {}
msg["params"] = p
is_request = msg.get("id") is not None
if method == HANG:
return
if method == "initialize":
said = ((p.get("clientCapabilities") or {}).get("_meta") or {}).get("lembas")
fs = (p.get("clientCapabilities") or {}).get("fs") or {}
client["lembas"] = bool(said)
said = said if isinstance(said, dict) else {}
client["protocol"] = said.get("protocol") if isinstance(said.get("protocol"), (int, float)) else 1
client["show"] = said.get("show") is True
client["editor"] = said.get("editor") is True and HAS_EDITOR
client["media"] = said.get("media") is True and HAS_EDITOR
client["read"] = fs.get("readTextFile") is True and HAS_EDITOR
client["write"] = fs.get("writeTextFile") is True and HAS_EDITOR
capabilities = [c for c in CAPABILITIES if HAS_EDITOR or c not in ("editor", "media")]
return result(msg, {
"protocolVersion": 1,
"agentCapabilities": {"loadSession": False, "promptCapabilities": {"image": True, "audio": False, "embeddedContext": True},
"mcpCapabilities": {"http": False, "sse": False}},
"authMethods": [],
"agentInfo": {"name": "LLeMbas CLI", "version": VERSION},
"_meta": {"lembas": {"protocol": 3, "harness_spec": "3.11.0" if HAS_EDITOR else "3.10.0", "limits": None, "connection": None,
"capabilities": capabilities,
**({"min_client": os.environ["FAKE_AGENT_MIN_CLIENT"]} if os.environ.get("FAKE_AGENT_MIN_CLIENT") else {})}}})
if method == "authenticate":
return result(msg, {})
if method == "session/new":
cwd = p.get("cwd") if isinstance(p.get("cwd"), str) else ""
if not cwd or not os.path.isabs(cwd):
raise Refusal(INVALID_PARAMS, "cwd must be an absolute path")
if not os.path.isdir(cwd):
raise Refusal(INVALID_PARAMS, f"{cwd} is not a directory on this machine")
if not LOGGED_IN:
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION)
meta = p.get("_meta") if isinstance(p.get("_meta"), dict) else {}
mode = meta.get("mode") if meta.get("mode") in MODES else "manual"
model = meta.get("model") if isinstance(meta.get("model"), str) else settings["main_model"] or "example/model-a"
if model not in [m["id"] for m in MODELS]:
raise Refusal(INVALID_PARAMS, f"unknown model {model} — the server offers: " + ", ".join(m["id"] for m in MODELS))
s = open_session("ses_test" if "ses_test" not in sessions else "ses_test" + str(len(sessions)), cwd, mode, model)
after_answer(lambda: update(s["id"], {"sessionUpdate": "available_commands_update", "availableCommands": COMMANDS}))
return result(msg, session_result(s))
if method == "session/prompt":
s = session_of(p)
blocks = p.get("prompt")
if not isinstance(blocks, list):
raise Refusal(INVALID_PARAMS, "prompt must be an array of content blocks")
texts = [b["text"] for b in blocks if isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str)]
return threading.Thread(target=guarded, args=(msg, lambda: prompt(msg, s, texts[-1] if texts else "")), daemon=True).start()
if method == "session/cancel":
s = sessions.get(str(p.get("sessionId") or ""))
ran = bool(s and s["working"])
if s:
s["cancel"].set()
return result(msg, {"cancelled": "running" if ran else "none"}) if is_request else None
if method == "session/set_mode":
if p.get("modeId") not in MODES:
raise Refusal(INVALID_PARAMS, f"unknown mode {p.get('modeId')}")
s = session_of(p)
set_mode(s["id"], p["modeId"])
return result(msg, {})
if method == "_lembas/configure":
s = session_of(p)
if "model" in p:
raw = p["model"].strip() if isinstance(p["model"], str) else ""
if not raw:
raise Refusal(INVALID_PARAMS, "model must be a non-empty string")
if raw not in [m["id"] for m in MODELS]:
raise Refusal(INVALID_PARAMS, f"unknown model {raw} — the server offers: " + ", ".join(m["id"] for m in MODELS))
if raw != s["model"]:
s["model"] = raw
event(s["id"], {"type": "model", "ref": raw, "effort": "default", "connection": "example", "instance": False})
return result(msg, {"model": s["model"], "effort": "default"})
if method == "_lembas/steer":
text = p.get("text").strip() if isinstance(p.get("text"), str) else ""
if not text:
raise Refusal(INVALID_PARAMS, "nothing to send")
s = session_of(p)
if not s["working"]:
raise Refusal(INVALID_PARAMS, "this session is not working on anything; send it as a prompt")
event(s["id"], {"type": "inbox", "texts": [text], "mode": "steer"})
return result(msg, {"queued": 1})
if method == "_lembas/session/compact":
s = session_of(p)
if s["working"]:
raise Refusal(INVALID_PARAMS, "this session is working — compact it when the reply is done")
event(s["id"], {"type": "compacted", "summary": "Compacted 2 turns."})
return result(msg, {"summary": "Compacted 2 turns."})
if method == "_lembas/files/search":
root = directory_of(p)
limit = max(1, min(50, int(p.get("limit") or 20)))
return result(msg, {"root": root, "files": list_files(root, p.get("query") if isinstance(p.get("query"), str) else "", limit)})
if method == "_lembas/commands":
directory_of(p)
return result(msg, {"commands": COMMANDS})
if method in ("_lembas/sessions/list", "_lembas/sessions/resume") and not HAS_SESSIONS:
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method)
if method == "_lembas/sessions/list":
if not LOGGED_IN:
return result(msg, {"sessions": []})
cwd = p.get("cwd") if isinstance(p.get("cwd"), str) and os.path.isabs(p.get("cwd")) else "/"
return result(msg, {"sessions": [] if deleted.get(PREVIOUS["id"]) else [{**PREVIOUS, "root": cwd}]})
if method == "_lembas/sessions/resume":
sid = str(p.get("sessionId") or "").strip()
if not sid:
raise Refusal(INVALID_PARAMS, "sessionId is required")
if (sid != PREVIOUS["id"] or deleted.get(sid)) and sid not in sessions:
raise Refusal(INVALID_PARAMS, "no such session")
if not LOGGED_IN:
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION)
s = sessions.get(sid) or open_session(sid, os.getcwd(), "edit", PREVIOUS["model"])
after_answer(lambda: update(s["id"], {"sessionUpdate": "available_commands_update", "availableCommands": COMMANDS}))
return result(msg, session_result(s, {"title": PREVIOUS["title"], "cwd": s["cwd"], "turns": [
{"role": "user", "text": "earlier question", "turnId": "t1", "attachments": [{"name": "notes.md", "mimeType": "text/markdown", "size": 120}]},
{"role": "assistant", "text": "earlier answer", "reasoning": "earlier thinking",
"tools": [{"id": "call_1", "name": "read", "args": "{\"path\":\"notes.md\"}", "output": "the notes", "isError": False},
{"id": "call_2", "name": "bash", "args": "{\"command\":\"make\"}", "output": "make: no rule", "isError": True}]},
{"role": "user", "text": "⏎ the job is done", "turnId": "t2", "machine": True},
{"role": "assistant", "text": "noted", "reasoning": "", "tools": []}]}))
if method == "_lembas/session/delete":
# As the CLI answers it (src/acp/agent.ts `deleteSession`): `{deleted}`, false for a session
# it does not have; one that works is stopped first; nothing is notified on `serve --stdio`
# (`_lembas/session/deleted` goes to the LLeMbas link only).
sid = str(p.get("sessionId") or "")
s = sessions.pop(sid, None)
if s:
s["cancel"].set()
return result(msg, {"deleted": True})
if sid == PREVIOUS["id"] and LOGGED_IN and not deleted.get(sid):
deleted[sid] = True
return result(msg, {"deleted": True})
return result(msg, {"deleted": False})
if method.startswith("_lembas/") and not HAS_EDITOR and method.split("/")[1] in ("complete", "edit", "models", "editor", "show"):
if is_request:
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method)
return None
if method == "_lembas/models":
login_or_refuse()
return result(msg, {"models": MODELS, **editor_settings()})
if method == "_lembas/editor/settings":
to_set = p.get("set")
if to_set is not None:
if not isinstance(to_set, dict) or not any(k in to_set for k in settings):
raise Refusal(INVALID_PARAMS, "set must name autocomplete_model or main_model", "invalid")
for key in settings:
if key in to_set and to_set[key] is not None and (not isinstance(to_set[key], str) or not to_set[key].strip()):
raise Refusal(INVALID_PARAMS, f"{key} must be a model's id, or null for the instance's", "invalid")
login_or_refuse()
for key in settings:
if to_set and key in to_set:
if to_set[key] is not None and to_set[key] not in [m["id"] for m in MODELS]:
raise Refusal(INVALID_PARAMS, f"{to_set[key]} is not a model of this account.", "unknown_model")
settings[key] = to_set[key]
return result(msg, editor_settings())
if method == "_lembas/complete":
if not isinstance(p.get("prefix"), str):
raise Refusal(INVALID_PARAMS, "prefix must be the text before the cursor", "invalid")
login_or_refuse()
return threading.Thread(target=guarded, args=(msg, lambda: complete(msg)), daemon=True).start()
if method == "_lembas/complete/cancel":
running = completion[0]
if running and running[0] and running[0] == p.get("id"):
running[1].set()
return None
if method == "_lembas/complete/warm":
return None
if method == "_lembas/edit":
if not isinstance(p.get("text"), str) or not p["text"]:
raise Refusal(INVALID_PARAMS, "text must be the selected text", "invalid")
if not isinstance(p.get("instruction"), str) or not p["instruction"].strip():
raise Refusal(INVALID_PARAMS, "instruction must say what to do with the selection", "invalid")
if len(rewrites) >= 4:
raise Refusal(INVALID_PARAMS, "4 rewrites are already being written — wait for one, or cancel it", "busy")
if p.get("sessionId") and p["sessionId"] not in sessions:
raise Refusal(INVALID_PARAMS, "no such session", "invalid")
if not LOGGED_IN:
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION, "not_logged_in")
return threading.Thread(target=guarded, args=(msg, lambda: edit(msg)), daemon=True).start()
if method == "_lembas/edit/cancel":
for ev, eid in list(rewrites.items()):
if eid and eid == p.get("id"):
ev.set()
return None
if method == "_lembas/show/read":
data = handles.get(str(p.get("handle") or ""))
if data is None:
raise Refusal(INVALID_PARAMS, "that file is not being handed over any more — a handle is good until its _lembas/show is answered", "invalid")
offset = p["offset"] if isinstance(p.get("offset"), int) and p["offset"] > 0 else 0
length = min(1000, p["length"] if isinstance(p.get("length"), int) and p["length"] >= 0 else 1000) # small parts, so a client has to loop
part = data[offset:offset + length]
return result(msg, {"data": base64.b64encode(part).decode(), "offset": offset, "eof": offset + len(part) >= len(data)})
if is_request:
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + str(method))
return None
def guarded(msg, fn):
try:
fn()
except Refusal as e:
if msg.get("id") is not None:
refuse(msg, e.code or INTERNAL_ERROR, e.message, e.reason)
except Exception as e: # what the CLI answers when a handler throws
if msg.get("id") is not None:
refuse(msg, INTERNAL_ERROR, str(e))
def main():
for line in sys.stdin:
if not line.strip():
continue
try:
msg = json.loads(line)
except ValueError:
out({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
continue
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
continue
if LOG:
with open(LOG, "a") as f:
f.write(json.dumps(msg) + "\n")
if msg.get("method") is None:
entry = waiting.get(msg.get("id"))
if entry:
if msg.get("error"):
entry[2] = msg["error"]
else:
entry[1] = msg.get("result")
entry[0].set()
continue
guarded(msg, lambda: handle(msg))
# The client went away: what was under way goes with it.
os._exit(0)
main()