Compare commits

..
Author SHA1 Message Date
HomerandClaude Fable 5.2 62148c5f81 2.0.0-beta.11
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 15:29:44 +00:00
HomerandClaude Fable 5.2 89e9e47ecc spec 3.8.1: a page for what is to be seen, a shown file for what has to run
ci / check (push) Canceled after 0s
The pages block now says that something the person asks to see in the answer
is written as a page, not as an HTML file opened with `show`, and that a page
is static: what has to run is said to be beyond a page and, where the model has
`write` and `show`, written as a file and shown. A text; nothing else moves.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:25:25 +00:00
HomerandClaude Fable 5.2 6db5d39f6f 2.0.0-beta.10
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 12:11:40 +00:00
HomerandClaude Fable 5.2 ca849facb2 spec 3.8.0: pages are static
ci / check (push) Canceled after 0s
A scripted page in a sealed frame can still send data out (a WebRTC
datagram), and a document without script can make the browser resolve a
chosen name (link rel=dns-prefetch, preconnect, prefetch). So a page is
static everywhere: HTML, CSS and inline SVG. pages.md §6, the prompt block
and loop.json pages.static say what it may hold — the listed elements and
attributes, no script or event handler, no link, meta, base, frames,
media, canvas or forms, no address but #fragment and an inline data:image,
no @import or url() that fetches — and what a client that shows pages
does: rebuild the document from the allow-list, a frame with scripts off,
fixed height with its own scrolling, Open larger in place; a client that
cannot guarantee it shows the note. Charts are inline SVG the model writes
out. conformance/pages.json gains the static cases (src/pages/static.ts
answers them); the fence, title, note and projection are as they were.

reports.md: the creator of a schedule that runs once may store always
(scheduled.notify.one_shot_default); a device without the reports
capability is never sent an instruction naming report_write — it gets the
3.5.0 prompt (the [SILENT] hint for `when`, none otherwise).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 10:47:07 +00:00
HomerandClaude Fable 5.2 0512745ccb The comment, as a sentence
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:28:04 +00:00
HomerandClaude Fable 5.2 2afc076682 A comment that still named prototypes
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:23:14 +00:00
HomerandClaude Fable 5.2 89ade2ad5b scripts/hygiene.sh: nothing private in the tracked files, checked in CI
ci / check (push) Canceled after 0s
The same check the other LLeMbas repositories run: private domains, .lan
names, container numbers, private address ranges, machine names. Three
lines are allowed, each with its reason in the script: the public forge
the release workflow republishes from, a theme's former name read from old
configurations, and the made-up private hosts the web tool's test needs
(renamed to made-up ones). Wired into scripts/ci.sh as its first step.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:22:28 +00:00
HomerandClaude Fable 5.2 20cd2f3ae9 /reports: the schedules' reports in the TUI; /schedule asks when to notify
ci / check (push) Canceled after 0s
On the shared menu: unread first with the schedule and when; a report's
own menu — read it here (rendered in the transcript, a page as its note,
marked read), reply (the report and the person's words to this session's
agent), mark read, delete (asked once); ctrl+r and ctrl+d in the list.
/reports <id or title> reads one; lembas run prints the list or a report
as text. Built against a provisional /api/v2/reports contract, marked in
src/lembas/reports.ts. /schedule new takes notify-when: the default
condition, the person's own words, every run, never.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:21:51 +00:00
HomerandClaude Fable 5.2 551393cf40 spec 3.8.0: html_pages on the served model's type
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:18:22 +00:00
HomerandClaude Fable 5.2 fb1b0b7119 spec 3.8.0: the served model's html_pages in its type; the connections schema regenerated
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:18:06 +00:00
HomerandClaude Fable 5.2 97fb03210a Harness spec 3.8.0: reports, HTML pages in answers, which permission rule decides
ci / check (push) Canceled after 0s
reports.md, tools/report_write.json (requires: scheduled), loop.json
scheduled.notify: a schedule's run files a report or leaves a history
line; notify when always | when | never with the instruction for each, in
the run's prompt; one report per run; the answer filed under always;
[SILENT] retired. A run on a linked computer carries its report in the
turn's answer (acp.md, capability reports). conformance/reports.json.

pages.md, prompts/blocks/html-pages.md, loop.json pages, models/schema.json
html_pages: a reply may carry a complete page in an html-view fence, when
the instance, the model and the chat all say so; never to a subagent, the
phone assistant or an agent chat. The note, the text projection, the
session note. blocks/prototypes.md, the prototypes context field and
capability, and conformance/prototype.json are gone; conformance/pages.json.

permission/rules.md, conformance/rules.json: the candidate and the floors
a later-made rule gives way to, and what making a rule does — for a rule
typed into a file as for one a menu wrote.

The CLI carries it: report_write in a scheduled turn, the pages fence read
and noted in the transcript (/pages; prototypes: true dropped with a
line), the model's html_pages kept and unused, lookupRule the strictest of
the floors, judgeNewRule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:17:49 +00:00
HomerandClaude Fable 5.2 22bfb5b579 gitleaks: the made-up key the MCP redaction test must take out
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 19:08:08 +00:00
HomerandClaude Fable 5.2 dfc30afc09 Tests take away the commands and agents they write into the shared config directory
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 19:05:00 +00:00
HomerandClaude Fable 5.2 e0f0a6d7bf Tests take away the login they write into the shared config directory
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 19:02:08 +00:00
HomerandClaude Fable 5.2 ff39b9dcbc What is a command where there is no menu; /command and /skill; hidden custom commands
A command that takes no words is the command only alone, and /mcp <word>
only for a server's name: anything else is a prompt. lembas run --json
gets the text as an event and the end; a command that could not do what
was asked exits 1. /command <name> runs a custom command by name (TUI and
link), /skill works over the link, and a custom command hidden by a
built-in's name is said once at start. The start-up line for a failed MCP
server is cleaned, redacted, and promises only what every front end has.
The status bar's MCP subscription is dropped with the screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 19:02:08 +00:00
HomerandClaude Fable 5.2 db7e7f05ff MCP: a server's text is cleaned and redacted; names that collide; the menu's manners
One function (mcp/clean.ts) takes control characters out of everything a
server supplies, where it enters and where a name is shown. /mcp's text
shows an address without credentials or query, a local server by its
program's name, an error by its first line with secrets out, never stderr;
as a markdown reply, names are code and descriptions escaped. A prompt is
listed and inserted under its registered name. Both of two colliding tool
names get a hash; a library server's tools other than the one it is there
for are ordinary MCP tools. In the menu: sign-out asks once, a failure is
said once, a failed save is said, a server the user's own config switches
off is switched on for the session only (and says why).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 19:02:08 +00:00
HomerandClaude Fable 5.2 9d6c316794 Menus: fit a short terminal, keep still, take a paste, leave rows that are only read
The box is laid out in the rows there are (the detail under the list and
then the body above it give way first); a menu whose rows have a detail
keeps that space, so the list does not jump; a paste goes into the filter
or the text a menu takes (Add a rule); Enter on an inert row (a key in
/help, a /status row with nothing behind it, a line of an error) does
nothing. A finished job's line keeps the warning sign when it did not end
well.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 19:02:08 +00:00
HomerandClaude Fable 5.2 85332c2a23 A command chosen in /help or /status goes through the typed line's guard
ci / check (push) Canceled after 0s
They ran the command directly, past submit()'s mid-task check: /new,
/compact, /undo, /model and the rest could start while a reply ran. A
menu now hands the line to the same function a typed line goes through.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 18:52:42 +00:00
HomerandClaude Fable 5.2 7859237dde A rule set in a menu loosens what was chosen and no more
ci / check (push) Canceled after 0s
setRule appended a sourceless rule last, so 'read * allow' shadowed the
default 'read *.env: ask' and 'bash allow' the user's own 'rm *' deny, and
wrote it to the project. Now: choosing what is in force is a no-op; a rule
the user's own config or a written deny takes in whole is refused; a rule
that is made is a project's rule in the session as in the saved file, and
a rule made after the written ones (project, 'always', menu) decides what
a broader rule decided, never what a narrower stricter one did — lookupRule
keeps the strictest narrower match. The menu says where the rule holds,
whether it was saved (a failed save is said), and which stricter rules
still apply. Removing a session rule removes its saved copy.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 18:52:10 +00:00
HomerandClaude Fable 5.2 98aa346c34 Tests: the start-up checks look at MCP's own notices (the suite shares one config directory)
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 17:36:29 +00:00
HomerandClaude Fable 5.2 dc4f9e89c7 The no-menu text of /mcp, /permissions and /status is a list
ci / check (push) Canceled after 0s
Lines begin with "- " instead of an indent: one to a line in a terminal
and where the reply is drawn as markdown (the web UI).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 17:32:31 +00:00
HomerandClaude Fable 5.2 dd9cb9135f /help, /permissions, /status and /agents as menus on the shared one
ci / check (push) Canceled after 0s
/help: every command under a heading, found by typing, run or put in the
box. /permissions (new): the rules in force by where they were made;
change, add, remove. /status (new): server, model, session, project, MCP
and terminal on one screen, what needs attention marked, enter opens what
changes it. /agents: a menu. Each has its text for where there is no menu
(session/report.ts): over the link, and lembas run now prints a
message-kind command instead of sending it to the model.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 17:31:40 +00:00
HomerandClaude Fable 5.2 6887f9e414 A /mcp menu, on the shared menu component
ci / check (push) Canceled after 0s
The dialog every picker uses gains sections, state marks, a body, a line
about the highlighted row, esc-goes-back, paging and a position in long
lists. /mcp is a menu on it: the servers by where they come from, with
state and what they offer; a server's actions (reconnect, off/on — kept
for a trusted project —, sign in/out, the last error in full), its tools
with their permission rule, changeable there (engine.setRule: the session,
and the project when trusted; never under the user's own stricter rule),
and its prompts. /mcp <name> opens one. Where there is no menu — over the
link, lembas run — /mcp is a plain table (mcp/text.ts).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 17:26:50 +00:00
HomerandClaude Fable 5.2 f7632ad232 A connected MCP server is not a warning; one table for notice kinds
ci / check (push) Canceled after 0s
Every bus notice was drawn with the warning sign, whatever it said, and a
server that connected said so at each start. A connect now says nothing
(the status bar counts: MCP 2, MCP 1/2); a server that failed or needs a
sign-in gets one line naming it and /mcp <name>. Notices carry a level —
info, success, warn, error — drawn from one table (tui/notices.ts) in the
transcript and in lembas run; the informational ones say so.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 17:20:19 +00:00
HomerandClaude Fable 5.2 53372f88ec 2.0.0-beta.9
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:27:24 +00:00
HomerandClaude Fable 5.2 8ad31deaa8 Review of the round: placeholders over a selection, the kitty read, titles, the stored end
ci / check (push) Canceled after 0s
Paste placeholders: the extmark is placed from the cursor after the insert
(a paste over a selection put it at the wrong range and sent the bare
label); a placeholder is atomic (cutting into its label removes all of
it); the same paste opens a placeholder only with the cursor where the
first paste left it; a paste of white space is not a clipboard read; a
data URL that is no image is pasted as text. The label is shown in this
transcript only: the prompt event and the session's title get the words.

kitty OSC 5522: the box's input is held during a read, input that arrives
meanwhile means a packet was lost (OpenTUI flushes an unfinished OSC after
about 20 ms), what arrives is believed by its bytes and must be a whole
image — else one line and nothing saved. It can still fail on a stalling
connection, so it is off unless kitty_clipboard: true.

The approval card over the link keeps the whole command (or the tool's
name) as its title and carries _meta.lembas.tool; spec text says so. The
stored end of a turn is tied to the conversation's length, so /undo, a
rewind or a compaction takes it away. A refused call is titled from
schema-parsed arguments. A stored call with no result is failed; the
person's own !command is not failed by the turn's end; 59.96 s is 1m 00s
(conformance case).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:32:04 +00:00
HomerandClaude Fable 5.2 495f89006c Review fixes: a refused call is announced over ACP; dictation keeps a placeholder
ci / check (push) Canceled after 0s
A denied call was sent as a tool_call_update of an id no plain ACP client
had been given (the approval card carries its own), which a client drops:
it is one tool_call, failed, with its title, arguments and reason, and
_meta.lembas.denied. acp.md says so.

Dictated text is inserted at the end of the box instead of setting its
whole text, which dropped every paste placeholder.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:10:51 +00:00
HomerandClaude Fable 5.2 b800c74068 Display per spec 3.7.0: one title for a call, the end of a reply, locale numbers
ci / check (push) Canceled after 0s
callTitle is the one title of a tool call: on the tool_start event, in the
transcript (argSummary is gone), as running_tool's what (callWhat is
gone), in lembas run and as the link's tool_call title; a refused call
carries _meta.lembas.denied and its title. A finished call shows what its
result adds and how long it took; a denied one its reason and no time; a
call still running when its turn ends is failed.

stopped and failed are drawn as the spec's line on the reply (budget too),
once, in the TUI and in lembas run, and kept with the session (meta
'ended') so a resumed session says it again. waiting_for_subagents counts
the foreground task calls and the session's running subagent jobs. Numbers
go through the terminal's locale; the working line has one clock.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:09:14 +00:00
HomerandClaude Fable 5.2 a3befd866d Clipboard images through the host clipboard; images over SSH
ci / check (push) Canceled after 0s
ctrl+v reads the clipboard with OpenTUI's createHostClipboard (macOS,
Windows, Wayland, X11; PNG, JPEG, WebP, GIF, known by their bytes), with
wl-paste / xclip behind it, awaited instead of spawnSync so the screen is
never held. Pasted copies live in the state directory's clipboard/ and go
after a week.

Over SSH: an image pasted as a data URL or bare base64 is decoded,
size-checked, saved and shown as [Image N]; with a forwarded X display the
X clipboard is read; in kitty the terminal is asked for its clipboard over
OSC 5522 (listed first, then read with a name and password so it asks
once), through renderer.subscribeOsc; and when nothing came through, one
line names the ways that work.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:57:00 +00:00
HomerandClaude Fable 5.2 4d14290cec Paste placeholders in the prompt box
ci / check (push) Canceled after 0s
A paste of three lines or more, or over 150 characters, is shown as
[Pasted text N lines] / [Pasted text N chars]; an image as [Image N],
numbered after the highest in the box. They are OpenTUI extmarks over the
label; the content is kept beside them and sent in full (an image as its
@path). Deleting a placeholder removes its content; the same paste again
opens it. The transcript shows the box as it looked; history, /undo, a
refused send and a copy of a selection in the box use the full text.
paste: full shows pastes whole.

The box's offsets are columns: the @file list and the edge-line check now
take text by range instead of slicing by offset.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:50:14 +00:00
HomerandClaude Fable 5.2 bba0428c3b The device's terminal picks a shell that exists; plainer refusals
ci / check (push) Canceled after 0s
pickShell: $SHELL where it exists, else bash, zsh, sh, as a login shell;
on Windows pwsh, then powershell, then ComSpec/cmd, without -l. A spawn
that fails (the runtime's PTY is POSIX's) is a one-line refusal, not an
internal error. The refusals for terminals switched off, a folder outside
the allowed ones, a missing folder and too many terminals say what to do.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:44:24 +00:00
HomerandClaude Fable 5.2 14a35d04b6 Harness spec 3.7.0: python says why it could not run
ci / check (push) Canceled after 0s
tools/python.json: unavailable is now only "no page of this chat is open"
and says where to open it; texts.no_answer (a page is open but did not
answer) and texts.timeout (the run passed its seconds) are their own
texts. conformance/python.json; the server's tool alone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:42:10 +00:00
HomerandClaude Fable 5.2 bf44371841 Harness spec 3.7.0: one display in every client
ci / check (push) Canceled after 0s
harness/display.md, loop.json display, conformance/display.json.
A tool call has one short title made from its arguments (questions and
patch by what they name, else the first non-blank string among the listed
keys; first line, 80 characters): the same in the transcript, as
running_tool's what and as the link's tool_call title. Pattern and query
now come before path, so a grep is titled by its pattern. Four states
(running, done, failed, denied), a finished call's duration, an edit's
+added −removed counted by the diff's hunks, a command's non-zero exit, a
search's hits; the kinds of block. stopped and failed stay on the finished
reply as the progress text alone. The approval, question and plan cards'
actions. Numbers in the client's locale format; conformance texts plain.

The pure functions (src/session/display.ts) answer the new area; the
clients' drawing follows. progress gains the budget stop; the README's
lost 3.5.0 heading is back.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:39:32 +00:00
HomerandClaude Opus 5.5 7627c342d6 2.0.0-beta.8
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:19:28 +00:00
HomerandClaude Opus 5.5 38a52d2e7f Harness 3.6.0: phone conformance uses fictional places
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:48:19 +00:00
HomerandClaude Opus 5.5 6da9c7fcd0 Harness spec 3.6.0: phone_action, done on the person's phone and confirmed there
ci / check (push) Canceled after 0s
harness/phone.md, tools/phone_action.json, loop.json phone, conformance/phone.json.
The LLeMbas server's tool alone (scope llembas, sessions chat), offered once a
message came from the LLeMbas app with the capability phone_actions (new
requirement phone). Actions: alarm, timer, calendar_event, sms_draft,
email_draft, dial, navigate, add_stop, search_nearby, stop_navigation,
open_app, open_url, media, torch, settings_panel, automation_intent. Each
reads its own fields; required fields and value checks give the call's
refusal in the spec's words. The person confirms on the phone every time;
the result is done, declined or failed with what the phone said, or no
answer in time. add_stop carries the route's destination: no map app adds
to a running route, so the phone plans again via the stop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:32:15 +00:00
HomerandClaude Opus 5.5 7f7cd148aa 2.0.0-beta.7
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:02:24 +00:00
HomerandClaude Opus 5.5 cb7800cc6e Reserved command names: rename, schedule, schedules and search are the TUI's
ci / check (push) Canceled after 0s
The shared-command test caught the four new TUI commands missing from TUI_COMMAND_NAMES, so a
project command could have taken one of their names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:57:52 +00:00
HomerandClaude Opus 5.5 a3e9a43dd6 Parity gaps: the finished-reply notice (bell and OSC 9 while unfocused; notify: false), /rename, /search over this machine's sessions, /memory shows the server's memory
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:23:17 +00:00
HomerandClaude Opus 5.5 a4027d5626 /schedule: list, create from words (the server's compile, a preview first, optionally to run here), pause, resume, run now, history — over /api/v2 with the device's token (spec 3.5.0)
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:18:49 +00:00
HomerandClaude Opus 5.5 d111cad22e Scheduled work on this computer (spec 3.5.0): Accept scheduled work, scheduled turns, the watch command; team_add names the sub-manager
ci / check (push) Canceled after 0s
remote.scheduled (lembas service scheduled on|off, lembas remote scheduled on|off) said as
limits.scheduled; a scheduled session runs in the schedule's mode (Edit when none, Plan refused,
lowered to max_mode), reports ok/silent/failed/cancelled and the final reply, waits the
schedule's wait on approvals and offers no question, plan card or show. _lembas/monitor judges
the watch command by the mode (ask is refused) and hashes the output as it streams.
Conformance areas scheduled, silent and monitor run here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:16:54 +00:00
HomerandClaude Opus 5.5 788db0ff4d Harness spec 3.5.0: the watch command's hash puts the exit status after the bytes, so the output is hashed as it streams
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:13:38 +00:00
HomerandClaude Opus 5.5 e349d829a1 Harness spec 3.5.0: scheduled work on a linked computer
ci / check (push) Canceled after 0s
Accept scheduled work (remote.scheduled, off by default) said as limits.scheduled; a scheduled
turn is an agent session marked `scheduled` in the schedule's mode (Edit when none chosen, Plan
refused, lowered to remote.max_mode) with its Min/Max; the answer reports status ok, silent,
failed or cancelled and the final reply. Approvals wait the schedule's wait and go to the person
through the server, then count as denied. _lembas/monitor runs a watch command under the mode's
rules (one that would ask is refused) and answers a hash and an excerpt. Schedule routes of
/api/v2 accept the device's token. team_add under a sub-manager names it (added_under).
Conformance areas scheduled, silent, monitor; team cases changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:11:56 +00:00
HomerandClaude Opus 5.5 fe0fa62a51 2.0.0-beta.6
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:29:56 +00:00
HomerandClaude Opus 5.5 f3db970c9d Team events: a change inside the pace window is said at its end, so the last state always goes out; the main agent waiting for a slot is the waiting_for_model phase
ci / check (push) Canceled after 0s
Found by the full suite: the link's tree could miss a subagent's last change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:38:12 +00:00
HomerandClaude Opus 5.5 ae1201540a CHANGELOG: Unreleased — harness spec 3.4.0 (progress phases, subagents v2)
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:32:34 +00:00
HomerandClaude Opus 5.5 b70cfe483b The link (spec 3.4.0): capabilities progress, tree and agents; the team event carries the tree; _lembas/team, /transcript, /findings, /stop; progress and tree in status; subagent on an approval; an agent chat's Min/Max and said read per turn
ci / check (push) Canceled after 0s
acp.md: a turn without agents keeps the device's own setting (an older server), as before 3.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:32:03 +00:00
HomerandClaude Opus 5.5 ecfd1b0b8a TUI (spec 3.4.0): the spinner line is the progress phase; /team shows the tree with each agent's phase, context and messages; /team open (a subagent's session, read-only), /team findings, /context <subagent>
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:28:28 +00:00
HomerandClaude Opus 5.5 8c5edc0f01 Subagents v2 in the CLI (harness spec 3.4.0): the main agent's tree, modes and requests, findings, finishing and running out of context; progress phases
ci / check (push) Canceled after 0s
team/team.ts: ids, positions, parents; only the main agent adds, assigns, replaces, stops and
decides; sub-managers; slots; modes inherited and never widened, request options and grants;
findings; team_finish; pause and out_of_context; ended subagents kept; the tree's data.
Seven new tools. A subagent's call is decided by team/delegation.ts (itself, the main agent
through a request, or the person). Its engine does not compact: at pause_at it is paused and
gets one final turn. Every engine says its progress as phase events (session/progress.ts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:21:29 +00:00
HomerandClaude Opus 5.5 b66891e186 Harness spec 3.4.0: an agent chat's subagents are the device's; the tree's cases
ci / check (push) Canceled after 0s
acp.md *Subagents in an agent chat*: capability agents carries the chat's {min, max} (and
subagents: false) down on every turn and _lembas/configure, said (the person's earlier words)
on session/new; the tree, progress, approvals, findings and transcripts come up; what the server
keeps. subagents.md §14. team.json: ten 3.4.0 cases (only the main agent, sub-managers and parent,
slots, modes and request options, whoami, finish, findings, running out of context and replacing,
requests and decisions, assign); a member's own task is refused only_main. subagents.md: the
subagents under a sub-manager that ended by itself move under its parent until it is replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:19:17 +00:00
HomerandClaude Opus 5.5 6199028358 Progress phases and delegation rules (harness spec 3.4.0): the text and line of each phase, who decides a subagent's call
ci / check (push) Canceled after 0s
Conformance areas progress and delegation pass. delegation.json: own_reason marks the cases
whose deny reason is each project's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:12:29 +00:00
HomerandClaude Opus 5.5 4b8786b7f6 Harness spec 3.4.0: progress phases, and subagents v2 — the main agent and its tree
ci / check (push) Canceled after 0s
progress.md: thirteen fixed phases (queued … failed), each { phase, since, data },
their texts as shared i18n keys (loop.json progress), one line every client draws,
sent beside the old status text in /api/v2 and over the link (capability progress).

subagents.md §5–§13 (supersedes team.md where they differ): only the main agent
adds, assigns, replaces, stops and decides; sub-managers direct those placed under
them; ids, positions, parents; Min above 1 opens slots; permissions inherited and
never widened, request options decided by the main agent, what nobody in the tree
can allow goes to the person; team_finish, findings, running out of context;
transcripts read-only; the tree over the link (capability tree). New tools
team_whoami, team_finish, team_findings, team_request, team_decide, team_assign,
team_replace. Conformance: progress, delegation; team updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:10:36 +00:00
HomerandClaude Opus 5.5 6a0e0ed145 Subagents: Min and Max, one range with two handles, counting this agent (harness spec 3.3.0)
ci / check (push) Canceled after 0s
/effort's Subagents row and /team size are a two-handle range from 1 to the cap (left/right move
the handle in focus, tab the other, enter sets both); the dialog gains a range row. Every text says
Min and Max, never fewest/most, and that the count includes this agent: "Subagents: Min 1, Max 4 -
1 is this agent alone". /settings shows the same beside agents.min / agents.max; config schema
and the bounds refusal likewise. CHANGELOG in the 2.0.0-beta.5 section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:09:31 +00:00
HomerandClaude Opus 5.5 3a206959b6 Harness spec 3.3.0: the Subagents setting is Min and Max, one range with two handles, counting the agent itself
ci / check (push) Canceled after 0s
loop.json subagents.setting: min/max are "Min" and "Max" (not fewest/most), with a hint and a short
form saying the numbers include the session's own agent - 1 is the agent alone, Max 4 the agent and
up to three subagents. team.md §2 and subagents.md §4 state that, and the UI rule: one range from 1
to the cap with two handles (a slider; two numbers on one line in a terminal). team_add says the
size includes the caller. Conformance team: max 2 is the lead and one task subagent.

Still 3.3.0, unreleased: edited in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:04:24 +00:00
HomerandClaude Opus 5.5 6993937522 2.0.0-beta.5
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:01:14 +00:00
HomerandClaude Opus 5.5 f88921667e CHANGELOG: the 2.0.0-beta.4 entry that was missed at release
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:09:36 +00:00
HomerandClaude Opus 5.5 0c3596d044 The model roster in the prompt: a subagent runs on another model only when the person names it (spec 3.3.0)
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:08:49 +00:00
HomerandClaude Opus 5.5 6e0582dc22 Subagents in the CLI (harness spec 3.3.0): the model, capacity, the offer, /context
ci / check (push) Canceled after 0s
- A task subagent or a team member runs on the session's model unless the
  person named another in this session's own messages (team/subagents.ts;
  engine.personSaid reads every prompt and mid-turn message, compacted ones
  included). Not named: refused; an agent file's own model is not used.
- Another model on the session's one-model server is refused; a one-request
  session model is not its own subagent, and nothing else is picked.
- The team is offered when a model could serve: the session's with two
  slots, or any usable model off its one-model server; the size note adds
  team_own when the session's model cannot serve its own.
- "Subagents" in /effort, /team, /settings and the config schema; the status
  bar reads "agents 3/4 · 2 subagents working".
- /context: used of the window, one bar by category, each category's share,
  what is free, and "N until auto-compact".
- Conformance runner for the subagents area (26 cases); helper -> task.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:04:58 +00:00
HomerandClaude Opus 5.5 a26dd8a5e0 Harness spec 3.3.0: name its spec commit (02c7282) in the README and CHANGELOG
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:56:45 +00:00
HomerandClaude Opus 5.5 02c7282e74 Harness spec 3.3.0: subagents — the word, the model, capacity, the offer
ci / check (push) Canceled after 0s
- "Subagent" in every text a person or a model reads; "helper" retired
  (the team area's step helper_done is now task_done).
- A subagent runs on the session's model unless the person named another
  in this session's own messages; task's and team_add's `model` is refused
  otherwise. No setting chooses a subagent's model.
- Capacity: another model on the session's model's one-model server is
  refused; the session's model as its own subagent needs parallel >= 2 or
  no limit; no fallback.
- The agents {min, max} setting is shown as Subagents, offered when a model
  could serve; context.note.team_own when the session's model cannot.
- subagents.md, loop.json subagents, conformance/subagents.json (26 cases).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:56:31 +00:00
HomerandClaude Opus 5.5 9499e93bc4 lembas login: a refused sign-in starts a new one; 2.0.0-beta.4
ci / check (push) Canceled after 0s
With a stored login for the same server, login only refreshed it; a 401
said "run login again", which did the same again. A SignInRejected from
the refresh now falls through to a fresh device login, which replaces the
old one. The installer's last line points at lembas login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:26:55 +00:00
HomerandClaude Opus 5.5 6a82e6cb61 2.0.0-beta.3
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:40:15 +00:00
HomerandClaude Opus 5.5 536fd2aa45 Teams: a sub-manager's member is no looser than its manager's mode (team.md §4)
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:12:33 +00:00
HomerandClaude Opus 5.5 d3af8c2f02 Changelog: harness spec 3.2.0 in the CLI — teams, levels, reasoning, paths
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:11:41 +00:00
HomerandClaude Opus 5.5 6ec95fbd66 Teams in the CLI (harness spec 3.2.0, team.md)
ci / check (push) Canceled after 0s
The four team tools (tool/team_tools.ts) on the rules of team/team.ts,
driven from real turns by team/runtime.ts:

- Members run on the subagent job machinery (app.ts spawn with `member`):
  background, unattended, their own prompt from blocks/team_member.md
  (the whole of team_lead.md for one with lead: true), team_send and
  team_read (team_add and team_stop for one that leads). Not jobs to the
  model: job_list and the job_* tools skip them; a client over the link
  still sees them as subagent jobs named "<name>: <role>".
- The room: messages and reports with their marks, delivered at the next
  step boundary or waking a finished member or the idle lead; report
  posts to the manager.
- A manager's work calls answer the refusal before the permission check,
  by risk class (an MCP tool by its readOnlyHint); the tool list is
  unchanged. job_stop and reading bash stay.
- Slots: the lead waits for one before its turn (Esc stops the wait);
  members wait in order; task helpers in a team count toward the size
  and hold a slot; job_send restarting a helper is refused when full.
- The offer is decided with the prompt and kept with it: a resumed
  session takes it from its kept tool list.
- The size: agents.min/max settings, refused outside 1 <= min <= max <=
  cap, kept across /new and resume; said in a note on the first message,
  after a change, after a compaction and a rewind.
- TUI: /team (tree and room, size, stop a member, dialogs for both), an
  "agents" row beside the effort in /effort, "team n/max" in the status
  bar. /team works over ACP too.

tests/team.test.ts runs a lead, a member and its report through the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:08:52 +00:00
HomerandClaude Opus 5.5 fbefe7f844 Harness spec 3.2.0 in the CLI: effort levels, reasoning round-trip, no absolute paths
ci / check (push) Canceled after 0s
Levels (models/schema.json levels): provider/effort.ts levelsOf/levelFields/
readLevel — `off` only with thinking_switch and sends enable_thinking false
and no effort, `default` for a model that takes no efforts and sends
nothing, a level not offered is read as the start level. The engine's
effort is a level; /effort shows nothing for one level, a Thinking switch
for [off, X], a list otherwise; the status bar follows. /v1/models'
thinking_switch, efforts [] and capacity.parallel are read
(lembas/webui.ts); session/capacity.ts counts parallel slots.

Reasoning (context.md §8): an assistant message of the current turn
carries reasoning_content (provider/common.ts turnReasoning,
openai-chat.ts); step-boundary deliveries, nudges and the wrap-up are
marked turn: false and do not start a turn.

Paths (context.md §11): the <env> block names the project and, started
below the root, that directory relative to it (assemble.ts envLines);
instruction files and @ attachments are named from the root or as ~/…;
file tools and bash resolve relative paths against the project root.

The team rules (team/team.ts) and conformance runners for levels,
reasoning, paths and team; the team runtime follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:36:55 +00:00
HomerandClaude Opus 5.5 5c23087cef Harness spec 3.2.0: version, README, changelog
ci / check (push) Canceled after 0s
VERSION 3.2.0; README's file table, the `team` requirement and a 3.2.0
section; CHANGELOG Unreleased. Two tests that pinned the AGENTS.md
block's absolute root now pin the relative text (context.md §11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:18:21 +00:00
HomerandClaude Opus 5.5 880289970b Harness spec 3.2.0: teams — subagents that work together
team.md: a lead adds members (team_add) that work in the background on
the parts they own; members may lead areas of their own. The chat
setting agents {min, max} (defaults 1/4, an instance cap of 32) bounds
the whole tree, task helpers included; a team is offered only where
subagents are enabled and the model serves two requests at once
(capacity.parallel). A manager's work calls — risk write or execute,
bar job_stop and reading bash — answer a fixed refusal while the tool
list stays unchanged. The room: team_send to names or all, delivered
under "[Team message from X to Y:]" at the next step or waking a
finished member; a member's final reply is its report to its manager;
team_read shows the tree and the visible part of the room; team_stop
stops a subtree. Past the model's capacity a member waits for a slot,
the lead first. Size notes in context.note; texts in loop.json team;
prompts blocks/team_lead.md and team_member.md; tools allowed by
default. Conformance area team, written from a reference model.

The CLI embeds the new tool and prompt files; its tools are pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:17:48 +00:00
HomerandClaude Opus 5.5 d09d51cfec Harness spec 3.2.0: reasoning goes back during its turn; no absolute paths
context.md §8: every assistant message of the current turn (after the
last message that started a turn — a step-boundary delivery does not)
carries its reasoning back, as reasoning_content in OpenAI chat and as
thinking blocks in Anthropic; earlier turns carry none, which the common
templates render identically. §11: an agent session's prompt names no
absolute machine path: the environment block names the project and says
paths are relative to its root (loop.json context.env), files outside
the project under home as ~/…; relative paths resolve against the
project root, absolute ones still accepted. agents-missing.md and
init.md no longer name the root. New conformance areas: reasoning, paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:08:53 +00:00
HomerandClaude Opus 5.5 fdfcf3666a Harness spec 3.2.0: effort levels, the thinking switch, parallel capacity
models/schema.json: thinking_switch (the server turns thinking off for
chat_template_kwargs.enable_thinking: false) and capacity.parallel
(single_session is parallel 1). The level `off` exists only with the
switch and sends enable_thinking false and no effort; a model that takes
no efforts has the one level `default`, which sends nothing. The levels a
chat offers are (off) + efforts; one level shows no control, [off, X] a
Thinking switch, more a slider. A start level and a level the model does
not offer follow one rule. quirks.json: thinking-default; acp.md: effort
values are levels. New conformance area: levels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:07:14 +00:00
HomerandClaude Opus 5.5 a97c5b46a4 2.0.0-beta.2
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 21:54:35 +00:00
HomerandClaude Opus 5.5 aa83bb9783 Harness spec 3.1.0: carried by both implementations
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:37:08 +00:00
HomerandClaude Opus 5.5 8e06590d57 Harness spec 3.1.0: the prefix stays still, in the CLI
ci / check (push) Canceled after 0s
The system prompt is made once per session (start, compaction, model
switch), kept in session_meta and resent byte for byte; it holds no
date. What changes mid-session -- the date, a mode the person chose, a
plan or memory or instruction file they edited, a personality, MCP
instructions that arrived later -- is a <session-note> on the next user
message, stored with it. The tool list is fixed for the session:
plan_submit is always offered and answers unavailable outside plan
mode, the wrap-up keeps the tools and runs no call, a withdrawn tool
stays listed and answers its refusal; the first request waits up to
mcp_wait_ms for MCP servers. Compaction asks for its summary as the
next turn of the same conversation. Cached input tokens are parsed
(incl. llama.cpp timings), stored per request and shown in /context.

Spec: context.md §7/§10, loop.json context.note (+ plan_ended,
plan_own, personal, empty, mcp_wait_ms), modes.json plan.refused,
compact.md without the transcript heading. Conformance area prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:22:02 +00:00
HomerandClaude Opus 5.5 ecae6247fd Harness spec 3.1.0-draft: the prefix stays still
ci / check (push) Canceled after 0s
Measured on 2026-11-05 against a local model's prompt cache: a harness
that rebuilds its system prompt for every request re-reads the whole
session whenever any part changes (a date at midnight: 16,912 tokens,
99 % -> 0 % cached, 139 s). context.md §10: the system prompt is made
once per session and resent; no clock in it; mid-session changes go as
a <session-note> on the next user message (loop.json context.note); the
tool list is fixed for the session, a requires that comes and goes
answers unavailable instead (plan_submit gains requires: plan); §7: the
compaction summary is the next turn of the same conversation, not a
separate request with a pasted transcript; cached tokens are recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:37:25 +00:00
202 changed files with 27528 additions and 1135 deletions

No files matched your search

+4
View File
@@ -2,3 +2,7 @@
# catch it. Not a credential. (gitleaks fingerprints: the commit that added it, and the file now.)
f9bad01ed7a06988bdd02bddaac14baad841d6d4:tests/memory.test.ts:stripe-access-token:95
tests/memory.test.ts:stripe-access-token:95
# A made-up key-shaped value that tests/mcp-clean.test.ts feeds the redaction of MCP errors,
# which must take it out. Not a credential.
db7e7f05ffe5c7d88ef96eaa3ee900f3796b5f89:tests/mcp-clean.test.ts:generic-api-key:31
tests/mcp-clean.test.ts:generic-api-key:31
+393
View File
@@ -6,6 +6,399 @@ All notable changes to LLeMbas CLI. The format follows
## [Unreleased]
## [2.0.0-beta.11] — 2026-11-13
Harness spec 3.8.1: the text that tells a model when to write a page and when to show a file.
### Changed
- **Harness spec 3.8.1: a page for what is to be seen, a shown file for what has to run.** The
text a model is given when HTML pages are on (`harness/prompts/blocks/html-pages.md`) now says
that something the person asks to see in the answer is written as a page, not as an HTML file
opened with `show`; and that a page is static, so anything that has to run — a calculator, a
game, something that reacts to a click — is not a page: the model says so and, where it can,
writes an HTML file and shows that. A text only; the CLI is never offered pages and behaves
as before.
## [2.0.0-beta.10] — 2026-11-13
Harness spec 3.8.0: reports from scheduled runs, HTML pages in answers, which permission rule decides.
### Added
- **Harness spec 3.8.0: reports** (`harness/reports.md`). A schedule's run files a report with the
new `report_write` tool — or leaves one line in the schedule's history. The schedule's *notify
when* decides: every run, only when your own condition holds (the default: "something needs my
attention"), or never. `[SILENT]` is retired. On a linked computer the CLI offers
`report_write` to a scheduled run's model and hands the report back with the run's answer.
- **Harness spec 3.8.0: HTML pages in answers** (`harness/pages.md`), experimental and off unless
the server switches it on: a reply may carry a complete page in an `html-view` block — static:
HTML, CSS and inline SVG, no script — shown in a sealed frame by the web UI and Desktop. A terminal shows a note in its place — *This answer
has a page: title* — and keeps the page as a file (`/pages`). A terminal's own model is never
offered pages.
- **`/reports`**: the reports your schedules filed, read from your LLeMbas server — unread first,
with the schedule and when. Enter opens one: read it here (Markdown, a page as its note; it is
marked read), reply (the report and your words go to this session's agent), mark it read, delete
it (asked once); in the list ctrl+r marks read and ctrl+d deletes. `/reports <id or title>`
reads one directly; `lembas run "/reports"` prints the list, or one report, as text.
- **`/schedule new` asks when to notify**: when something needs your attention (the default),
when a condition you type holds, every run, or never; `/schedule` shows it for each schedule.
- **Harness spec 3.8.0: which permission rule decides** (`harness/permission/rules.md`): the
rule order this program has used since the menus is now the shared specification, with
conformance cases both sides run.
- **A `/mcp` menu.** The servers with their state (connected, connecting, failed and why, needs
sign-in, switched off), where each comes from (the LLeMbas server's library, this project, your
config) and what it offers. Enter opens a server: reconnect, switch it off or on (kept for a
trusted project), sign in or out, read its last error in full; its tools, searchable as you
type, each with what the permission rules say of it — asks, always allowed, denied — which
Enter changes (for the session, and saved to a trusted project); its prompts. `/mcp <name>` opens one server directly. Keyboard
only; Esc goes back. Over the link and in `lembas run`, `/mcp` and `/mcp <name>` print a plain
table instead.
- **Menus have sections, state marks, a line about the highlighted row, Esc-goes-back, PgUp/PgDn
and Home/End, and say where the cursor is in a long list** — every picker is the one component.
- **`/help` is a menu**: every command under a heading (this session, the model, the project,
what it knows and can use, account and settings, look), found by typing a word of its name or
of what it does; Enter runs it, or puts it in the box when it needs words. The keys are in it
too.
- **`/permissions`** (new): the permission rules in force, by where each was made — this session,
the project, your config, built in. Enter changes one (asks / always allowed / denied), the
first row adds one (`bash git status* allow`), and a rule of this session can be removed (its
saved copy with it). A rule made in a menu changes what a broader rule decided and nothing
else: a narrower, stricter rule keeps winning (`read: allow` leaves `read *.env` asking), your
own config is never loosened, choosing what is already so changes nothing, and the menu says
which stricter rules still apply. This session and the next start judge a call the same way.
- **A project's rule, or an "always" answer, no longer overrides a narrower, stricter rule**
either: a project's `read: allow` leaves `.env` files asking, unless the project names
`"*.env"` itself.
- **`/status`** (new): the server and login, the model, the session, the project and whether it
is trusted, the MCP servers, and this terminal — how copying and pasting images work here —
on one screen. What needs attention is marked; Enter on a row opens what changes it.
- **`/agents` is a menu** of the subagents; Enter puts one's name in the box to hand it a task.
- **`lembas run "/mcp"`** (and `/status`, `/permissions`, `/agents`, `/team`) prints the command's
text instead of sending the words to the model; the same text answers these commands over the
link. Only the command alone is the command: `/status of the build?` is a question for the
model, and `/mcp <word>` is the command only when the word is a server's name. With `--json`
the text is an event of the stream; a command that could not do what was asked exits 1.
- **`/command <name> [words]`** runs a custom command by its name, and **`/skill <name>`** now
works over the link too. `permissions`, `status` and `command` are command names of the
program: a custom command of such a name is said once at start, with `/command <name>` as the
way to it; a skill is reached as `/skill <name>`.
- **What `/mcp` prints does not carry what your config resolved to**: an address is shown
without user, password or query, a local server by its program's name alone, an error by its
first line with what looks like a secret taken out — and never a local server's stderr. The
menu shows an error in full, on your own screen.
- **A server's own words cannot draw on your terminal or put markup into a reply**: control
characters and escape sequences are taken out of every name, description, error and stderr
line an MCP server supplies; where `/mcp`'s text becomes a markdown reply, descriptions are
escaped.
- **Two MCP tools whose names come out the same both get a distinguishing suffix**, so a server
that lists its tools in another order cannot move an "always allow" onto the other tool.
### Changed
- **An MCP server that connects no longer says so with a warning sign at every start.** Nothing is
printed when the servers connect; the status bar carries a quiet count (`MCP 2`, or `MCP 1/2`
when one that is switched on is not connected). A server that failed or needs a sign-in gets
one plain line that names it and points at `/mcp <name>`.
- **One look for the lines the program says**: `·` something happened, `✓` done, `⚠` needs
attention, `✗` failed — in the transcript and in `lembas run`. A warning sign now always means
something to look at: compaction starting and finishing, a job's note and the like are plain
lines.
### Removed
- **Prototypes** — the 1.x `prototype-chat` / `prototype-page` blocks a terminal could be offered
with `prototypes: true`. HTML pages take their place; the setting is dropped with a line saying
so, and `/prototype` is now `/pages`.
## [2.0.0-beta.9] — 2026-11-12
Harness spec 3.7.0: one display in every client.
### Added
- **Harness spec 3.7.0: one display everywhere** (`harness/display.md`). The spec now says how
every client — the web UI, Desktop, the CLI, Android — shows a tool call: one short title made
from the call's arguments (the same in the transcript, on the progress line and over the link),
the four states running, done, failed and denied, how long a finished call took, `+added
−removed` for an edit, and the kinds of block. A reply that was stopped or failed keeps the
spec's line (`Stopped: by you`, `Failed: …`) on it. The approval, question and plan cards offer
the same actions everywhere, and numbers are written in the client's locale format.
- **Harness spec 3.7.0: `python` says why it could not run.** The server's `python` tool had one
answer for three situations; the spec now has one each — no page of the chat is open (and where
to open it), the page did not answer, the run took too long.
- **Paste placeholders in the prompt box.** A paste of three lines or more, or of more than 150
characters, shows as `[Pasted text 40 lines]` (or `[Pasted text 300 chars]`), and an image as
`[Image 1]`, `[Image 2]`…; what is sent is the text itself and the image. One backspace removes
a placeholder and what it stands for — cutting into one removes all of it; pasting the same
text again right after its placeholder opens it. The transcript shows the placeholder; prompt history, `/undo` and copying from the box
give the text in full. `paste: full` in the config (or `/settings`) shows pastes whole, as
before.
- **Images from the clipboard on macOS and Windows, and JPEG, WebP and GIF** besides PNG: ctrl+v
reads the clipboard through OpenTUI's host clipboard, with `wl-paste` / `xclip` behind it. It
no longer holds the screen while a clipboard answers, and says so when there is no image.
Pasted images are kept under the state directory and removed after a week.
- **Images over SSH.** A terminal cannot hand over the clipboard image of the machine you sit at,
so: an image pasted as text — a `data:image/png;base64,…` URL, or the base64 itself — is
recognised, saved and shown as `[Image N]`; with `ssh -X` the forwarded X clipboard is read; in
kitty, with `kitty_clipboard: true`, the terminal itself is asked for its clipboard (its
clipboard protocol, OSC 5522 — it asks you once). That one is off by default: on a connection
that stalls, part of the image can be lost on the way, and it is then refused with a line —
never saved broken, never typed into the box. And when nothing came through, one line names what works: the data URL, `@path` after
copying the file over, or attaching it to the same chat in the web, Desktop or Android app.
### Changed
- **The terminal opened from the web UI or Desktop picks a shell that exists.** `$SHELL` when
it is there, else bash, zsh or sh; on Windows PowerShell 7, then Windows PowerShell, then
`cmd.exe` — started without `-l`, which none of them takes. (The runtime's pseudo-terminal is
documented for Linux and macOS only, and there is no Windows build of the CLI yet: where a
terminal cannot be opened, the refusal now says so in a sentence.)
- **Tool calls are shown as spec 3.7.0 says.** A call has one title from its start to its end —
the command, the pattern, the path — the same in the transcript, on the progress line, in
`lembas run` and over the link (a `bash` call used to be titled by its description in the
transcript and by its command elsewhere; a `grep` by its directory on the progress line). After
the title come what the result adds (`+12 −3`, `exit 2`, `14 hits`, the lines read) and how long
it took; a denied call shows its reason and no time; a call cut off by a stop no longer stays
"running".
- **A reply that was stopped or failed says so on the reply**, in the spec's words — `Stopped: by
you`, `Stopped: step limit`, `Stopped: budget`, `Failed: …` — once, in place of the separate
"cancelled" notice and the raw error line; a session opened again from the store says it again.
- **One clock on the working line**: the phase's own (`Running bash: bun test · 12s`); once the
turn has gone on longer than the phase it reads `12s of 1m 05s`, instead of a second
`turn 1m 05s`.
- **`Waiting for subagents: N running` counts the subagents that are running** (it always said 1).
- **Numbers in your locale's format** (`LC_ALL`, `LC_NUMERIC`, `LANG`): token counts, rates, hits.
Durations stay as they are; with no locale set, English grouping as before.
- **Completing an `@file` or moving through the prompt box now counts columns as the box does**:
with a wide character (CJK, an emoji) before the cursor, the `@` list could replace the wrong
part of the line.
- **An approval card over the link names its tool** (`_meta.lembas.tool`); its title stays the
whole command, or the tool's name.
- **A duration just under a minute** is `1m 00s`, not `60.0s`.
- **A refused tool call reaches a plain ACP client** (an editor): it was sent as an update of a
call the client had never been told about, which a client drops; it is now announced as a failed
call, with its title and the reason.
- **Dictating into a box that holds a paste placeholder** keeps the placeholder.
- **Plainer refusals when a terminal or a folder cannot be used**: each says what to do —
`lembas remote terminal on`, `lembas remote add <dir>`, close one of the open terminals.
## [2.0.0-beta.8] — 2026-11-10
### Added
- **Harness spec 3.6.0: phone actions.** The spec now describes `phone_action`, the LLeMbas
server's tool for doing something on the person's phone when they write from the LLeMbas app on
it — alarms and timers, calendar events, SMS and email drafts, the dialer, routes (start one,
add a stop, search nearby, stop), opening an app or an address, media, the torch, settings
panels and automations — confirmed on the phone every time (`harness/phone.md`). The server's
alone: the CLI does not offer it, and its conformance area is the server's.
## [2.0.0-beta.7] — 2026-11-10
Harness spec 3.5.0: scheduled work on a linked computer.
### Added
- **Accept scheduled work.** A new switch, off by default: `lembas service scheduled on` (or
`lembas remote scheduled on`; `remote.scheduled` in the global config). On, the schedules you
make on your LLeMbas server may run on this computer as agent turns, in the folders remote work
may use. `lembas remote list --json` says `scheduled`; the server is told at once (the link
dials again once nothing is working).
- **Scheduled turns.** A run is an agent session in the schedule's mode — Edit unless the schedule
says Auto, never Plan, and never beyond `remote.max_mode` — with the schedule's Subagents
Min/Max. Its answer reports the run: `ok`, `silent` (the reply said `[SILENT]` on its first or
last line), `failed` or `cancelled`, and the final reply. A switch turned off is a fixed refusal
the server shows as it is.
- **Approvals in a scheduled run** go to you through the server (a notification on your phone)
and wait the schedule's wait — 30 minutes unless it says otherwise — then count as denied, and
the model is told so. Questions and plans have nobody to answer in a scheduled run.
- **Watch commands** (monitor mode): the server asks this computer to run a schedule's watch
command in its folder, with a timeout, and gets back a hash of the output and a short excerpt;
the model runs only when the output changed. A command the schedule's mode would ask about is
refused rather than run.
- **`/schedule`**: your schedules on the LLeMbas server from the terminal — the list with each
one's next run and last result, `new <words>` (the server works out the rule; you see what it
understood and the next runs before anything is made, and may have it run on this computer in
the current folder), `pause`, `resume`, `run` (now, without using up the next scheduled run) and
`history`. It uses this computer's sign-in; a server too old to allow that says so.
- **A notice when a reply finishes** — or when the agent waits for your answer — while the
terminal is not focused: the bell, and a desktop notification (OSC 9, in terminals that show
one) naming the session, never what the reply says. `notify: false` (or `/settings`) turns it
off.
- **`/rename <title>`** names this session — in `/sessions`, and in the web UI when it is shared.
- **`/search <words>`** finds a past session in this project by what was said in it (add `all`
for every project) and resumes the one you pick.
- **`/memory` shows the server's memory** when the server keeps it (`library: lembas`): its
entries beside this machine's files, each one to change or forget, through the server.
### Changed
- `team_add` under a sub-manager says where the report goes: "Its report goes to <sub-manager>
when it finishes", not "comes to you".
## [2.0.0-beta.6] — 2026-11-10
Harness spec 3.4.0 (spec commits 4b8786b, b66891e): one progress vocabulary for every client, and
subagents organised as the main agent's tree.
### Added
- **Progress phases.** The line under the conversation says what the agent is doing in the words
every LLeMbas client uses — *Queued*, *Waiting for {model}*, *Reading the prompt: n / total
tokens (p%)*, *Thinking*, *Writing: n tok/s*, *Running {tool}: {what}*, *Waiting for you*,
*Waiting for subagents*, *Compacting the conversation*, *Retrying in n s*, *Stopped*, *Failed* —
with how long it has lasted, then the turn's time and tokens. The CLI keeps its own estimate of
how long the rest of a long prompt will take. Over the link each phase is a `phase` event and is
in the session's status (capability `progress`).
- **The main agent and its subagents.** Only the main agent adds, reassigns (`team_assign`),
replaces (`team_replace`), stops and decides; a subagent added with `lead: true` is a
sub-manager that directs the subagents placed under it (`parent`) and adds none. Each subagent
has an id (`s1`, `s2`, …), a name, a position, a parent, a task, a mode and a model, and can ask
`team_whoami`. With Min above 1 the main agent starts with Min − 1 open slots to fill.
- **Permissions only go down.** A subagent's mode is its parent's or stricter. A narrowed one may
be given request options (read, write, execute) and ask the main agent with `team_request`; the
main agent decides with `team_decide`, and never allows more than its own mode would. What
nobody in the tree could allow — a `bash` call in an all-Edit tree — is put to you, on an
approval card that names the subagent.
- **A subagent's end.** It reports and ends with `team_finish`. Its findings (`team_findings`) are
kept after it ends. When its context fills it does not compact: it is paused, gets one last
turn of at most 8 steps to save its findings and tell its parent, and ends; the main agent
replaces it or uses what it found.
- **Seeing the tree.** `/team` draws every agent with its position, state, model, mode, context
use, current phase and messages, the open slots and the subagents that ended; `/team open
<name>` shows a subagent's session read-only, live or after it ended; `/team findings <name>`;
`/context <name>` for a subagent's context.
- **An agent chat's subagents run on this device.** The chat's Min and Max come with every turn
(capability `agents`) and the tree, progress, findings and transcripts go back to the server
(capability `tree`: the `team` event with the tree, `_lembas/team`, `/transcript`, `/findings`,
`/stop`).
### Changed
- A subagent can no longer add subagents of its own or start a `task`; it asks the main agent.
`team_stop` is the main agent's alone.
## [2.0.0-beta.5] — 2026-11-09
Harness spec 3.3.0 (spec commit 02c7282): subagents run on your model unless you name another,
and `/context` shows where the window goes the way the side panel of the other apps does.
### Changed
- **Subagents run on the session's model**, unless you named another model in this session's own
messages — its id, the part after its provider, or its display name, as a whole word, in any
letter case. A `task` or `team_add` that asks for any other model is refused ("Use another
model for subagents only when the person names it."), and an agent file's own `model:` is no
longer used. Nothing in the settings chooses a subagent's model.
- **Only the logical capacity limits remain.** A named model on the same one-model server as the
session's model is refused ("That model is on the same one-model server as this chat's model;
name a model on another server."). On a model that serves one request at a time, a subagent on
that same model is refused ("This model serves one request at a time: name another model, on
another server, for subagents.") and nothing else is picked instead.
- **Subagents are offered** — the size setting, the team tools — when subagents are on and some
model could serve one: the session's, when it serves two requests at once, or any model of the
server that is not on its one-model server. When the session's model cannot serve its own
subagents, the agent is told so in its first note, and `/effort`, `/team size` and `/team` say it
beside the setting.
- **"Subagents" is the word** for the setting, with **Min** and **Max**: the row beside the effort
in `/effort`, `/team size`, `/settings`. "Helper" is gone. The status bar reads
`agents 3/4 · 2 subagents working` while there is a team.
- **The numbers count this agent**: `Subagents: Min 1, Max 4 — 1 is this agent alone`. Max 1 is
the agent alone, with no subagents; Max 4 is the agent and up to three subagents.
- **The setting is one range with two handles.** In `/effort` and `/team size` the Subagents row
shows `Min 1`, a track from 1 to the cap with a handle for each, and `Max 4`: ←→ move the handle in focus, tab switches to the other, enter
sets both for the session (Min never passes Max; Max goes up to `agents.cap`). `/team size` also
keeps the usual pairs and `<min> <max>` typed.
- **`/context`** shows the window as used tokens of the window and a percentage, one bar split by
category, every category with its tokens and its share of the window, what is free, and how far
it is to automatic compaction (`N until auto-compact`, with `/compact` to do it now).
## [2.0.0-beta.4] — 2026-11-09
### Fixed
- **`lembas login` no longer loops on a sign-in the server stopped accepting.** With an earlier login
for the same server kept here (from an older install, or LLeMbas Desktop), login only refreshed it;
when the server refused the old token it said “run login again”, and running it again did the same.
Now a refused sign-in starts a new one, which replaces the old.
- The installer's last line says to run `lembas login`, not to edit `connections.yaml` (gone in 2.0).
## [2.0.0-beta.3] — 2026-11-09
Harness spec 3.2.0: teams, effort levels that mean what they say, the model's reasoning sent
back while it works, and no absolute paths in the prompt.
### Added
- **Teams.** Where the model serves at least two requests at once, the agent can add **members**
(`team_add`): background agents that each own a part of the work, briefed on their own and told
the team's goal. Once it has a member the agent **leads**: tools that change things answer that
it should give the work to a member, while reading, reviewing and managing stay. Members and the
lead talk in the team's **room** (`team_send`, to a name or to `all`); a member's final reply
comes back as its report and wakes the lead if it was idle, and a message wakes a member that
had finished. A member made with `lead: true` leads an area with members of its own.
`team_read` shows the team and the room, `team_stop` stops a member and everything under it.
- **How many agents a team may have**: the `agents` setting (`min` 1 and `max` 4 by default, at
most `agents.cap`, 32), changed with `/team size <min> <max>`, from the **agents** row beside the
effort in `/effort`, or in `/settings`; the agent is told the size and every change in a note.
`max: 1` means one agent and no helpers; `min: 2` or more makes the agent lead from the start.
`subagents: false` switches teams off together with `task`.
- **`/team`** shows the team as a tree and the room, and stops a member (`/team stop <name>`); the
agent is told who you stopped. The status bar shows `team 3/4 · 2 working` while there is a team.
- When every slot of the model is busy, a member (or the agent itself) **waits for a free slot**
and starts when one frees, instead of being refused; one-off `task` helpers count toward the
team's size.
- **A Thinking switch.** A model that can switch thinking off offers `off` as a real level: no
thinking at all, not the model's default. `/effort` shows a list for several levels, an on/off
switch where that is the only choice, and nothing where there is nothing to choose.
### Changed
- **The model's reasoning goes back to it during its turn**, so it carries on from what it thought
instead of working it out again at every step; earlier turns are sent without it, as before.
- **No absolute paths in the prompt.** The agent is told the project's name and, when you started
below its root, that directory relative to it. Relative paths in every file tool and the
directory `bash` starts in are taken from the project root; absolute paths still work.
Instruction files are named from the project root or as `~/…`.
## [2.0.0-beta.2] — 2026-11-07
Harness spec 3.1.0: what the model has already read stays exactly as it was, so its server
can reuse it instead of reading the whole session again.
### Changed
- **The system prompt is made once per session** — at the start, after a compaction, on a model
switch — kept with the session and sent byte for byte on every request; a resumed session sends
the one it kept. It holds no date any more.
- **What changes during a session is said in a note** after your words on your next message: the
date (on the first message, and when it changes), a permission mode you chose, a plan you
changed, memory or an instruction file you edited, a personality you picked, an MCP server's
instructions that arrived later. The model's own changes (its plan, its edits, a plan approval)
are not said again. Notes are not shown as your words.
- **The tool list is the same for the whole session.** `plan_submit` is offered in every mode and
answers that it works only in plan mode; `show` is offered from the start where the session can
have a viewer; knowledge search is decided as the session starts. The tools stay listed when a
step limit or budget winds a prompt up (a call in that answer is not run), and a tool refused
for good stays listed and answers that refusal. The first request waits up to 3 seconds for the
configured MCP servers, so their tools are in the first list.
- **Compaction asks for its summary as the next turn of the same conversation** instead of a
separate request with a pasted transcript, so it reuses what the server has read and no longer
loses the middle of a long session. A tool call in the summary's reply is not run.
### Added
- **Cached input tokens are recorded for every request** (the usage's own count, or llama.cpp's
`timings` and progress), kept with the session, and shown by `/context` for the last request.
## [2.0.0-beta.1] — 2026-11-03
LLeMbas CLI 2.0 works with LLeMbas 2.0 and nothing else: it uses the server it is logged in to,
+260 -11
View File
@@ -15,16 +15,24 @@ page *Harness-parity* in LLeMbas CLI's wiki.
|---|---|
| `VERSION` | The spec's own version, apart from LLeMbas CLI's |
| `purpose.json` | The `purpose` argument added to a tool whose calls say what they are for |
| `tools/<name>.json` | One tool each: name, `scope`, `sessions`, `risk`, `exclusive`, `block` (how a call is shown: `shell`, `edit`, `read`, `search`, `web`, `task`, `plan` — not drawn, the plan card refreshes — `hidden`, `tool`), `purpose`, former names (`aliases`, per project), renamed arguments, `variables`, what a project offers of the parameters (`narrow`, per project), `offered` (`subagent`: given to subagents only, never to the main agent — `report`), `requires` and `unavailable` (when it can be offered, and what a call answers when that has gone), `confirm` (`always`: the person is asked in every mode), the description and the JSON Schema of its parameters — exactly what a model is sent |
| `tools/<name>.json` | One tool each: name, `scope`, `sessions`, `risk`, `exclusive`, `block` (how a call is shown: `shell`, `edit`, `read`, `search`, `web`, `task`, `plan` — not drawn, the plan card refreshes — `hidden`, `tool`), `purpose`, former names (`aliases`, per project), renamed arguments, `variables`, what a project offers of the parameters (`narrow`, per project), `offered` (`subagent`: given to subagents only, never to the main agent — `report`, `team_finish`, `team_request`; `main`, spec 3.4.0: given to the main agent only, never to a subagent — `team_add`, `team_assign`, `team_replace`, `team_stop`, `team_decide`), `requires` and `unavailable` (when it can be offered, and what a call answers when that has gone), `texts` (3.7.0: a tool's other fixed answers by key — `python`'s `no_answer` and `timeout`), `confirm` (`always`: the person is asked in every mode), the description and the JSON Schema of its parameters — exactly what a model is sent |
| `prompts/` | The prompt texts; `prompts/index.json` says which are shared, which LLeMbas fragment each one is, and what each `{{variable}}` in a text means. `prompts/personality/` holds the personality presets both offer |
| `permission/hardline.json` | The floor: commands refused in every mode, protected paths, and how a command is spelled plainly before it is checked again |
| `permission/arity.json` | How much of a command an "always allow" covers |
| `permission/defaults.json` | The rules every session starts from |
| `permission/modes.json` | The four modes — manual, edit, auto, plan — as what each does with each risk class |
| `models/schema.json` | Model metadata: context, output limit, efforts, vision, tools, notes, capacity |
| `loop.json` | How one prompt runs: the step backstop, budgets, wrap-up, nudges, parallel calls, capacity; `jobs` — background work, its marks and limits; `context` — result ids, stubs, the output cap, the compaction table |
| `models/schema.json` | Model metadata: context, output limit, efforts and the thinking switch, vision, tools, notes, capacity (`parallel`); `levels` — the effort levels a chat offers and what each sends |
| `loop.json` | How one prompt runs: the step backstop, budgets, wrap-up, nudges, parallel calls, capacity; `jobs` — background work, its marks and limits; `subagents` — the model refusals, what names a model, the setting's label; `team` — a team's size, names, marks, refusals and texts; `progress` — the phases' texts; `context` — result ids, stubs, the output cap, the compaction table, the environment lines, the session notes; `scheduled` (3.5.0) — scheduled work on a linked computer: the setting, the modes, the approval wait, the sentinel, the watch command's limits and the refusals; `phone` (3.6.0) — phone actions: the capability, each action's fields, what is required and checked, the wait and the texts; `display` (3.7.0) — a call's title keys, states and facts, the blocks, the cards' actions; `scheduled.notify` (3.8.0) — notify-when and its texts; `pages` (3.8.0) — the fence word, the frame's variables, the note and the projection |
| `filesystem.md` | The file system a session works in: paths, node kinds, the four access levels, errors, listings, search and indexing by tokens, stacked instruction files, skills, memory |
| `context.md` | Context hygiene: what happens to a tool result when it is inserted, and never afterwards |
| `context.md` | Context hygiene: what happens to a tool result when it is inserted, and never afterwards; the prefix that stays still; reasoning sent back during its turn; no absolute paths in the prompt |
| `team.md` | Teams: a lead and the members it adds, the size setting, the room, who receives what, reports, a manager's refusals, capacity, stopping |
| `subagents.md` | Subagents: the word, which model one runs on (the session's, or one the person named), the capacity refusals, and when the Subagents setting is offered; from 3.4.0 (§5–§13) the main agent and its tree — only it adds, permissions inherited and never widened, request options, a subagent's life and its findings, what clients show |
| `phone.md` | Phone actions (3.6.0): `phone_action`, carried out by the LLeMbas app on the person's phone and confirmed there — who offers it, how a call is checked, the answer, navigation |
| `progress.md` | Progress (3.4.0): the thirteen phases every client shows the same way, the data each carries, their texts, and where they are sent |
| `reports.md` | Reports (3.8.0): a schedule's run files a report with `report_write`, or leaves a history line; notify-when (`always`, `when`, `never`) and the instruction for each; what a run leaves; the retired `[SILENT]`; a run on a linked computer |
| `pages.md` | HTML pages in answers (3.8.0, experimental): the `html-view` fence, what the model is told, the note and the text projection for a reader that cannot show a page, when pages are offered, the session note, the frame |
| `permission/rules.md` | Which permission rule decides (3.8.0): the layers, the candidate, the floors a later-made rule gives way to, and what making a rule does |
| `display.md` | Display (3.7.0): one display in every client — a tool call's title, its four states, the duration and the facts beside it, the kinds of block; how `stopped` and `failed` stay on a finished reply; what the approval, question and plan cards offer; numbers in the client's locale |
| `quirks.json` | What real servers do, and how both harnesses cope |
| `conformance/<area>.json` | Cases with their expected results, run by both test suites |
| `acp.md` | The link between them: ACP plus every `_lembas/*` method, field and capability |
@@ -32,7 +40,7 @@ page *Harness-parity* in LLeMbas CLI's wiki.
## Vocabulary
- **Risk classes:** `read`, `write`, `execute`, `interact`. **Reading and writing are never one
tool** among the shared ones, so a read-only helper is given exactly the readers.
tool** among the shared ones, so a read-only subagent is given exactly the readers.
- **Modes:** `manual`, `edit`, `auto`, `plan` (`unrestricted` is read as `auto`).
- **Scopes:** `shared` — both projects implement it; `cli` or `llembas` — only that one. The same
two names key what is per project elsewhere: a tool's `aliases`, `loop.json`'s budgets, a
@@ -46,9 +54,15 @@ page *Harness-parity* in LLeMbas CLI's wiki.
- **Requires** (spec 3.0.0): what must hold for a tool to be offered at all — `page`: a browser
page of the chat is open and attached (not a schedule, not a background job); `display`: the
session is shown somewhere a file can be opened (the web UI, Desktop; not a bare terminal);
`forge`: the session's view holds a repository mounted from a forge. A requirement that goes away
between the offer and the call makes the call answer the tool's `unavailable` text, word for
word, as its result.
`forge`: the session's view holds a repository mounted from a forge; `plan`: the session is in
plan mode; `team` (3.2.0): the session's team setting allows more than one agent, and a model could
serve as a subagent (3.3.0: `subagents.md` §4; before, the chat's model serving two requests at
once); `phone` (3.6.0): a message in the chat came from an app on the person's phone that
carries out phone actions (`phone.md` §1). `scheduled` (3.8.0): the session was opened by a schedule for its
run, and the turn is that run (`reports.md` §2). A requirement that goes away between the offer and the call makes the call answer the
tool's `unavailable` text, word for word, as its result. **From 3.1.0 a requirement that can come
and go during a session does not take the tool out of the list** (`context.md` §10, rule 4): the
tool is offered from the start and answers `unavailable` while the requirement is not met.
- **Confirm** (spec 3.0.0): `always` — the call is put to the person before it runs, in every mode,
auto included, and runs on a yes only; nothing remembers the answer (`permission/modes.json`).
- A tool's other names, per project, are listed in its `aliases` and work as the tool. A former
@@ -57,11 +71,246 @@ page *Harness-parity* in LLeMbas CLI's wiki.
`in_progress` → `doing`, `completed` → `done`, `cancelled` → `dropped`; `conformance/plan.json`).
- **The plan** (`plan_write`, `plan_update`, `plan_submit`) is one structure both keep per session —
title, summary, findings, objectives, phases of tasks with a status each, ids given by the
implementation and never by the model — shown as a card in every UI and put into the prompt
(`{{plan_context}}`) on every step while it exists. `plan_write` and `plan_update` are offered in
every mode; `plan_submit` only in plan mode, where it is the approval. Their permission key is
implementation and never by the model — shown as a card in every UI. From 3.1.0 it is in the
system prompt (`{{plan_context}}`) only as it was when the prompt was made; the model sees it change
in its own `plan_write` / `plan_update` results, and a change by the person comes as a note
(`context.md` §10). All three are offered in every mode; `plan_submit` (`requires: plan`) is the
approval in plan mode and answers its `unavailable` text outside it. Their permission key is
`plan` (`permission/defaults.json`), which a rule written for the former `todo` key still reaches.
## 3.8.1
A text. `prompts/blocks/html-pages.md` (`pages.md` §2) now says which of the two ways of
showing HTML is for what: **something the person asks to see in the answer is a page** — not
an HTML file written and opened with `show`, which is what a model did when nothing said
otherwise, leaving a card to open where the drawing was asked for — and **something that has to
run is not a page**: a page is static, so for a calculator, a game or anything that reacts to a
click the model says a page cannot do it and, where it has `write` and `show`, writes an HTML
file and shows that. Nothing else changes: no tool, rule, field or conformance case; the CLI is
never offered pages, so its behaviour is the same.
## 3.8.0
Written ahead of the implementations; the CLI carries it in the same round.
- **Reports** (`reports.md`, `tools/report_write.json`, `loop.json` `scheduled.notify`). A
schedule's run no longer answers into a conversation: the model files a report with
**`report_write`** (title, body, summary, importance) or the run leaves one line in the
schedule's history. New requirement **`scheduled`**: the tool is offered only in a session a
schedule opened for its run, and is unavailable in a turn of it that is not the run. **Notify
when** is `always` (a report every run), `when` (only if the person's condition holds; the
default) or `never` (the tool is not offered); the instruction for each is a spec text the
server puts into the run's prompt. A run files at most one report — a second call replaces the
first; under `always` an answer without a report is filed as one. **`[SILENT]` is retired**:
told to no model, and a reply that still carries it leaves no report. A run on a linked
computer carries its report **in the turn's answer** (`acp.md`, capability `reports`,
`scheduled.notify` in the request, `scheduled.report` in the answer) — no new method.
Conformance area **`reports`**.
- **HTML pages in answers** (`pages.md`, `prompts/blocks/html-pages.md`, `loop.json` `pages`,
`models/schema.json` `html_pages`) — experimental, off unless switched on. The reply stays
Markdown; the model may add a complete, self-contained page in a fence whose info string is
`html-view` and a title. **A page is static everywhere** — HTML, CSS and inline SVG; no script,
no event handlers, no `<link>`/`<meta>`/`<base>`, frames, media or forms, no address but
`#fragment` and an inline `data:image/…`; a client rebuilds it from the allow-list
(`loop.json` `pages.static`) and shows it in a frame with scripts off, or shows the note.
Offered only when the instance's switch, the model's flag and the
chat's switch are all on (a scheduled run: instance and model); never to a subagent, the phone
assistant or an agent chat. A reader that cannot show a page sees *This answer has a page:
title*; anything that reads a reply as text sees `[page: title]`. A switch changed mid-chat is
a session note (`context.note.pages_on`, `pages_off`). **`blocks/prototypes.md`, the context
field `prototypes` and the capability of that name are gone** (the CLI alone had kept them);
the conformance area `prototype` is replaced by **`pages`**.
- **Which permission rule decides** (`permission/rules.md`): the last matching rule is the
candidate, and a candidate made after the written ones — a project's, an "always" answer, one
set in a menu — gives way to a narrower stricter written rule, to the person's own config, and
(an "always" answer) to a written deny. So `read: allow` leaves `read *.env: ask` asking,
whether a menu wrote it or a person typed it. Making a rule: the action already in force is a
no-op; a rule the person's own config or a written deny takes in whole is refused; the stricter
rules that still apply are named. Conformance area **`rules`**. `permission/defaults.json`
allows `report_write`.
## 3.7.0
Written ahead of the implementations; the CLI carries it in the same round (`display.md`,
`loop.json` `display`).
- **One display in every client** (`display.md`). **A tool call has one short title**, made from
its arguments alone — `questions` and `patch` by what they name, else the first non-blank string
among `summary`, `command`, `code`, `pattern`, `query`, `url`, `path`, `file_path`, `from`,
`description`, `name`, `id`, `title`, `key`, `target`, `to`, `action`; first line, 80 characters
— and it is the same string in the transcript, as `running_tool`'s `what` and as the link's
`tool_call` title. **This fixes the order `what` is taken in**: before, both implementations
looked at `path` before `pattern` and `query`, so a `grep` was titled by its directory.
- **Four states** — `running`, `done`, `failed`, `denied` — told apart in every client; a finished
call shows **how long it took** (`0.4s`, `1m 05s`, `2h 03m`), a denied one never; an edit shows
**`+added −removed`**, counted from the diff **by its hunks** (a header without `a/` `b/` is
still a header; a removed line beginning `-- ` is still a line); a command its non-zero
`exit N`; a search its hits.
- **The blocks** every client distinguishes: `shell`, `edit`, `read`, `search`, `web`, `task`,
`tool`; `plan` and `hidden` are not drawn.
- **`stopped` and `failed` stay on the finished reply**: the progress text alone (`Stopped: by
you`, `Stopped: budget`, `Failed: …`) at the end of that reply, in every client, and again
wherever the reply is shown from what was stored. Nothing else says it twice.
- **The cards**: an approval offers Allow once / Always allow (where the request offers it) /
Deny / Deny, and say why; a question its options and always "Something else"; a plan Approve
with the mode to continue in, and Revise (`loop.json` `display.actions`).
- **Numbers in the client's locale format**; durations, ids, exit codes and line numbers never.
Conformance texts are in the plain format.
- **`python` says why it could not run** (`tools/python.json`): one text used to answer three
situations. `unavailable` is now only *no page of this chat is open* and says where to open
it; `texts.no_answer` — a page is open but did not answer; `texts.timeout` — the run passed
its `{{seconds}}`. Conformance area **`python`** (the server's).
- **The approval card keeps its own title** (`acp.md` `session/request_permission`): the whole
command, or the tool's name — not the short title — and `_meta.lembas.tool` names the tool.
- Conformance area **`display`** (titles, durations, hunk counts, facts, the end line, drawn
blocks); `progress` gains the `budget` stop.
## 3.6.0
- **Phone actions** (`phone.md`, `tools/phone_action.json`, `loop.json` `phone`): a chat's model
may do something on the person's phone when they write from the LLeMbas app on it — an alarm or a
timer, a calendar event, an SMS or email draft, the dialer, a route (`navigate`, `add_stop`,
`search_nearby`, `stop_navigation`), an app or an address, media, the torch, a settings panel,
an automation. The app declares the capability `phone_actions` with each message; the person
confirms every call on the phone (`confirm: always`); the result is `done`, `declined` or
`failed` with what the phone said. The server's alone (`scope: llembas`, `sessions: chat`); new
requirement `phone`, offered once a message came from the phone and kept, answering
`unavailable` when the message being answered did not. Conformance area **`phone`** (the checks
and the result texts).
## 3.5.0
Written ahead of both implementations; the server vendors it as written, both carry it in the same
round (`acp.md` *Scheduled work on a linked computer*, `loop.json` `scheduled`).
- **Scheduled turns on a linked computer.** A schedule may run each time as an agent turn on a
linked device, in a folder of it. The device must allow it: **Accept scheduled work**
(`remote.scheduled`, off by default; `lembas service scheduled on|off`), said to the server as
`limits.scheduled` and judged again at every request — off, every scheduled request is refused
with one fixed text. The server opens an agent session marked `scheduled` (schedule, run, mode,
approval wait) with the schedule's Min/Max as an agent chat's, and prompts it with the run's own
text. **The mode** is the schedule's — Manual, Edit or Auto, **Edit when none was chosen**, so never
wider than Edit unless the person picked Auto; Plan refused — lowered to `remote.max_mode`. The
answer reports the run: `status` `ok`, `silent` (the `[SILENT]` sentinel on the first or last
line, the server's rule), `failed` or `cancelled`, and the final reply's `text`. A device that is
away is waited for like a busy model, then the run is missed; a refusal fails the run.
- **Approvals in a scheduled turn** go to the person through the server (a phone notification with
the card), carry `scheduled` on `session/request_permission`, and wait the schedule's wait
(default 30 minutes) instead of `remote.approval_timeout`; then they count as denied and the turn
goes on. `ask_user` and `plan_submit` have nobody to answer; `show` is not offered.
- **Monitor mode, the device's half**: `_lembas/monitor` runs a schedule's watch command in its
folder, with a timeout, under the mode's permission rules — **a command the mode would ask about
is refused** — and answers the output's hash (`sha256:` over the bytes and then the exit status) and a
short excerpt; the server runs the model only when the hash changed, and records `unchanged`
otherwise.
- **Schedules over `/api/v2` with the device's token** (scope `link`): the CLI's `/schedule` lists,
creates from words (compile), pauses, resumes, runs now and reads history. A run may be
`unchanged`, may wait for the `device`; a schedule may say `runs_on` and `watch`.
- **`team_add` under a sub-manager** says where the report goes: `team.texts.added_under` and
`added_waiting_under` ("Its report goes to <parent> when it finishes").
- Capability `scheduled`. Conformance areas **`scheduled`** (the mode, the wait, the refusals),
**`silent`** (the sentinel and the stripped text) and **`monitor`** (the hash, and what a watch
command may run); `team` cases changed for `added_under`.
## 3.4.0
Written ahead of both implementations; the server vendors it as written, both carry it in the same
round (`progress.md`, `subagents.md` §5–§13).
- **Progress** (`progress.md`, `loop.json` `progress`): one fixed set of phases — `queued`,
`waiting_for_model`, `loading_model`, `reading_prompt`, `thinking`, `writing`, `running_tool`,
`waiting_for_person`, `waiting_for_subagents`, `compacting`, `retrying`, `stopped`, `failed` —
each a structured object `{ phase, since, …data }` with fixed fields, an English text that is
the shared i18n key, and one line every client draws: `text · elapsed`. Sent beside the old
`status` text in `/api/v2` and over the link (`acp.md` capability `progress`: the `phase` event,
`progress` in `status`); `status` stays. Area `progress`.
- **Subagents v2** (`subagents.md` §5–§13; supersedes `team.md` where they differ, which says so):
the **main agent** is the session's, permanent, and **alone adds, assigns, replaces, stops and
decides** (`offered: main`); a member with `lead: true` is a **sub-manager** that directs those
placed under it (`team_add`'s `parent`). Every subagent has an id (`s1`…), a name, a position, a
parent, a task, a mode and a model. Min above 1 opens `min − 1` **slots** from the start of the
reply. **Permissions are inherited and never widened**: a subagent's mode is its parent's or
stricter; a narrowed one may get **request options** (`read`, `write`, `execute`) and ask the
main agent (`team_request` → `team_decide`, a grant that never reaches past the main agent's own
mode); a call nobody in the tree can allow goes **to the person**. A subagent ends with
`team_finish`, is stopped, or **runs out of context**: paused, one final turn to save its
findings and tell its parent, then `out_of_context` and a report; findings and transcripts are
kept, readable by the parent, the main agent and the person. New tools `team_whoami`,
`team_finish`, `team_findings`, `team_request`, `team_decide`, `team_assign`, `team_replace`;
`team_add` gains `parent`, `mode`, `request`; `team_send` takes `parent`; `team_stop` is the main
agent's. `blocks/team_submanager.md`; `team_lead.md` and `team_member.md` reworded. Over the link,
capability `tree`: the `team` event, `_lembas/team`, `/transcript` (read-only), `/findings`,
`/stop`, `subagent` on an approval. **An agent chat's subagents are the device's** (`subagents.md`
§14, `acp.md` *Subagents in an agent chat*): capability `agents` carries the chat's `{ min, max }`
down on every turn (and `said`, the person's earlier words, on `session/new`); the tree, progress,
approvals, findings and transcripts come up. Areas `team` (cases changed where a member used to add or
stop, and new ones) and `delegation`.
## 3.3.0
Written ahead of both implementations as LLeMbas CLI 02c7282; both carry it in the same round (`subagents.md`).
- **Subagent** is the word everywhere a person or a model reads one — a `task` subagent and a
team's member alike; *helper* is retired. Tool names and aliases are unchanged. The `team`
conformance area's step `helper_done` is now **`task_done`**.
- **The model**: a subagent runs on the session's model, unless the person named another one in
this session's own messages (its served id, its id at its connection or its display name, a whole
word, without case — never the model's text or a tool's output). `task`'s and `team_add`'s
`model` is refused otherwise: "Use another model for subagents only when the person names it."
No setting chooses a subagent's model; an agent definition's own `model` is not used for one.
- **Capacity, the logical restrictions only**: another model on the session's model's one-model
server is refused ("That model is on the same one-model server as this chat's model; name a
model on another server."); the session's model as its own subagent needs `parallel ≥ 2` or no
limit, else "This model serves one request at a time: name another model, on another server,
for subagents." — and nothing else is picked. A member is refused for these too, and still only
waits for a full model.
- **The offer**: the `agents {min, max}` setting is shown as **Subagents** (**Min**, **Max**;
`loop.json` `subagents.setting`) — one range from 1 to the cap with two handles, and a hint that
the numbers count the session's own agent: 1 is the agent alone, Max 4 the agent and up to three
subagents — and with it the team tools, when subagents are enabled and at
least one model could serve: the session's, with the capacity, or any usable model off its
one-model server. `context.note.team_own` tells the model, and `subagents.setting.own` the
person, when the session's model cannot serve subagents itself.
- `task`'s and `team_add`'s `model` descriptions, `task`'s description (a line on the model),
`models/schema.json` capacity texts, `team.md` §2, §4, §8. Conformance area **`subagents`**.
## 3.2.0
Written ahead of both implementations; both carry it in the same round.
- **Effort levels and the thinking switch** (`models/schema.json`). `thinking_switch`: the model's
server turns thinking off for `chat_template_kwargs.enable_thinking: false`. The level `off`
exists only then, and sends that and no effort — before, `off` sent nothing, which left the model
at its server's default effort. A model that takes no efforts has the one level `default`, which
sends nothing. The levels a chat offers are `off` (with the switch) and the efforts; one level
shows no control, `[off, X]` a Thinking on/off switch, more a slider. `capacity.parallel`: how
many requests the model serves at once (`single_session` is `parallel: 1`). Conformance area
`levels`; `quirks.json` `thinking-default`; in `acp.md` an `effort` is one of these levels.
- **Reasoning goes back during its turn** (`context.md` §8): every assistant message after the last
message that started a turn carries its reasoning (`reasoning_content`; Anthropic thinking
blocks); earlier turns carry none. Area `reasoning`.
- **No absolute paths in the prompt** (`context.md` §11): an agent session's environment block names
the project and says paths are relative to its root (`loop.json` `context.env`); relative paths
resolve against the project root, absolute ones are still taken. Area `paths`.
- **Teams** (`team.md`): `team_add`, `team_send`, `team_read`, `team_stop` (shared, both,
`requires: team`); the chat setting `agents {min, max}`; the room and its marks; reports to the
manager; the size across the tree, `task` helpers included; a manager's work tools refused with a
fixed text while the tool list stays the same; members waiting for a slot past the model's
capacity; `blocks/team_lead.md` and `blocks/team_member.md`; size notes in `context.note`. Area
`team`.
## 3.1.0
Written ahead of both implementations as `3.1.0-draft`, and `3.1.0` once both carried it (LLeMbas CLI 8e06590, LLeMbas 48e905f). **The prefix stays still** (`context.md` §10). Found on 2026-11-05 by measuring a local model's
prompt cache: a harness that rebuilds its system prompt for every request re-reads the whole session
whenever any part of it changes — the date at midnight, a permission mode, a memory, the plan. So:
the system prompt is made once per session and resent byte for byte; no clock is in it; what
changes during a session comes as a `<session-note>` on the next user message (`loop.json`
`context.note`); the tool list is fixed for the session (`requires` that can come and go no longer
remove a tool — `plan_submit` gains `requires: plan` and an `unavailable` text); compaction asks
for its summary as the next turn of the same conversation instead of a separate request with a
pasted transcript (§7); every request records its cached input tokens.
## 3.0.0
Written ahead of both implementations as `3.0.0-draft`, and `3.0.0` once both carried it (LLeMbas
+1 -1
View File
@@ -1 +1 @@
3.0.0
3.8.1
+302 -14
View File
@@ -60,11 +60,15 @@ change to the protocol is a change here first, then in both projects.
| `shell` | `shell` and `integration` in `_lembas/terminal/open`'s answer (listed only with `terminal`) |
| `context` | `system_prompt` and `personalization` in `session/new` and `session/prompt` `_meta.lembas` are read |
| `library` | `library` in `session/new` and `session/prompt` `_meta.lembas` is read; `_meta.lembas.scope` sent on the instance library's `tools/call`. Spec 3.0.0: an instance's chats have no knowledge bases, so a 3.0.0 instance sends no `library`; the scope is still sent on its `memory` calls (*The HTTP API*) |
| `prototypes` | `prototypes` in `session/new` and `session/prompt` `_meta.lembas` is read. Spec 3.0.0: a 3.0.0 instance sends none (`show` replaces prototypes) |
| `plan_state` | the structured plan: `_meta.lembas.plan` on the `plan` session update and on `_lembas/plan`; `plan` in `_lembas/session/status` |
| `rewind` | `_lembas/session/rewind` |
| `show` | spec 3.0.0: `_lembas/show`; the `show` tool is offered in a session the client opened when the client said `show: true` in `clientCapabilities._meta.lembas` |
| `jobs` | background work (spec 2.0.0): the `job` and `job_note` events; `_lembas/jobs`, `_lembas/job/output`, `_lembas/job/stop`, `_lembas/job/send`, `_lembas/job/transcript`; `jobs` in `_lembas/session/status`; `job` on `session/request_permission`; `machine` on a `prompt` event |
| `progress` | spec 3.4.0 (`progress.md`): the `phase` event; `progress` in `_lembas/session/status` |
| `agents` | spec 3.4.0: the session's Subagents setting `{ min, max }` is read from `_meta.lembas.agents` on `session/new`, `session/prompt` and `_lembas/configure` (*Subagents in an agent chat*, below) |
| `tree` | spec 3.4.0 (`subagents.md` §5–§13): the `team` event; `_lembas/team`, `_lembas/team/transcript`, `_lembas/team/findings`, `_lembas/team/stop`; `subagent` on `session/request_permission` |
| `scheduled` | spec 3.5.0 (*Scheduled work on a linked computer*, below): `scheduled` in `_meta.lembas` of `session/new` and `session/prompt` read, and the run's outcome in the prompt's answer; `scheduled` on `session/request_permission`; `_lembas/monitor`; `limits.scheduled` in `_lembas/hello` and `initialize`. Listed by every build that has it, whatever the setting says: whether this device *accepts* scheduled work is `limits.scheduled` |
| `reports` | spec 3.8.0 (`reports.md` §6): `scheduled.notify` in `_meta.lembas` of `session/new` and `session/prompt` read; `report_write` offered to the model of a schedule's run that notifies; the report the run wrote carried in the prompt's answer (`scheduled.report`); the status `silent` no longer given to a turn whose request said `notify` |
## Standard ACP, as used here
@@ -87,14 +91,15 @@ Result:
"_meta": { "lembas": {
"protocol": 3,
"harness_spec": "3.0.0",
"limits": { "roots": ["~/work"], "max_mode": "edit" },
"limits": { "roots": ["~/work"], "max_mode": "edit", "scheduled": false },
"connection": "example",
"capabilities": ["directories", "configure", "…"]
} }
}
```
`limits` is `null` on `serve --stdio`. `connection` is the device's name for the instance — the
`limits` is `null` on `serve --stdio`. `limits.scheduled` (spec 3.5.0, capability `scheduled`): whether
this device accepts scheduled work now (`remote.scheduled`, *Scheduled work on a linked computer*). `connection` is the device's name for the instance — the
login's connection — or `null`; the `model` event and `announce` say directly whether a model is
the instance's (`instance`).
@@ -112,7 +117,7 @@ Params: `{ cwd: <absolute>, mcpServers?: [], _meta?: { mode?, lembas_model?, mod
`cwd` must be a directory inside `remote.roots`, in a trusted project when `remote.require_trust`
(the default) — otherwise `-32602` with the reason. `mode` is lowered to `remote.max_mode`.
`lembas_model` is the instance's name of a model; `model` a ref the device knows (an editor's
choice); `effort` a level or `"off"`.
choice); `effort` one of the model's levels (`models/schema.json` `levels`, spec 3.2.0: `"off"` where the model has `thinking_switch`, `"default"` where it takes no efforts, else an effort); a level the model does not offer is read as its start level, and the result says the level used.
Result: `{ sessionId: "ses_…", modes: { currentModeId, availableModes }, _meta: { lembas: { model, mode, effort, instance } } }`.
`instance` (spec 3.0.0) is a boolean, with the `model` event's meaning: true exactly when the
@@ -141,7 +146,6 @@ texts, as for its own sessions, and these are the pieces the instance holds):
| `system_prompt: string` | `context` | the chat's effective authored prompt (chat over folder over model over instance), appended after the shared text as `## Instructions from <instance>`; empty: none |
| `personalization: { personality, personality_custom, instructions } \| null` | `context` | the account's, as `/v1/me/personalization` gives them, used in place of the device's own for this session; `null`: the device's own |
| `library: { bases: [{ id, name }] }` | `library` | the knowledge bases this chat may search, named to the model (`blocks/library.md`'s `{{knowledge_scope}}`) and sent back as the scope on every library call (below); an empty list: the account's whole library, as before |
| `prototypes: { offered: boolean, sources: string }` | `prototypes` | whether the model may write a prototype (`blocks/prototypes.md`), and the sentence saying what a page may load (a device offering them on its own, with no instance, sends nothing and the bullet drops) |
### `session/prompt` — client → agent
@@ -214,7 +218,18 @@ Params: `{ sessionId }`. Stops the running turn.
`{ sessionId, update }` with `sessionUpdate` one of `agent_message_chunk`, `agent_thought_chunk`,
`tool_call`, `tool_call_update`, `plan` (below), `current_mode_update`, and
`available_commands_update` (capability `commands`):
`available_commands_update` (capability `commands`).
From spec 3.7.0 a `tool_call`'s `title` is **the call's short title** (`display.md` §1) — the
tool's name where the call has none — and no `tool_call_update` changes it: `completed` is the
state `done`, `failed` is `failed`, and a call that was refused — it never started, so nothing
announced it — is one `tool_call` with status `failed`, `_meta.lembas.denied: true` and the reason
as its content (the state `denied`). The same title is
`title` on the `tool_start` event of `_lembas/event` and `what` of `running_tool`; `tool_end`
carries `ms`, the call's duration, and `tool_denied` its `reason`. A client of `_lembas/event`
that is given no `title` (a device before 3.7.0) makes it from `args` by the same rule.
`available_commands_update`:
```json
{ "sessionUpdate": "available_commands_update",
@@ -242,14 +257,225 @@ named like any TUI command is not a command (the built-in wins in the TUI).
An approval card. Params: ACP's `{ sessionId, toolCall: { toolCallId, title, kind, status: "pending", rawInput, content? }, options }`
with options `once` (allow_once), `session` (allow_always, absent where "always" is never offered)
and `deny` (reject_once), and `_meta.lembas: { reason, purpose?, always?, patient?, job? }`. `patient`: a
and `deny` (reject_once), and `_meta.lembas: { tool, reason, purpose?, always?, patient?, job? }`. `tool`
(spec 3.7.0): the tool's name — `toolCall.title` here is **the whole command, or the tool's name where
the call has no command**, as before 3.7.0 (a card is read before it is answered; the call's short
title of `display.md` §1 is `tool_call`'s, not the card's), so a client that titles a card by the
command still has the tool to name. `patient`: a
person may also answer at the terminal (a shared session), so the client does not time it out.
`job` (capability `jobs`): `{ id, agent, description }` when a subagent running as a background job asks, so the card
can say which — a background subagent may ask while the session itself is idle.
can say which — a background subagent may ask while the session itself is idle. `subagent` (capability `tree`, spec 3.4.0):
`{ id, name, position }` when the call is a tree subagent's that nobody in the tree could allow (`subagents.md` §7) —
the card names it; the answers are the same as for the main agent's own call.
`scheduled` (capability `scheduled`, spec 3.5.0): `{ schedule_id, run_id, wait_s }` when the call is
a scheduled turn's — nobody is at the chat, so the client puts the card to the person where they are
(LLeMbas: a notification on their phone carrying the card, answerable there and in every client),
and the device waits `wait_s` for it, not `remote.approval_timeout` (*Scheduled work*, below).
Answer: ACP's `{ outcome: { outcome: "selected", optionId } | { outcome: "cancelled" } }`, with
optional `_meta.lembas.command` (the corrected command line, `once` only) or
`_meta.lembas.feedback` (why it was denied). No answer within `remote.approval_timeout` is a denial.
## Subagents in an agent chat (spec 3.4.0)
**An agent chat's main agent is the CLI on the device.** Its subagents are the device's: it starts
them locally, on the models of the server it is logged in to, under every rule of `subagents.md` —
the model rules (§2–§3), Min/Max, slots, permissions only ever narrowed, request options, and a
call nobody in the tree can allow going to the person. The server runs no subagent of its own for
an agent chat and offers its own subagent tool to no agent chat; what it does is carry the setting
down and the tree up. A device without the capabilities `agents` and `tree` gets neither and runs no
subagents for the chat (the chat says so beside the setting).
**What goes down, with every turn.**
- `agents: { min, max }` in `_meta.lembas` of `session/new`, of **every** `session/prompt`, and of
`_lembas/configure` when the person changes it between turns — the chat's setting as the server
keeps it (`team.md` §2: 1 ≤ min ≤ max ≤ the instance's cap). The device takes the value as the
session's setting for that turn: a change reaches the main agent as `team.md` §10's note, and
nothing else reads the device's own configuration for the chat. Absent (an older server, or a
client that is not LLeMbas): the device's own setting, as before 3.4.0. A value the device's own global cap is under is read as `team.md` §2
says (lowered, never refused).
- `subagents: false` in the same `_meta.lembas` when the instance has subagents switched off: the
device offers none whatever `agents` says.
- **What the person named** (`subagents.md` §2): the person's words reach the device as the turns'
prompt texts, so the device judges a named model from them as in its own sessions — every
`session/prompt` without `machine`; never a `machine` turn, a `_lembas/steer` from the harness, or
a tool's output. A chat continued on a device that has not seen its earlier turns gets them in
`_meta.lembas.said: string[]`, the person's earlier messages of the chat, oldest first (on
`session/new` only); the device counts them as typed in the session.
- The models: the device's subagents may run on any model of the person's (`/v1/models` as the
device's token sees it), as in its own sessions.
**What comes up.**
- The tree, as it changes: the `team` event (`{ tree }`, `subagents.md` §12's data, at most four a
second), and on request `_lembas/team` (the tree and the whole room). Every agent's `progress`
is in it; the main agent's own also as the `phase` event (capability `progress`).
- Approvals: a subagent's call that only the person can allow is an ordinary
`session/request_permission` with `_meta.lembas.subagent: { id, name, position }`; the server
shows it as its usual approval card naming the subagent, in every client. Requests the main agent
decides (`team_request` / `team_decide`) never reach the server as approvals: they are room
messages.
- Findings and transcripts on request: `_lembas/team/findings`, `_lembas/team/transcript` (live and
ended subagents, read-only — the link has no method that writes into a subagent's session).
- The person stopping a subagent: `_lembas/team/stop`.
**What the server keeps.** The latest tree with the chat (so a client opening the chat draws it at
once, and after the device has gone), and the room as `_lembas/team` last answered. Findings and
transcripts stay on the device; a client asking for one while the device is not linked is told it
is on the device, and gets it once the device links again. Over `/api/v2` the chat's stream carries
the tree as it changes and the endpoints to read a subagent's transcript and findings, the same for
a chat's own subagents and for an agent chat's — so Web, Desktop and Android draw both alike.
## Scheduled work on a linked computer (spec 3.5.0)
A schedule (the server's: its rule, its runs, its history and notifications) may run **on a linked
computer**: each run is an agent turn on that device, in a folder of it, instead of a chat on the
server. The server decides *when*; the device decides *whether*, and *how far* — every rule an agent
chat has still holds, and the ones below are added. Numbers and texts: `loop.json` `scheduled`.
Conformance areas `scheduled`, `silent`, `monitor`.
### The device's setting: Accept scheduled work
- **`remote.scheduled`** in the device's global config, **off by default**; shown as **Accept
scheduled work** (`loop.json` `scheduled.setting`). Set from the command line with
`lembas service scheduled on|off` (also `lembas remote scheduled on|off`; `lembas remote list
--json` says `scheduled`), and by LLeMbas Desktop through the same command. It is global only: a
project's config cannot turn it on.
- It narrows remote work and widens nothing: a scheduled turn also needs `remote.enabled`, a folder
inside `remote.roots`, a trusted project where `remote.require_trust`, and a mode within
`remote.max_mode`, exactly as an agent chat does.
- The device says it in `limits.scheduled` (hello and `initialize`). Turning it on or off changes
the limits, so the device dials again once nothing works (as for any limit) and the client hears
it. The client may offer the device in a schedule's form only while `limits.scheduled` is true,
and says why not otherwise. The device judges it again at every `session/new`, `session/prompt`
and `_lembas/monitor` that is scheduled, whatever it said earlier.
- **Off** (or remote work off): every scheduled request is refused with `-32602`, the message
`loop.json` `scheduled.texts.off` word for word, and `data: { reason: "scheduled_off" }`. Not
retried: it is the person's setting. A folder the device does not accept is `-32602` with the
usual reason and `data: { reason: "folder" }`.
### Starting a scheduled turn
The client opens an agent session as for an agent chat (`session/new`: `cwd`, `lembas_model`,
`effort`, `_meta.lembas` with `agents` — the schedule's **Min/Max**, as an agent chat's — and the
`Context`), marked scheduled:
```json
"_meta": { "mode": "edit", "lembas_model": "qwen", "lembas": {
"agents": { "min": 1, "max": 4 },
"scheduled": { "schedule_id": "sched1", "run_id": "run7", "title": "Waybread check",
"mode": "edit", "approval_wait_s": 1800 } } }
```
and runs the turn with `session/prompt`, its `_meta.lembas` carrying the same `scheduled` object
(and a `turnId`, the run's — so a prompt sent again after a dropped link gets the run's answer
instead of a second run). A schedule that continues one conversation (`continue`) prompts the same
session again on its next run; a fresh run opens a new one. The prompt's text is the server's own
for a scheduled run — the instruction, the run's time, and for a schedule that notifies only when
it matters the `[SILENT]` hint — composed exactly as for a run on the server; the device adds nothing.
**The mode** (`scheduled.mode`; `_meta.mode` is ignored for a scheduled session): `manual`, `edit`
or `auto`, and **`edit` when absent** — so a run is never wider than Edit unless the person picked
Auto on that schedule. `plan` is refused (`scheduled.texts.plan`, `data: { reason: "plan" }`):
nobody is there to approve a plan. Then lowered to `remote.max_mode`, as every remote session is —
Auto runs only where both the schedule and the device allow it (`conformance/scheduled.json`). The
mode holds for the turn; neither `_lembas/configure` nor a command in the prompt widens it.
In a scheduled turn:
- **Approvals** go to the person through the client (`session/request_permission` with
`_meta.lembas.scheduled: { schedule_id, run_id, wait_s }`), and the device waits
`approval_wait_s` — the schedule's wait, 30 minutes by default, clamped to
`scheduled.approval_wait_seconds` — instead of `remote.approval_timeout`. Unanswered by then, the
call is denied with `scheduled.texts.denied` as the feedback the model reads (`{{minutes}}` the
wait in whole minutes), the card is settled (`_lembas/permission/settled`), and the turn goes on —
the model works around the refusal or fails. Not `patient`.
- **`ask_user` and `plan_submit`** have nobody to answer: the device answers them as it does with
no client (`ask_user` tells the model nobody can be asked; `plan_submit` saves the plan and says
to stop). `show` is not offered: nobody is looking.
- Subagents as in an agent chat (`agents`, the tree, findings); a subagent's call only the person
can allow is an approval like the main agent's, with `scheduled` beside `subagent`.
### How the turn ends and reports
`session/prompt`'s answer carries the run's outcome in `_meta.lembas.scheduled`:
```json
{ "stopReason": "end_turn", "_meta": { "lembas": { "turnId": "run7",
"scheduled": { "run_id": "run7", "status": "ok", "text": "All the waybread is wrapped.",
"error": null } } } }
```
**From spec 3.8.0 (capability `reports`, `reports.md` §6)** the client marks the turn with the
schedule's notify-when — `"scheduled": { …, "notify": "always" | "when" | "never" }` in
`session/new` and `session/prompt` — and the prompt it composes carries the instruction for it
(`loop.json` `scheduled.notify.texts`) where the `[SILENT]` hint used to be. A device with the
capability offers `report_write` in that session unless `notify` is `never`
(`tools/report_write.json`, `requires: scheduled`: unavailable in a turn of the session that is
not the schedule's), keeps the last report the run's model wrote, and answers with it:
```json
"scheduled": { "run_id": "run7", "status": "ok", "text": "Filed a report: the disk is almost full.",
"error": null,
"report": { "title": "Disk almost full", "summary": "The log partition is at 94%.",
"body": "## What\n\n…", "importance": "high" } }
```
`report` is absent when none was written; it is kept even when the turn then failed. For a turn
whose request said `notify`, the sentinel means nothing and `status` is never `silent`. What the
run leaves — the report, the `always` fallback, the history line, the notification — is the
client's to decide from this answer (`reports.md` §4). A device without the capability is sent no
`notify`; a client without it sends none, and everything below is as in 3.5.0.
- **`text`**: the turn's final reply — the text of the last assistant message the turn wrote, as
written (`[SILENT]` included). Model output: untrusted wherever it is shown.
- **`status`**: `cancelled` — the turn was cancelled (`session/cancel`: the person stopped it, or the
client's inactivity limit); `failed` — the turn ended on an error (`error` its text), or with no
reply text at all (`scheduled.texts.no_reply`); `silent` — the reply says the sentinel
`[SILENT]` on its first or last non-empty line (any case, a trailing full stop forgiven;
`conformance/silent.json`, the server's own rule for its runs); otherwise `ok`. A turn that hit the
step backstop or a budget and still wrote a reply is `ok`; `stopReason` says why it stopped.
- The client records the run from this (its history, its notification by the schedule's policy —
`silent` is never notified, a failure is told as a failure), and keeps the session as the run's
agent chat, whose events it received as for any agent chat. What the sentinel stripped looks like
is `silent.json`'s `stripped`.
### When the device is away, or refuses
- **Away** (not linked when the run is due, or the link drops before `session/new` is answered): the
client treats the device like a busy model — the run is `waiting` (`waiting_for: "device"`) and
tried again on the same steps a run waiting for a free model is, until the run's window closes;
then it is **missed**. A turn already running when the link drops is followed again by
`_lembas/session/status` and the turn id, as for any agent chat.
- **Refused** (`-32602` from a scheduled `session/new`, `session/prompt` or `_lembas/monitor`): the
run **fails** with the device's message, said in the run's history and in the failure
notification; `data.reason` (`scheduled_off`, `folder`, `plan`, `permission`) lets the client say
what to change. Not retried.
### Monitor mode: a command watched on the device
A schedule may **watch** something and run the model only when it changed. A URL is fetched by the
server and needs nothing from the device; a **command's output** is watched on the device with
`_lembas/monitor` (below): the client asks the device to run the watch command, compares the
answer's `hash` with the one the previous check stored, and when it is the same records the run as
`unchanged` — no model, nobody notified. Changed (or the first check), the model runs as the
schedule says — on the server, or as a scheduled turn on the device — told what changed through the
`excerpt`. A check that fails (timed out, refused) is a failed run.
The command runs under the **same permission rules as the schedule's mode**, with one difference:
**a command the mode would ask about is refused**, because a watch has nobody to ask. The device
judges the command line as `bash` would be judged in a session in that folder (the hardline, the
default rules, the global rules and — in a trusted project — the project's), and runs it only on
`allow`; `ask` is refused with `scheduled.texts.monitor_asks`, `deny` with
`scheduled.texts.monitor_denied`, both `-32602` with `data: { reason: "permission" }`
(`conformance/monitor.json`).
**The hash** (`monitor.json` `hash` cases): `sha256:` and the lowercase hex SHA-256 of the
output's bytes exactly as read — standard output and standard error as one stream, as the `bash`
tool reads them — followed by a newline and the exit status as decimal digits (after the bytes, so
the device hashes the output as it streams, however long). Nothing is normalised: a watch command
that prints a time changes every time, and should not.
## `_lembas/*` methods
Direction is who sends it. "→ result" marks a request; the others are notifications.
@@ -257,7 +483,9 @@ Direction is who sends it. "→ result" marks a request; the others are notifica
### `_lembas/hello` — agent → client
Sent once when the link opens, before `initialize`:
`{ protocol, version, harness_spec, device: { host, platform }, limits: { roots, max_mode, require_trust } }`.
`{ protocol, version, harness_spec, device: { host, platform }, limits: { roots, max_mode, require_trust, scheduled } }`
(`scheduled` since spec 3.5.0: whether the device accepts scheduled work; a change of it is a
change of the limits, below).
A device links whether its remote work is on or not, and with no roots at all. Off, or with no
roots, it says `limits.roots: []` here and in `initialize`, and refuses every `session/new`, every
@@ -275,7 +503,7 @@ client hears the new limits.
`{ sessionId, event }`: every engine event of the session, to a client that said `_meta.lembas`.
`event.type` is one of `session`, `prompt`, `step`, `title`, `text`, `reasoning`,
`tool_call_delta`, `progress`, `tool_start`, `tool_end`, `tool_denied`, `usage`, `inbox`,
`steered`, `task`, `notice`, `retract`, `plan`, `compacted`, `sub_tool`, `job`, `job_note`, `mode`, `model`, `flash`,
`steered`, `task`, `notice`, `retract`, `plan`, `compacted`, `sub_tool`, `job`, `job_note`, `phase`, `team`, `mode`, `model`, `flash`,
`setting`, `error`, `done` (`src/bus/index.ts`). Those this protocol relies on:
| Event | Fields |
@@ -284,13 +512,31 @@ client hears the new limits.
| `task` | `state: "start" \| "end"`, `turnId` — every turn has one: the client's, or one made here for a turn typed in a terminal |
| `steered` | `texts`, `ids?` — the `_lembas/steer` message ids taken in at this step |
| `mode` | `mode` |
| `model` | `ref` (the device's ref, above), `effort` (a level or `"off"`), `connection` (the device connection it is spoken to through) and **`instance: boolean`** — true exactly when that connection is the login of **this link's** instance, i.e. the model is one the instance serves (its served id is `ref`, or `ref` less a leading `<connection>/`). Whenever either changes, for any reason: `/model`, `/effort`, the settings tool, a fallback, `_lembas/configure` |
| `model` | `ref` (the device's ref, above), `effort` (one of the model's levels: an effort, `"off"` or `"default"`), `connection` (the device connection it is spoken to through) and **`instance: boolean`** — true exactly when that connection is the login of **this link's** instance, i.e. the model is one the instance serves (its served id is `ref`, or `ref` less a leading `<connection>/`). Whenever either changes, for any reason: `/model`, `/effort`, the settings tool, a fallback, `_lembas/configure` |
| `plan` | `plan` — the structure, or `null` when cleared (what the `plan` session update carries) |
| `compacted` | `summary` |
| `title` | `id`, `title` |
| `job` | `state: "start" \| "update" \| "end"`, `job: JobInfo` (capability `jobs`) — a background job of the session began, has news (new output, a subagent's step; at most four a second per job), or ended. `JobInfo = { id, kind: "command" \| "subagent", state: "running" \| "done" \| "stopped" \| "error" \| "lost", description, command?, agent?, model?, started, ended?, exit?, unread, steps?, tools?, ownerJobId? }` — `description` what is shown for it (a command's `description` or its first line; a subagent's description), `unread` characters of output the model has not read, `exit` a command's exit code (null: a signal), `ownerJobId` set on a job a subagent started, `lost` a job that was running when the device's process ended |
| `job_note` | `jobId`, `text` (capability `jobs`) — the note about that job was given to the model: inside a turn at the next step, or as the `machine` turn whose `prompt` follows |
| `sub_tool` | `callId` (the `task` call the subagent belongs to), `jobId?` (its job, when it runs as one), `name`, `title`, `isError?` — a tool call of a subagent finished; a client draws it under the task line, or in the job's panel |
| `phase` | `progress` — the progress object (`progress.md` §1), or `null` when nothing runs; `agent?` — the subagent's id when it is a subagent's, absent for the main agent's (capability `progress`). Sent when the phase changes, and for a change of its data at most four times a second. The existing `progress` event (the prompt's tokens read) is unchanged |
| `team` | `tree` — the session's subagent tree (`subagents.md` §12, the data) — whenever it changes, at most four times a second (capability `tree`). A client draws it and fetches nothing else to do so |
### `_lembas/monitor` — client → agent → result (capability `scheduled`)
The watch command of a schedule in monitor mode (*Monitor mode*, above). Params
`{ cwd, command, mode?, timeout_s?, schedule_id?, run_id? }` — `cwd` absolute, judged as
`session/new`'s; `mode` the schedule's (`manual`, `edit` or `auto`; `edit` when absent; `plan`
refused), lowered to `remote.max_mode`; `timeout_s` defaulting to and clamped by
`loop.json` `scheduled.monitor.timeout_seconds`. Refused like any scheduled request when the device
does not accept scheduled work. The command runs as `bash -c` in `cwd`, in its own process group,
with no input; at the timeout the group is stopped.
Result `{ hash, exit, timed_out, excerpt, truncated, bytes, duration_ms }`: `hash` as above (`null`
when it timed out), `exit` the exit status (`null` on a signal or a timeout), `excerpt` the start of
the output decoded as UTF-8 (invalid bytes replaced), at most `scheduled.monitor.excerpt_chars`
characters, `truncated` whether there was more, `bytes` the output's length. The device hashes all
of the output as it streams and keeps at most `scheduled.monitor.output_max_bytes` of it.
### `_lembas/directories` — client → agent → result
@@ -301,7 +547,7 @@ Only on the link (an error on `serve --stdio`).
### `_lembas/configure` — client → agent → result
Params `{ sessionId, model?: <instance's name>, effort?: <level> | "off" }` between prompts. Result
Params `{ sessionId, model?: <instance's name>, effort?: <level>, agents?: { min, max } }` between prompts (a level as in `session/new`; `agents` with capability `agents`, spec 3.4.0). Result
`{ model: <ref>, effort }`. Emits a `model` event when something changed.
### `_lembas/steer` — client → agent → result
@@ -319,9 +565,9 @@ with the message in the store; `attachments`, and the text without them) or `{ r
### `_lembas/session/status` — client → agent → result
Params `{ sessionId }`. Result
`{ sessionId, exists, held: "here" | "terminal" | "none", busy, title, turnId?, queued: string[], lastTurnId?, plan?, jobs? }`
`{ sessionId, exists, held: "here" | "terminal" | "none", busy, title, turnId?, queued: string[], lastTurnId?, plan?, jobs?, progress?, tree? }`
— `plan` the session's plan or `null` (capability `plan_state`), so a client reattaching draws it
without waiting for the next change; `jobs` the session's background jobs, `JobInfo[]` running first (capability `jobs`), for the same reason; the turn fields with capability `turns`: the turn running now, the ones waiting, the last
without waiting for the next change; `progress` the main agent's progress object or `null` (capability `progress`), and `tree` the subagent tree or `null` when the session has none (capability `tree`), for the same reason; `jobs` the session's background jobs, `JobInfo[]` running first (capability `jobs`), for the same reason; the turn fields with capability `turns`: the turn running now, the ones waiting, the last
one finished (for a session not open, `held: "none"`, the last one it finished before). **Reattaching** after a restart or a dropped link, for an incomplete row with turn T:
T running → follow it; T queued → wait, and follow it when it starts; T done → import it from
`history`; T unknown → send the prompt again (safe: the device deduplicates).
@@ -362,6 +608,30 @@ with its output — so a client can show the subagent as a panel and follow it w
`job` events that come after. `-32602` for a command job. A subagent's transcript lasts as long as
its session row on the device: it is kept with the parent session and deleted with it.
### `_lembas/team` — client → agent → result (capability `tree`)
Params `{ sessionId, since?: number }`. Result `{ tree, room }`: the subagent tree (`subagents.md`
§12) and the room's messages numbered above `since` (default 0), every one — the person sees the
whole room — each `{ n, from, to, recipients, text, time, report, kind }` with `kind` one of
`message`, `report`, `assignment`, `request`, `decision`. `tree` is `null` for a session with no
subagents. For a session held by a terminal, answered through the hub, as `status` is.
### `_lembas/team/transcript` — client → agent → result (capability `tree`)
Params `{ sessionId, id }` — a subagent's id (`s1`), live or ended. Result `{ id, state, turns }` in
the shape of `_lembas/session/history`'s `turns`: its conversation so far, **read-only** — the link
has no method to write into it. A client following it live refetches on the `team` event and draws
the `sub_tool` events meanwhile. `-32602` for an id the session never had.
### `_lembas/team/findings` — client → agent → result (capability `tree`)
Params `{ sessionId, id }`. Result `{ id, findings: [{ n, text, time }] }`, ended subagents' too.
### `_lembas/team/stop` — client → agent → result (capability `tree`)
Params `{ sessionId, id }`: the person stops a subagent and its subtree (`subagents.md` §10), said to
the main agent as a note. Result `{ stopped: [id, …] }`; `-32602` for an id that is not live.
### `_lembas/session/delete` — client → agent → result
Params `{ sessionId }`: the chat was deleted. The session stops if it works, leaves the store (its
@@ -600,6 +870,24 @@ Besides `/v1/models`, the chat completions, `/api/v1/instance` and `/mcp`:
older `library` scope counts as `memory`. Local memory files are not synced up; logged out, there
is no memory.
- **Schedules** (spec 3.5.0): the schedule routes of `/api/v2` — `GET`/`POST /api/v2/schedules`,
`GET`/`PATCH`/`DELETE /api/v2/schedules/{id}`, `POST …/{id}/pause`, `/resume`, `/run`,
`GET …/{id}/runs`, `GET …/{id}/runs/{run}`, `POST /api/v2/schedules/compile` and `/preview` —
**accept the device's token** (scope `link`) as well as an app's (`app`), for the same person and
under the same `schedule.use` permission; nothing else of `/api/v2` does. The shapes are the
server's (its contract fixtures); what the CLI's `/schedule` relies on: a schedule's `id`,
`title`, `instruction`, `description`, `enabled`, `next_run`, `last_run` (`status`, `timing`,
`due_at`, `finished_at`, `preview`, `error.text`), `running`; a run's `id`, `status`, `due_at`,
`started_at`, `finished_at`, `model.name`, `preview`, `error`; compile's `ok`, `reason`, `title`,
`instruction`, `rule`, `description`, `next_runs`, `timezone`. A run's `status` may also be
**`unchanged`** (monitor mode: the watch saw nothing new; no model ran), and `waiting_for` may be
**`device`**. A schedule that runs on a linked computer has
**`runs_on: { device, device_name, cwd, mode, approval_wait_minutes }`** (else `null`); one that
watches has **`watch: { kind: "url", url } | { kind: "command", command, timeout_s }`** (else
`null`). Creating one with the device's token, `runs_on.device: "this"` names the calling device.
A server without these answers 401 or 403 to the device's token, and the CLI says the server is
older.
## Notes
- `_lembas/files/search`'s `root` is the session's working directory, which `@path` mentions
+433
View File
@@ -0,0 +1,433 @@
{
"about": "Delegation (subagents.md §7, spec 3.4.0): a subagent's mode and request options, and who decides its calls. The project root is /project, nothing named exists on disk, and only the default rules apply (permission/defaults.json). `add` — team_add's mode check for a parent in `parent_mode` with `mode` and `request` as given → `{result, mode}`: the refusal word for word, or null and the mode the subagent gets. `call` — a subagent in `mode` with `request` options and `grants` (rules {tool, pattern} the main agent allowed) under a main agent in `main_mode`, calling `call` (`bash` with a `line`, or a file tool with a `path` relative to the root) → `{answer, text?}`: `run`, `person` (an approval card to the person), or `refused` with its text, word for word — except where the case says `own_reason` (a hardline's, a mode's or the unattended refusal's reason is each project's), when only the answer is compared. `unattended`: nobody can answer. `request` — team_request for `tool` by a subagent with `request` options, its first → `{result}`. `switch` — the main agent's mode changes from `main_from` to `main_to` with these subagents (each with its parent and mode) → each one's mode after. LLeMbas: services/team.py; CLI: team/delegation.ts.",
"cases": [
{
"about": "No mode given: the parent's.",
"op": "add",
"parent_mode": "edit",
"expect": {
"result": null,
"mode": "edit"
}
},
{
"about": "Stricter is allowed.",
"op": "add",
"parent_mode": "edit",
"mode": "manual",
"expect": {
"result": null,
"mode": "manual"
}
},
{
"about": "Looser is refused, naming the parent's mode.",
"op": "add",
"parent_mode": "manual",
"mode": "edit",
"expect": {
"result": "A subagent's mode cannot be looser than its parent's (manual).",
"mode": null
}
},
{
"about": "Plan is the strictest: anything else under it is looser.",
"op": "add",
"parent_mode": "plan",
"mode": "auto",
"expect": {
"result": "A subagent's mode cannot be looser than its parent's (plan).",
"mode": null
}
},
{
"about": "Request options with the parent's own mode: nothing to ask for.",
"op": "add",
"parent_mode": "auto",
"mode": "auto",
"request": [
"write"
],
"expect": {
"result": "Request options go with a mode stricter than the parent's: without one there is nothing to ask for.",
"mode": null
}
},
{
"about": "Request options with no mode given (the parent's): refused the same way.",
"op": "add",
"parent_mode": "edit",
"request": [
"execute"
],
"expect": {
"result": "Request options go with a mode stricter than the parent's: without one there is nothing to ask for.",
"mode": null
}
},
{
"about": "Request options with a stricter mode.",
"op": "add",
"parent_mode": "edit",
"mode": "manual",
"request": [
"write",
"execute"
],
"expect": {
"result": null,
"mode": "manual"
}
},
{
"about": "An unknown kind is refused, naming it.",
"op": "add",
"parent_mode": "edit",
"mode": "manual",
"request": [
"delete"
],
"expect": {
"result": "delete is not a request option: use read, write or execute.",
"mode": null
}
},
{
"about": "An empty list of request options is no options, and needs nothing.",
"op": "add",
"parent_mode": "edit",
"request": [],
"expect": {
"result": null,
"mode": "edit"
}
},
{
"about": "All in edit: an edit inside the project runs.",
"op": "call",
"main_mode": "edit",
"mode": "edit",
"call": {
"tool": "edit",
"path": "src/a.ts"
},
"expect": {
"answer": "run"
}
},
{
"about": "All in edit: bash that edit mode asks goes to the person — the main agent could not allow it either.",
"op": "call",
"main_mode": "edit",
"mode": "edit",
"call": {
"tool": "bash",
"line": "git push origin main"
},
"expect": {
"answer": "person"
}
},
{
"about": "All in manual: an edit goes to the person.",
"op": "call",
"main_mode": "manual",
"mode": "manual",
"call": {
"tool": "edit",
"path": "src/a.ts"
},
"expect": {
"answer": "person"
}
},
{
"about": "Narrowed with no request options: what the main agent could allow is refused.",
"op": "call",
"main_mode": "edit",
"mode": "manual",
"call": {
"tool": "edit",
"path": "src/a.ts"
},
"expect": {
"answer": "refused",
"text": "Your mode does not allow this, and you may not ask for it: tell your parent what you need."
}
},
{
"about": "Narrowed with the kind in its options: it asks the main agent.",
"op": "call",
"main_mode": "edit",
"mode": "manual",
"request": [
"write"
],
"call": {
"tool": "edit",
"path": "src/a.ts"
},
"expect": {
"answer": "refused",
"text": "Your mode does not allow this, but the main agent may: ask for it with team_request (the tool, the pattern, why), then try again once it allows."
}
},
{
"about": "Narrowed, the kind not in its options.",
"op": "call",
"main_mode": "auto",
"mode": "edit",
"request": [
"write"
],
"call": {
"tool": "bash",
"line": "git push origin main"
},
"expect": {
"answer": "refused",
"text": "Your mode does not allow this, and you may not ask for it: tell your parent what you need."
}
},
{
"about": "Narrowed, execute in its options: asks the main agent.",
"op": "call",
"main_mode": "auto",
"mode": "edit",
"request": [
"execute"
],
"call": {
"tool": "bash",
"line": "git push origin main"
},
"expect": {
"answer": "refused",
"text": "Your mode does not allow this, but the main agent may: ask for it with team_request (the tool, the pattern, why), then try again once it allows."
}
},
{
"about": "A grant from the main agent lets the call run.",
"op": "call",
"main_mode": "auto",
"mode": "edit",
"request": [
"execute"
],
"grants": [
{
"tool": "bash",
"pattern": "git push *"
}
],
"call": {
"tool": "bash",
"line": "git push origin main"
},
"expect": {
"answer": "run"
}
},
{
"about": "A grant for another pattern does not.",
"op": "call",
"main_mode": "auto",
"mode": "edit",
"request": [
"execute"
],
"grants": [
{
"tool": "bash",
"pattern": "git push *"
}
],
"call": {
"tool": "bash",
"line": "git commit -m x"
},
"expect": {
"answer": "refused",
"text": "Your mode does not allow this, but the main agent may: ask for it with team_request (the tool, the pattern, why), then try again once it allows."
}
},
{
"about": "A grant never reaches past the main agent's own mode: what it would have to ask goes to the person.",
"op": "call",
"main_mode": "edit",
"mode": "manual",
"request": [
"execute"
],
"grants": [
{
"tool": "bash",
"pattern": "git push *"
}
],
"call": {
"tool": "bash",
"line": "git push origin main"
},
"expect": {
"answer": "person"
}
},
{
"about": "Reading .env asks in every mode: it goes to the person.",
"op": "call",
"main_mode": "edit",
"mode": "edit",
"call": {
"tool": "read",
"path": ".env"
},
"expect": {
"answer": "person"
}
},
{
"about": "Reading .env under an auto main agent: a narrowed subagent with read in its options asks it.",
"op": "call",
"main_mode": "auto",
"mode": "manual",
"request": [
"read"
],
"call": {
"tool": "read",
"path": ".env"
},
"expect": {
"answer": "refused",
"text": "Your mode does not allow this, but the main agent may: ask for it with team_request (the tool, the pattern, why), then try again once it allows."
}
},
{
"about": "Plan mode's refusal is final: request options do not reach past it.",
"op": "call",
"main_mode": "auto",
"mode": "plan",
"request": [
"execute"
],
"call": {
"tool": "bash",
"line": "rm -rf build"
},
"own_reason": true,
"expect": {
"answer": "refused"
}
},
{
"about": "What the rules allow runs in every mode.",
"op": "call",
"main_mode": "edit",
"mode": "plan",
"call": {
"tool": "bash",
"line": "git status"
},
"expect": {
"answer": "run"
}
},
{
"about": "The hardline refuses in every mode, auto included.",
"op": "call",
"main_mode": "auto",
"mode": "auto",
"call": {
"tool": "bash",
"line": "rm -rf /"
},
"own_reason": true,
"expect": {
"answer": "refused"
}
},
{
"about": "Unattended: what would go to the person is refused.",
"op": "call",
"main_mode": "edit",
"mode": "edit",
"unattended": true,
"call": {
"tool": "bash",
"line": "git push origin main"
},
"own_reason": true,
"expect": {
"answer": "refused"
}
},
{
"about": "team_request: a tool whose risk class is not in the options is refused, naming them.",
"op": "request",
"request": [
"write"
],
"tool": "bash",
"expect": {
"result": "You may not ask for bash: your request options are write."
}
},
{
"about": "team_request: a kind in the options is asked, with the request's id.",
"op": "request",
"request": [
"write",
"execute"
],
"tool": "bash",
"expect": {
"result": "Asked the main agent (r1): you are told its decision. Carry on with what you can meanwhile."
}
},
{
"about": "The main agent made stricter: every subagent looser than its parent is made as strict as it, down the tree; a stricter one keeps its own.",
"op": "switch",
"agents": [
{
"name": "api",
"parent": "lead",
"mode": "auto"
},
{
"name": "tests",
"parent": "api",
"mode": "edit"
},
{
"name": "docs",
"parent": "lead",
"mode": "plan"
}
],
"main_from": "auto",
"main_to": "manual",
"expect": {
"api": "manual",
"tests": "manual",
"docs": "plan"
}
},
{
"about": "The main agent made looser: no subagent changes.",
"op": "switch",
"agents": [
{
"name": "api",
"parent": "lead",
"mode": "edit"
}
],
"main_from": "edit",
"main_to": "auto",
"expect": {
"api": "edit"
}
}
]
}
+684
View File
@@ -0,0 +1,684 @@
{
"about": "Display (display.md, spec 3.7.0), in the plain number format. `show` says what is asked. `title`: a call's `args` (and its `tool`, for the reader) — expect `title`, the one short title (display.md §1), or null where the call has none. `duration`: a call's `state` and `ms` — expect `duration` as drawn beside the title (§2), or null. `change`: a unified `diff` — expect `added`, `removed` counted by its hunks, and `text` (loop.json display.change). `facts`: a finished call's `block` with its `diff`, `exit` or `hits` — expect `facts`, the texts after the title in order. `end`: a turn's last `progress` (or null) — expect `line`, the line that stays on the finished reply (§4), or null. `drawn`: a `block` — whether it is drawn as a call (§3). LLeMbas: services/display.py; CLI: session/display.ts.",
"cases": [
{
"about": "A command is its own title.",
"show": "title",
"tool": "bash",
"args": {
"command": "bun test",
"description": "Run the tests"
},
"expect": {
"title": "bun test"
}
},
{
"about": "Only the first line of a command.",
"show": "title",
"tool": "bash",
"args": {
"command": " cd src &&\n make "
},
"expect": {
"title": "cd src &&"
}
},
{
"about": "A search is titled by its pattern, not where it looks.",
"show": "title",
"tool": "grep",
"args": {
"pattern": "TODO\\(",
"path": "src"
},
"expect": {
"title": "TODO\\("
}
},
{
"about": "A file search likewise.",
"show": "title",
"tool": "glob",
"args": {
"pattern": "**/*.ts",
"path": "src/tui"
},
"expect": {
"title": "**/*.ts"
}
},
{
"about": "A read by its path.",
"show": "title",
"tool": "read",
"args": {
"path": "src/app.ts",
"offset": 120
},
"expect": {
"title": "src/app.ts"
}
},
{
"about": "A listing with no path has no title.",
"show": "title",
"tool": "list",
"args": {
"depth": 2
},
"expect": {
"title": null
}
},
{
"about": "An edit by its path.",
"show": "title",
"tool": "edit",
"args": {
"path": "README.md",
"old": "a",
"new": "b"
},
"expect": {
"title": "README.md"
}
},
{
"about": "A web search by its query.",
"show": "title",
"tool": "web_search",
"args": {
"query": "opentui extmarks",
"max_results": 5
},
"expect": {
"title": "opentui extmarks"
}
},
{
"about": "A fetch by its address.",
"show": "title",
"tool": "web_fetch",
"args": {
"url": "https://example.org/docs"
},
"expect": {
"title": "https://example.org/docs"
}
},
{
"about": "A task by its description, not its prompt.",
"show": "title",
"tool": "task",
"args": {
"description": "Find the callers",
"prompt": "Look through src/ for every caller of load() and list them."
},
"expect": {
"title": "Find the callers"
}
},
{
"about": "A subagent by its name.",
"show": "title",
"tool": "team_add",
"args": {
"name": "Reviewer",
"role": "reviews the change",
"task": "Read the diff."
},
"expect": {
"title": "Reviewer"
}
},
{
"about": "A phone action by its summary, whatever else it carries.",
"show": "title",
"tool": "phone_action",
"args": {
"action": "open_url",
"summary": "Open the timetable",
"url": "https://example.org/t"
},
"expect": {
"title": "Open the timetable"
}
},
{
"about": "Python by the first line of its code.",
"show": "title",
"tool": "python",
"args": {
"code": "import math\nprint(math.pi)"
},
"expect": {
"title": "import math"
}
},
{
"about": "A question by its headers.",
"show": "title",
"tool": "ask_user",
"args": {
"why": "The schema is open.",
"questions": [
{
"header": "Database",
"question": "Which one?",
"options": []
},
{
"header": "Cache",
"question": "Which cache?",
"options": []
}
]
},
"expect": {
"title": "Database · Cache"
}
},
{
"about": "A patch by the files it names.",
"show": "title",
"tool": "apply_patch",
"args": {
"patch": "*** Begin Patch\n*** Update File: src/a.ts\n@@\n-x\n+y\n*** Add File: docs/b.md\n+hello\n*** Delete File: old.txt\n*** End Patch"
},
"expect": {
"title": "src/a.ts, docs/b.md, old.txt"
}
},
{
"about": "A unified diff as a patch: the +++ paths, without b/ and without /dev/null.",
"show": "title",
"tool": "apply_patch",
"args": {
"patch": "--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1 +1 @@\n-x\n+y\n--- a/gone.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-bye\n"
},
"expect": {
"title": "src/a.ts"
}
},
{
"about": "A patch that names nothing falls back to its path.",
"show": "title",
"tool": "apply_patch",
"args": {
"patch": "@@ -1 +1 @@\n-x\n+y\n",
"path": "src/a.ts"
},
"expect": {
"title": "src/a.ts"
}
},
{
"about": "Cut to 80 characters: 79 and an ellipsis.",
"show": "title",
"tool": "bash",
"args": {
"command": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
"expect": {
"title": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…"
}
},
{
"about": "Exactly 80 is not cut.",
"show": "title",
"tool": "bash",
"args": {
"command": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
},
"expect": {
"title": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
}
},
{
"about": "Counted in code points, not UTF-16 units.",
"show": "title",
"tool": "bash",
"args": {
"command": "echo 🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂"
},
"expect": {
"title": "echo 🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂…"
}
},
{
"about": "A blank argument is passed over.",
"show": "title",
"tool": "grep",
"args": {
"pattern": " ",
"path": "src"
},
"expect": {
"title": "src"
}
},
{
"about": "An argument that is not a string is passed over.",
"show": "title",
"tool": "job_output",
"args": {
"id": "job3",
"wait": 30
},
"expect": {
"title": "job3"
}
},
{
"about": "A setting by its key.",
"show": "title",
"tool": "settings",
"args": {
"action": "set",
"key": "theme",
"value": "moria"
},
"expect": {
"title": "theme"
}
},
{
"about": "Only an action.",
"show": "title",
"tool": "tasks",
"args": {
"action": "list"
},
"expect": {
"title": "list"
}
},
{
"about": "No arguments, no title.",
"show": "title",
"tool": "job_list",
"args": {},
"expect": {
"title": null
}
},
{
"about": "Arguments that are not an object, no title.",
"show": "title",
"tool": "read",
"args": "src/app.ts",
"expect": {
"title": null
}
},
{
"about": "A finished call: tenths under a minute.",
"show": "duration",
"state": "done",
"ms": 412,
"expect": {
"duration": "0.4s"
}
},
{
"about": "Seconds.",
"show": "duration",
"state": "done",
"ms": 8449,
"expect": {
"duration": "8.4s"
}
},
{
"about": "Just under a minute.",
"show": "duration",
"state": "failed",
"ms": 59940,
"expect": {
"duration": "59.9s"
}
},
{
"about": "What would round to 60.0s is a minute.",
"show": "duration",
"state": "done",
"ms": 59960,
"expect": {
"duration": "1m 00s"
}
},
{
"about": "The last tenth under a minute.",
"show": "duration",
"state": "done",
"ms": 59949,
"expect": {
"duration": "59.9s"
}
},
{
"about": "From a minute: minutes and whole seconds.",
"show": "duration",
"state": "done",
"ms": 65000,
"expect": {
"duration": "1m 05s"
}
},
{
"about": "From an hour: hours and minutes.",
"show": "duration",
"state": "done",
"ms": 7380000,
"expect": {
"duration": "2h 03m"
}
},
{
"about": "A failed call shows how long it took.",
"show": "duration",
"state": "failed",
"ms": 1200,
"expect": {
"duration": "1.2s"
}
},
{
"about": "A denied call shows none.",
"show": "duration",
"state": "denied",
"ms": 3,
"expect": {
"duration": null
}
},
{
"about": "A running call shows none.",
"show": "duration",
"state": "running",
"ms": 5000,
"expect": {
"duration": null
}
},
{
"about": "A stored call whose time was not kept shows none.",
"show": "duration",
"state": "done",
"expect": {
"duration": null
}
},
{
"about": "One line changed.",
"show": "change",
"diff": "--- a/a.txt\n+++ b/a.txt\n@@ -1,3 +1,3 @@\n one\n-two\n+2\n three\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "Headers without a/ and b/ are still headers.",
"show": "change",
"diff": "Index: a.txt\n===================================================================\n--- a.txt\n+++ a.txt\n@@ -1,2 +1,3 @@\n one\n+one and a half\n two\n",
"expect": {
"added": 1,
"removed": 0,
"text": "+1 −0"
}
},
{
"about": "A removed line that begins with `-- ` and an added one that begins with `++ ` are lines, not headers.",
"show": "change",
"diff": "--- a/q.sql\n+++ b/q.sql\n@@ -1,3 +1,3 @@\n select 1;\n--- the old comment\n+++ the new one\n select 2;\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "A new file.",
"show": "change",
"diff": "--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n",
"expect": {
"added": 2,
"removed": 0,
"text": "+2 −0"
}
},
{
"about": "A hunk header without counts means one line each.",
"show": "change",
"diff": "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "No newline at end of file counts for nothing.",
"show": "change",
"diff": "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n\\ No newline at end of file\n+b\n\\ No newline at end of file\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "Two files add up.",
"show": "change",
"diff": "diff --git a/a b/a\n--- a/a\n+++ b/a\n@@ -1 +1,2 @@\n a\n+b\ndiff --git a/c b/c\n--- a/c\n+++ b/c\n@@ -1,2 +1 @@\n c\n-d\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "No diff, nothing changed.",
"show": "change",
"diff": "",
"expect": {
"added": 0,
"removed": 0,
"text": "+0 −0"
}
},
{
"about": "An edit shows its change.",
"show": "facts",
"block": "edit",
"diff": "--- a/x\n+++ b/x\n@@ -1 +1,2 @@\n-a\n+b\n+c\n",
"expect": {
"facts": [
"+2 −1"
]
}
},
{
"about": "A command that failed shows its exit code.",
"show": "facts",
"block": "shell",
"exit": 2,
"expect": {
"facts": [
"exit 2"
]
}
},
{
"about": "A command that succeeded shows none.",
"show": "facts",
"block": "shell",
"exit": 0,
"expect": {
"facts": []
}
},
{
"about": "A search shows its hits.",
"show": "facts",
"block": "search",
"hits": 14,
"expect": {
"facts": [
"14 hits"
]
}
},
{
"about": "One hit.",
"show": "facts",
"block": "search",
"hits": 1,
"expect": {
"facts": [
"1 hit"
]
}
},
{
"about": "No hits is a fact too.",
"show": "facts",
"block": "search",
"hits": 0,
"expect": {
"facts": [
"0 hits"
]
}
},
{
"about": "A read has none of these.",
"show": "facts",
"block": "read",
"hits": 3,
"exit": 1,
"expect": {
"facts": []
}
},
{
"about": "Stopped by the person: the line stays on the reply.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "person"
},
"now": 1762790460000,
"expect": {
"line": "Stopped: by you"
}
},
{
"about": "The budget ran out.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "budget"
},
"now": 1762790460000,
"expect": {
"line": "Stopped: budget"
}
},
{
"about": "The step limit.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "steps"
},
"now": 1762790460000,
"expect": {
"line": "Stopped: step limit"
}
},
{
"about": "Stopped, no reason known.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000
},
"now": 1762790460000,
"expect": {
"line": "Stopped"
}
},
{
"about": "Failed, with the error.",
"show": "end",
"progress": {
"phase": "failed",
"since": 1762790400000,
"reason": "502 Bad Gateway"
},
"now": 1762790460000,
"expect": {
"line": "Failed: 502 Bad Gateway"
}
},
{
"about": "A reply that finished shows nothing.",
"show": "end",
"progress": null,
"now": 1762790460000,
"expect": {
"line": null
}
},
{
"about": "A phase that is not an end shows nothing on the reply.",
"show": "end",
"progress": {
"phase": "writing",
"since": 1762790400000
},
"now": 1762790460000,
"expect": {
"line": null
}
},
{
"about": "A plan change is not drawn as a call.",
"show": "drawn",
"block": "plan",
"expect": {
"drawn": false
}
},
{
"about": "Nor a hidden tool.",
"show": "drawn",
"block": "hidden",
"expect": {
"drawn": false
}
},
{
"about": "A command is.",
"show": "drawn",
"block": "shell",
"expect": {
"drawn": true
}
},
{
"about": "A tool nobody knows is the generic block.",
"show": "drawn",
"expect": {
"drawn": true
}
}
]
}
+337
View File
@@ -0,0 +1,337 @@
{
"about": "The effort levels a chat offers for a model, and what each sends (models/schema.json `levels`, spec 3.2.0). `op: levels` — `model` is model metadata (`thinking_switch`, `efforts` as given — never absent here, since an absent list is each project's own fallback — `effort`); the answer is `levels` (in offering order), `control` (`none`: one level, no effort control; `switch`: two levels, one of them off — a Thinking on/off switch; `slider`: anything else, a slider or a list) and `start` (the level a new conversation starts with: `effort` when it is one of the levels, else `medium` when offered, else the first effort, else `default`). `op: request` — `level` is the level asked for; the answer is what an OpenAI chat request body carries for it: `reasoning_effort` and `chat_template_kwargs` (only the keys set; `{}` when nothing). A level the model does not offer is read as the start level. LLeMbas: services/generation.py; CLI: provider/effort.ts.",
"cases": [
{
"about": "A model with the switch and one effort: a Thinking switch, on at its effort.",
"op": "levels",
"model": {
"thinking_switch": true,
"efforts": [
"medium"
]
},
"expect": {
"levels": [
"off",
"medium"
],
"control": "switch",
"start": "medium"
}
},
{
"about": "The same effort without the switch: one level, no control at all.",
"op": "levels",
"model": {
"efforts": [
"medium"
]
},
"expect": {
"levels": [
"medium"
],
"control": "none",
"start": "medium"
}
},
{
"about": "The switch and no efforts: off, or the model's own default — still a switch.",
"op": "levels",
"model": {
"thinking_switch": true,
"efforts": []
},
"expect": {
"levels": [
"off",
"default"
],
"control": "switch",
"start": "default"
}
},
{
"about": "Neither: one level, the model's own; nothing is shown and nothing sent.",
"op": "levels",
"model": {
"efforts": []
},
"expect": {
"levels": [
"default"
],
"control": "none",
"start": "default"
}
},
{
"about": "The switch and three efforts: a slider, off first; medium is where it starts when nothing is said.",
"op": "levels",
"model": {
"thinking_switch": true,
"efforts": [
"low",
"medium",
"high"
]
},
"expect": {
"levels": [
"off",
"low",
"medium",
"high"
],
"control": "slider",
"start": "medium"
}
},
{
"about": "Three efforts without the switch: a slider without off.",
"op": "levels",
"model": {
"efforts": [
"low",
"medium",
"high"
]
},
"expect": {
"levels": [
"low",
"medium",
"high"
],
"control": "slider",
"start": "medium"
}
},
{
"about": "The model's own start level, when it offers it.",
"op": "levels",
"model": {
"thinking_switch": true,
"efforts": [
"low",
"medium",
"high"
],
"effort": "high"
},
"expect": {
"levels": [
"off",
"low",
"medium",
"high"
],
"control": "slider",
"start": "high"
}
},
{
"about": "A start of off, with the switch: the conversation starts with thinking off.",
"op": "levels",
"model": {
"thinking_switch": true,
"efforts": [
"medium"
],
"effort": "off"
},
"expect": {
"levels": [
"off",
"medium"
],
"control": "switch",
"start": "off"
}
},
{
"about": "A start of off without the switch is not a level the model offers: the start rule applies (no medium: the first effort).",
"op": "levels",
"model": {
"efforts": [
"low",
"high"
],
"effort": "off"
},
"expect": {
"levels": [
"low",
"high"
],
"control": "slider",
"start": "low"
}
},
{
"about": "thinking_switch false is the same as absent.",
"op": "levels",
"model": {
"thinking_switch": false,
"efforts": [
"high",
"xhigh"
]
},
"expect": {
"levels": [
"high",
"xhigh"
],
"control": "slider",
"start": "high"
}
},
{
"about": "Two efforts and no switch: two levels, neither off — a slider, not a switch.",
"op": "levels",
"model": {
"efforts": [
"low",
"medium"
]
},
"expect": {
"levels": [
"low",
"medium"
],
"control": "slider",
"start": "medium"
}
},
{
"about": "off sends enable_thinking false and no effort anywhere.",
"op": "request",
"model": {
"thinking_switch": true,
"efforts": [
"medium"
]
},
"level": "off",
"expect": {
"chat_template_kwargs": {
"enable_thinking": false
}
}
},
{
"about": "An effort is sent where effort_style puts it (both, by default), and enable_thinking is not sent.",
"op": "request",
"model": {
"thinking_switch": true,
"efforts": [
"medium"
]
},
"level": "medium",
"expect": {
"reasoning_effort": "medium",
"chat_template_kwargs": {
"reasoning_effort": "medium"
}
}
},
{
"about": "effort_style top: the effort at the top level only.",
"op": "request",
"model": {
"thinking_switch": true,
"efforts": [
"low",
"medium"
],
"effort_style": "top"
},
"level": "low",
"expect": {
"reasoning_effort": "low"
}
},
{
"about": "effort_style kwargs: inside chat_template_kwargs only.",
"op": "request",
"model": {
"efforts": [
"low",
"medium"
],
"effort_style": "kwargs"
},
"level": "medium",
"expect": {
"chat_template_kwargs": {
"reasoning_effort": "medium"
}
}
},
{
"about": "default sends nothing: the model's own.",
"op": "request",
"model": {
"thinking_switch": true,
"efforts": []
},
"level": "default",
"expect": {}
},
{
"about": "off, effort_style top: still only enable_thinking, in chat_template_kwargs (the only place a template reads it).",
"op": "request",
"model": {
"thinking_switch": true,
"efforts": [
"medium"
],
"effort_style": "top"
},
"level": "off",
"expect": {
"chat_template_kwargs": {
"enable_thinking": false
}
}
},
{
"about": "off asked of a model without the switch is read as its start level.",
"op": "request",
"model": {
"efforts": [
"low",
"medium",
"high"
]
},
"level": "off",
"expect": {
"reasoning_effort": "medium",
"chat_template_kwargs": {
"reasoning_effort": "medium"
}
}
},
{
"about": "A level the model does not take is read as its start level too.",
"op": "request",
"model": {
"thinking_switch": true,
"efforts": [
"medium"
]
},
"level": "high",
"expect": {
"reasoning_effort": "medium",
"chat_template_kwargs": {
"reasoning_effort": "medium"
}
}
}
]
}
+123
View File
@@ -0,0 +1,123 @@
{
"about": "Spec 3.5.0 (acp.md *Monitor mode*, `_lembas/monitor`): the watch command on a device. `hash`: `exit` and `output` (the bytes as UTF-8) → the answer's `hash`. `judge`: a command line in the schedule's mode, with the default rules (and any extra global rules given), the project root /project and nothing named on disk, as conformance/permission.json judges it → `run` (the mode allows it without asking), or `{refused}` with `asks` (the mode would ask: scheduled.texts.monitor_asks) or `denied` (scheduled.texts.monitor_denied). The device's own; the server keeps only the hash.",
"cases": [
{
"about": "Exit 0 and a line of output.",
"kind": "hash",
"exit": 0,
"output": "ok\n",
"expect": "sha256:9427ae13c91f98a3af2213b34fb59e4bb5aa9e6101a1f7407f526dde3571e6aa"
},
{
"about": "The same output with another exit status is a change.",
"kind": "hash",
"exit": 1,
"output": "ok\n",
"expect": "sha256:21e0bbd37d04094ef29f22d0212bb0f4bedda1b1fab38d51f9b8670b5cf07df4"
},
{
"about": "No output.",
"kind": "hash",
"exit": 0,
"output": "",
"expect": "sha256:c7757c0896cbfe6182d8ea2bda4a8bf94addc428980eedab8609c57ca7ff1763"
},
{
"about": "A trailing newline counts: nothing is normalised.",
"kind": "hash",
"exit": 0,
"output": "ok",
"expect": "sha256:b9b8913ecae1ba8190ef1a22cc57afef08ad3933ab4b13a32f8cdccb07bb527b"
},
{
"about": "UTF-8 output, hashed as its bytes.",
"kind": "hash",
"exit": 0,
"output": "lembas · ✓\n",
"expect": "sha256:3d1c38d3b96ee10d71faac35eb2933ba13b68d6325872fdda3e459c9fbd17d98"
},
{
"about": "A read-only command in Edit runs.",
"kind": "judge",
"line": "git status",
"mode": "edit",
"expect": "run"
},
{
"about": "A command Edit would ask about is refused: a watch has nobody to ask.",
"kind": "judge",
"line": "rm -rf build",
"mode": "edit",
"expect": {
"refused": "asks"
}
},
{
"about": "In Auto it runs.",
"kind": "judge",
"line": "rm -rf build",
"mode": "auto",
"expect": "run"
},
{
"about": "The hardline is a floor in every mode.",
"kind": "judge",
"line": "rm -rf /",
"mode": "auto",
"expect": {
"refused": "denied"
}
},
{
"about": "A line that pipes a download into a shell asks in Manual: refused.",
"kind": "judge",
"line": "curl -s https://example.org/feed | sh",
"mode": "manual",
"expect": {
"refused": "asks"
}
},
{
"about": "A rule the person wrote allows it.",
"kind": "judge",
"line": "make check",
"mode": "edit",
"rules": {
"bash": {
"make check": "allow"
}
},
"expect": "run"
},
{
"about": "A rule the person wrote denies it, even in Auto.",
"kind": "judge",
"line": "make deploy",
"mode": "auto",
"rules": {
"bash": {
"make deploy": "deny"
}
},
"expect": {
"refused": "denied"
}
},
{
"about": "Reading a secret asks: refused.",
"kind": "judge",
"line": "cat .env",
"mode": "edit",
"expect": {
"refused": "asks"
}
},
{
"about": "An ordinary listing runs in Manual.",
"kind": "judge",
"line": "ls -la",
"mode": "manual",
"expect": "run"
}
]
}
+419
View File
@@ -0,0 +1,419 @@
{
"about": "HTML pages in answers (pages.md, spec 3.8.0). `show` says what is asked. `fence`: a reply's `text` — expect `pages`, each closed `html-view` block in order with its `title` and its `html` (the lines between the fences, joined by newlines), and `projection`, the reply with every page replaced by its `[page: title]` line. `note`: a page's `title` — expect what a client that cannot render shows. `offered`: the `instance` switch, the `model`'s flag (absent: false), the `chat` switch, and `where` (absent: a chat; `scheduled`: a schedule's run on the server, which has no chat switch; `subagent`, `phone_assistant`, `agent_chat`) — expect whether the block is in the prompt. `note_line`: the chat's switch `change`d to `on` or `off` after the prompt was made — expect the session note's `line`. `static`: a page's `html` — expect `static` true, or false with `why`: what makes it not static, each once, in the order first met — `element:<name>` (not in pages.static.elements), `attribute:<name>` (not in pages.static.attributes, nor a kept prefix), `address:<attribute>` (an address other than #fragment or an inline data: image of a listed type), `css:import`, `css:url` (a url() that is neither) — names in lower case. It says what the rule is; a client still rebuilds the document with a real parser (pages.md §6). LLeMbas: services/pages.py; CLI: src/prototype/fence.ts.",
"cases": [
{
"about": "A page with a title.",
"show": "fence",
"text": "Here are the sales.\n\n```html-view Monthly sales\n<!doctype html>\n<html><body><h1>Hi</h1></body></html>\n```\n\nThey rose.",
"expect": {
"pages": [
{
"title": "Monthly sales",
"html": "<!doctype html>\n<html><body><h1>Hi</h1></body></html>"
}
],
"projection": "Here are the sales.\n\n[page: Monthly sales]\n\nThey rose."
}
},
{
"about": "No title on the line: the page's own <title>.",
"show": "fence",
"text": "```html-view\n<title> Q3 results </title><p>x</p>\n```",
"expect": {
"pages": [
{
"title": "Q3 results",
"html": "<title> Q3 results </title><p>x</p>"
}
],
"projection": "[page: Q3 results]"
}
},
{
"about": "No title anywhere.",
"show": "fence",
"text": "```html-view\n<p>x</p>\n```",
"expect": {
"pages": [
{
"title": "Page",
"html": "<p>x</p>"
}
],
"projection": "[page: Page]"
}
},
{
"about": "The word is exact: html is a code block, and so is html-views.",
"show": "fence",
"text": "```html\n<p>x</p>\n```\n\n```html-views A\n<p>y</p>\n```",
"expect": {
"pages": [],
"projection": "```html\n<p>x</p>\n```\n\n```html-views A\n<p>y</p>\n```"
}
},
{
"about": "An unclosed fence is not a page.",
"show": "fence",
"text": "Look:\n\n```html-view Chart\n<svg>",
"expect": {
"pages": [],
"projection": "Look:\n\n```html-view Chart\n<svg>"
}
},
{
"about": "Three backticks inside a page of four: the inner line does not end it.",
"show": "fence",
"text": "````html-view Code sample\n<pre>\n```js\nlet a = `x`\n```\n</pre>\n````\nafter",
"expect": {
"pages": [
{
"title": "Code sample",
"html": "<pre>\n```js\nlet a = `x`\n```\n</pre>"
}
],
"projection": "[page: Code sample]\nafter"
}
},
{
"about": "A closing fence may be longer than the opening, not shorter.",
"show": "fence",
"text": "````html-view A\n<p>1</p>\n```\n<p>2</p>\n`````",
"expect": {
"pages": [
{
"title": "A",
"html": "<p>1</p>\n```\n<p>2</p>"
}
],
"projection": "[page: A]"
}
},
{
"about": "Tildes are a fence too; backticks do not close it.",
"show": "fence",
"text": "~~~html-view Tilde\n<p>x</p>\n```\n~~~",
"expect": {
"pages": [
{
"title": "Tilde",
"html": "<p>x</p>\n```"
}
],
"projection": "[page: Tilde]"
}
},
{
"about": "Two pages in one reply, and an ordinary code block between them left alone.",
"show": "fence",
"text": "```html-view One\n<p>1</p>\n```\n```js\nx()\n```\n ```html-view Two words \n<p>2</p>\n ```",
"expect": {
"pages": [
{
"title": "One",
"html": "<p>1</p>"
},
{
"title": "Two words",
"html": "<p>2</p>"
}
],
"projection": "[page: One]\n```js\nx()\n```\n[page: Two words]"
}
},
{
"about": "A page fence inside an ordinary code block is that block's text.",
"show": "fence",
"text": "````markdown\n```html-view Not one\n<p>x</p>\n```\n````",
"expect": {
"pages": [],
"projection": "````markdown\n```html-view Not one\n<p>x</p>\n```\n````"
}
},
{
"about": "A long title is cut.",
"show": "fence",
"text": "```html-view tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt\n<p>x</p>\n```",
"expect": {
"pages": [
{
"title": "tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt",
"html": "<p>x</p>"
}
],
"projection": "[page: tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt]"
}
},
{
"about": "The note a client that cannot render shows.",
"show": "note",
"title": "Monthly sales",
"expect": {
"note": "This answer has a page: Monthly sales"
}
},
{
"about": "All three on.",
"show": "offered",
"instance": true,
"model": true,
"chat": true,
"expect": {
"offered": true
}
},
{
"about": "The instance's switch off.",
"show": "offered",
"instance": false,
"model": true,
"chat": true,
"expect": {
"offered": false
}
},
{
"about": "The model cannot.",
"show": "offered",
"instance": true,
"model": false,
"chat": true,
"expect": {
"offered": false
}
},
{
"about": "The model says nothing: false.",
"show": "offered",
"instance": true,
"chat": true,
"expect": {
"offered": false
}
},
{
"about": "The chat's switch off.",
"show": "offered",
"instance": true,
"model": true,
"chat": false,
"expect": {
"offered": false
}
},
{
"about": "A scheduled run has no chat switch: the instance and the model decide.",
"show": "offered",
"instance": true,
"model": true,
"where": "scheduled",
"expect": {
"offered": true
}
},
{
"about": "A scheduled run on an instance with the switch off.",
"show": "offered",
"instance": false,
"model": true,
"where": "scheduled",
"expect": {
"offered": false
}
},
{
"about": "Never to a subagent.",
"show": "offered",
"instance": true,
"model": true,
"chat": true,
"where": "subagent",
"expect": {
"offered": false
}
},
{
"about": "Never in the phone assistant.",
"show": "offered",
"instance": true,
"model": true,
"chat": true,
"where": "phone_assistant",
"expect": {
"offered": false
}
},
{
"about": "Never in an agent chat (a device, a terminal).",
"show": "offered",
"instance": true,
"model": true,
"chat": true,
"where": "agent_chat",
"expect": {
"offered": false
}
},
{
"about": "A scheduled run on a linked computer is an agent chat: never.",
"show": "offered",
"instance": true,
"model": true,
"where": "agent_chat",
"scheduled": true,
"expect": {
"offered": false
}
},
{
"about": "Switched on mid-chat: the note carries the block.",
"show": "note_line",
"change": "on",
"pages_text": "- (the block)",
"expect": {
"line": "HTML pages are now on for this chat:\n- (the block)"
}
},
{
"about": "Switched off mid-chat.",
"show": "note_line",
"change": "off",
"expect": {
"line": "HTML pages are now off for this chat: write no more `html-view` blocks."
}
},
{
"about": "A static page: text, a table, a style element with the variables, inline SVG.",
"show": "static",
"html": "<!doctype html><html><head><title>Sales</title><style>body{color:var(--page-ink,#222);background:var(--page-bg,#fff)} td{border:1px solid var(--page-line,#ccc)}</style></head><body><h1>Sales</h1><table><tr><th scope=\"col\">Month</th><td colspan=\"2\">12</td></tr></table><svg viewBox=\"0 0 100 40\" role=\"img\" aria-label=\"Bars\"><rect x=\"0\" y=\"10\" width=\"20\" height=\"30\" fill=\"var(--page-accent,#06c)\"/><text x=\"10\" y=\"8\" text-anchor=\"middle\" font-size=\"6\">12</text></svg></body></html>",
"expect": {
"static": true
}
},
{
"about": "A link within the page and an inline picture are the two addresses there are.",
"show": "static",
"html": "<a href=\"#totals\">Totals</a><h2 id=\"totals\">Totals</h2><img alt=\"dot\" src=\"data:image/png;base64,iVBORw0KGgo=\">",
"expect": {
"static": true
}
},
{
"about": "A script.",
"show": "static",
"html": "<p>x</p><script>fetch('https://example.org/')</script>",
"expect": {
"static": false,
"why": [
"element:script"
]
}
},
{
"about": "An event handler.",
"show": "static",
"html": "<p onclick=\"go()\">x</p><svg onload=\"go()\"></svg>",
"expect": {
"static": false,
"why": [
"attribute:onclick",
"attribute:onload"
]
}
},
{
"about": "A link element — a dns-prefetch needs no script at all.",
"show": "static",
"html": "<link rel=\"dns-prefetch\" href=\"//example.org\"><p>x</p>",
"expect": {
"static": false,
"why": [
"element:link"
]
}
},
{
"about": "meta, base, frames, objects, media, canvas, forms.",
"show": "static",
"html": "<meta http-equiv=\"refresh\" content=\"0;url=https://example.org\"><base href=\"https://example.org/\"><iframe src=\"https://example.org\"></iframe><object data=\"x\"></object><embed src=\"x\"><video src=\"x\"></video><audio></audio><canvas></canvas><form action=\"https://example.org\"><input name=\"q\"><button>go</button></form>",
"expect": {
"static": false,
"why": [
"element:meta",
"element:base",
"element:iframe",
"element:object",
"element:embed",
"element:video",
"element:audio",
"element:canvas",
"element:form",
"element:input",
"element:button"
]
}
},
{
"about": "An address that leaves the page.",
"show": "static",
"html": "<a href=\"https://example.org/\">out</a><img src=\"https://example.org/p.png\" alt=\"\"><a href=\"page2.html\">next</a>",
"expect": {
"static": false,
"why": [
"address:href",
"address:src"
]
}
},
{
"about": "A javascript: address, a protocol-relative one, a data: address that is not a picture, an SVG picture.",
"show": "static",
"html": "<a href=\"JavaScript:go()\">x</a><a href=\"//example.org\">y</a><a href=\"data:text/html;base64,PGI+\">z</a><img alt=\"\" src=\"data:image/svg+xml;base64,PHN2Zz4=\">",
"expect": {
"static": false,
"why": [
"address:href",
"address:src"
]
}
},
{
"about": "CSS that would fetch: @import and url() to anywhere; url(#id) and an inline picture are fine.",
"show": "static",
"html": "<style>@import url(https://example.org/a.css); .a{background:url(https://example.org/b.png)} .b{fill:url(#grad)} .c{background:url(data:image/png;base64,iVBOR=)}</style><p style=\"background:url('//example.org/c.png')\">x</p>",
"expect": {
"static": false,
"why": [
"css:import",
"css:url"
]
}
},
{
"about": "Elements and attributes nobody listed: dropped, whatever they are.",
"show": "static",
"html": "<marquee>x</marquee><template><p>y</p></template><svg><foreignObject><p>z</p></foreignObject><use href=\"#a\"/></svg><p contenteditable=\"true\" data-n=\"1\" aria-hidden=\"true\">w</p>",
"expect": {
"static": false,
"why": [
"element:marquee",
"element:template",
"element:foreignobject",
"attribute:contenteditable"
]
}
},
{
"about": "An xlink:href is not a listed attribute; a use that points outside is an address.",
"show": "static",
"html": "<svg><use xlink:href=\"#a\"/><use href=\"https://example.org/s.svg#a\"/></svg>",
"expect": {
"static": false,
"why": [
"attribute:xlink:href",
"address:href"
]
}
}
]
}
+89
View File
@@ -0,0 +1,89 @@
{
"about": "Where an agent session works, as the model is told it and as its tools read a path (context.md §11, spec 3.2.0). `op: env` — `root` is the project root and `started` the directory the session was started in (both absolute); the answer is the environment block's lines about them, in order, from loop.json context.env — none naming an absolute path. `op: resolve` — `path` as a tool call gives it; the answer is the absolute path it means: relative paths against the project root, whatever `started` is, `.` and `..` by their text (filesystem.md, Paths); an absolute path as it is. LLeMbas: not run — a chat's paths are the server's tree's; CLI: prompt/assemble.ts, tool/tool.ts.",
"cases": [
{
"about": "Started at the root: the project's name and nothing else.",
"op": "env",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app",
"expect": [
"Project: app (paths are relative to its root)"
]
},
{
"about": "Started below the root: that directory, relative to the root.",
"op": "env",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app/packages/web",
"expect": [
"Project: app (paths are relative to its root)",
"Started in: packages/web (relative to the project root)"
]
},
{
"about": "A trailing slash changes nothing.",
"op": "env",
"root": "/srv/work/site/",
"started": "/srv/work/site",
"expect": [
"Project: site (paths are relative to its root)"
]
},
{
"about": "A relative path is resolved against the project root.",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app",
"path": "src/main.ts",
"expect": "/home/ada/src/app/src/main.ts"
},
{
"about": "…also when the session started below the root: one base for every relative path.",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app/packages/web",
"path": "src/main.ts",
"expect": "/home/ada/src/app/src/main.ts"
},
{
"about": "The directory the session started in is reached by its path from the root.",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app/packages/web",
"path": "packages/web/index.ts",
"expect": "/home/ada/src/app/packages/web/index.ts"
},
{
"about": "An absolute path is still accepted, as it is.",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app/packages/web",
"path": "/etc/hosts",
"expect": "/etc/hosts"
},
{
"about": ". is the root.",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app/packages/web",
"path": ".",
"expect": "/home/ada/src/app"
},
{
"about": ".. is resolved by its text (whether it may be reached is the permission rules' business).",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app",
"path": "../lib/x.ts",
"expect": "/home/ada/src/lib/x.ts"
},
{
"about": "./ and repeated slashes are resolved by their text.",
"op": "resolve",
"root": "/home/ada/src/app",
"started": "/home/ada/src/app",
"path": "./docs//guide.md",
"expect": "/home/ada/src/app/docs/guide.md"
}
]
}
+595
View File
@@ -0,0 +1,595 @@
{
"about": "Spec 3.6.0 (phone.md §2-§3): `check` — a phone_action call's arguments, and either the action the phone is sent (`action`: its own fields only, strings trimmed, `summary` the action's name when empty) or the call's refusal (`refused`, loop.json phone.texts); `result` — the phone's answer (`status`, `message`; `status` null is no answer in time) as the text the model is told. LLeMbas only: the CLI has no runner for this area.",
"cases": [
{
"about": "A known action, its fields only: a stray field is dropped and strings are trimmed.",
"kind": "check",
"args": {
"action": "alarm",
"summary": " Alarm at 7:00 on weekdays ",
"time": "07:00",
"days": [
"mon",
"tue",
"wed",
"thu",
"fri"
],
"label": " Work ",
"seconds": 60
},
"expect": {
"action": {
"action": "alarm",
"summary": "Alarm at 7:00 on weekdays",
"time": "07:00",
"days": [
"mon",
"tue",
"wed",
"thu",
"fri"
],
"label": "Work"
}
}
},
{
"about": "No summary: the action's name stands in.",
"kind": "check",
"args": {
"action": "torch",
"on": false
},
"expect": {
"action": {
"action": "torch",
"summary": "torch",
"on": false
}
}
},
{
"about": "An action that is not one.",
"kind": "check",
"args": {
"action": "call",
"summary": "Call mum",
"number": "+421 900 123 456"
},
"expect": {
"refused": "\"call\" is not an action. Use one of: alarm, timer, calendar_event, sms_draft, email_draft, dial, navigate, add_stop, search_nearby, stop_navigation, open_app, open_url, media, torch, settings_panel, automation_intent. Nothing was sent to the phone."
}
},
{
"about": "A required field missing.",
"kind": "check",
"args": {
"action": "timer",
"summary": "Tea"
},
"expect": {
"refused": "timer needs seconds. Nothing was sent to the phone."
}
},
{
"about": "Both of add_stop's missing: all of them, in order, in one sentence.",
"kind": "check",
"args": {
"action": "add_stop",
"summary": "Add a stop"
},
"expect": {
"refused": "add_stop needs stop and destination. Nothing was sent to the phone."
}
},
{
"about": "A group: an SMS draft needs a recipient or a text.",
"kind": "check",
"args": {
"action": "sms_draft",
"summary": "Text"
},
"expect": {
"refused": "sms_draft needs to or body. Nothing was sent to the phone."
}
},
{
"about": "A group met by one of its fields.",
"kind": "check",
"args": {
"action": "sms_draft",
"summary": "Text Jana",
"to": [
"Jana"
]
},
"expect": {
"action": {
"action": "sms_draft",
"summary": "Text Jana",
"to": [
"Jana"
]
}
}
},
{
"about": "An empty string is missing, whitespace included.",
"kind": "check",
"args": {
"action": "open_app",
"summary": "Open",
"app": " "
},
"expect": {
"refused": "open_app needs app. Nothing was sent to the phone."
}
},
{
"about": "A time out of range.",
"kind": "check",
"args": {
"action": "alarm",
"summary": "Alarm",
"time": "24:00"
},
"expect": {
"refused": "time is not a time as HH:MM (24-hour). Nothing was sent to the phone."
}
},
{
"about": "A timer of zero seconds.",
"kind": "check",
"args": {
"action": "timer",
"summary": "Timer",
"seconds": 0
},
"expect": {
"refused": "seconds is not a whole number of seconds from 1 to 86400. Nothing was sent to the phone."
}
},
{
"about": "A boolean is not a number of seconds.",
"kind": "check",
"args": {
"action": "timer",
"summary": "Timer",
"seconds": true
},
"expect": {
"refused": "seconds is not a whole number of seconds from 1 to 86400. Nothing was sent to the phone."
}
},
{
"about": "A calendar event with a date for a whole day.",
"kind": "check",
"args": {
"action": "calendar_event",
"summary": "Holiday",
"title": "Holiday",
"start": "2026-12-24",
"all_day": true
},
"expect": {
"action": {
"action": "calendar_event",
"summary": "Holiday",
"title": "Holiday",
"start": "2026-12-24",
"all_day": true
}
}
},
{
"about": "A start that is not a date.",
"kind": "check",
"args": {
"action": "calendar_event",
"summary": "Meet",
"title": "Meet",
"start": "tomorrow at 3"
},
"expect": {
"refused": "start is not a date and time as YYYY-MM-DDTHH:MM, or a date as YYYY-MM-DD for a whole day. Nothing was sent to the phone."
}
},
{
"about": "A number with too few digits.",
"kind": "check",
"args": {
"action": "dial",
"summary": "Dial",
"number": "12"
},
"expect": {
"refused": "number is not a phone number. Nothing was sent to the phone."
}
},
{
"about": "A number with letters in it.",
"kind": "check",
"args": {
"action": "dial",
"summary": "Dial",
"number": "0900 ABC"
},
"expect": {
"refused": "number is not a phone number. Nothing was sent to the phone."
}
},
{
"about": "A web address that is not http or https.",
"kind": "check",
"args": {
"action": "open_url",
"summary": "Open",
"url": "javascript:alert(1)"
},
"expect": {
"refused": "url is not an http or https address. Nothing was sent to the phone."
}
},
{
"about": "A web address in capitals is still one.",
"kind": "check",
"args": {
"action": "open_url",
"summary": "Open",
"url": "HTTPS://example.org/"
},
"expect": {
"action": {
"action": "open_url",
"summary": "Open",
"url": "HTTPS://example.org/"
}
}
},
{
"about": "A route: a destination, stops in order, a mode.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Drive home via the shop",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Shop",
"lat": 48.89,
"lon": 18.04
}
],
"mode": "drive"
},
"expect": {
"action": {
"action": "navigate",
"summary": "Drive home via the shop",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Shop",
"lat": 48.89,
"lon": 18.04
}
],
"mode": "drive"
}
}
},
{
"about": "A destination with coordinates out of range and nothing else is not a place.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Go",
"destination": {
"lat": 95,
"lon": 18
}
},
"expect": {
"refused": "destination is not a place: lat and lon together, or a query, or a name. Nothing was sent to the phone."
}
},
{
"about": "A stop that is not a place, inside the list.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Go",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Shop"
},
{}
]
},
"expect": {
"refused": "stops is not a list of places, each lat and lon together, or a query, or a name. Nothing was sent to the phone."
}
},
{
"about": "add_stop with its destination, as the person told it.",
"kind": "check",
"args": {
"action": "add_stop",
"summary": "Add the petrol station",
"stop": {
"query": "Fuel station, Bywater"
},
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
}
},
"expect": {
"action": {
"action": "add_stop",
"summary": "Add the petrol station",
"stop": {
"query": "Fuel station, Bywater"
},
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
}
}
}
},
{
"about": "A mode the schema does not have.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Go",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"mode": "fly"
},
"expect": {
"refused": "mode is not one of drive, walk, bike, transit. Nothing was sent to the phone."
}
},
{
"about": "search_nearby along the route.",
"kind": "check",
"args": {
"action": "search_nearby",
"summary": "Petrol on the way",
"query": "petrol station",
"near": "route"
},
"expect": {
"action": {
"action": "search_nearby",
"summary": "Petrol on the way",
"query": "petrol station",
"near": "route"
}
}
},
{
"about": "stop_navigation needs nothing.",
"kind": "check",
"args": {
"action": "stop_navigation",
"summary": "Stop the route"
},
"expect": {
"action": {
"action": "stop_navigation",
"summary": "Stop the route"
}
}
},
{
"about": "The checks run in the spec's order: time is reported before days.",
"kind": "check",
"args": {
"action": "alarm",
"summary": "Alarm",
"time": "7",
"days": [
"monday"
]
},
"expect": {
"refused": "time is not a time as HH:MM (24-hour). Nothing was sent to the phone."
}
},
{
"about": "A field another action reads is not checked here.",
"kind": "check",
"args": {
"action": "media",
"summary": "Pause",
"command": "pause",
"url": "nope"
},
"expect": {
"action": {
"action": "media",
"summary": "Pause",
"command": "pause"
}
}
},
{
"about": "An automation with its values.",
"kind": "check",
"args": {
"action": "automation_intent",
"summary": "Run Arrive home",
"task": "Arrive home",
"values": {
"lights": "on"
}
},
"expect": {
"action": {
"action": "automation_intent",
"summary": "Run Arrive home",
"task": "Arrive home",
"values": {
"lights": "on"
}
}
}
},
{
"about": "Values must be text.",
"kind": "check",
"args": {
"action": "automation_intent",
"summary": "Run",
"task": "x",
"values": {
"n": 1
}
},
"expect": {
"refused": "values is not named text values. Nothing was sent to the phone."
}
},
{
"about": "An email draft with a list of recipients.",
"kind": "check",
"args": {
"action": "email_draft",
"summary": "Email",
"to": [
"a@example.org"
],
"subject": "Hi"
},
"expect": {
"action": {
"action": "email_draft",
"summary": "Email",
"to": [
"a@example.org"
],
"subject": "Hi"
}
}
},
{
"about": "A recipient list holding an empty name.",
"kind": "check",
"args": {
"action": "email_draft",
"summary": "Email",
"to": [
"a@example.org",
""
],
"subject": "Hi"
},
"expect": {
"refused": "to is not a list of recipients. Nothing was sent to the phone."
}
},
{
"about": "torch: on must be a boolean.",
"kind": "check",
"args": {
"action": "torch",
"summary": "Torch",
"on": "yes"
},
"expect": {
"refused": "on is not true or false. Nothing was sent to the phone."
}
},
{
"about": "A panel the schema does not have.",
"kind": "check",
"args": {
"action": "settings_panel",
"summary": "Open",
"panel": "battery"
},
"expect": {
"refused": "panel is not one of wifi, bluetooth, internet, volume, nfc, location, do_not_disturb. Nothing was sent to the phone."
}
},
{
"about": "Done, with nothing said.",
"kind": "result",
"status": "done",
"message": "",
"expect": "Done on the phone."
},
{
"about": "Done, with what the phone said.",
"kind": "result",
"status": "done",
"message": "Alarm set for 07:00, weekdays.",
"expect": "Done on the phone.\n\nThe phone says: Alarm set for 07:00, weekdays."
},
{
"about": "Declined.",
"kind": "result",
"status": "declined",
"message": "",
"expect": "The person declined it on the phone: nothing was done. Do not try again unless they ask."
},
{
"about": "Declined, with the person's words.",
"kind": "result",
"status": "declined",
"message": "Not now.",
"expect": "The person declined it on the phone: nothing was done. Do not try again unless they ask.\n\nThe phone says: Not now."
},
{
"about": "Failed, with why.",
"kind": "result",
"status": "failed",
"message": "OsmAnd is not installed.",
"expect": "The phone could not do it: nothing was done.\n\nThe phone says: OsmAnd is not installed."
},
{
"about": "A status the phone does not know is failed.",
"kind": "result",
"status": "maybe",
"message": "?",
"expect": "The phone could not do it: nothing was done.\n\nThe phone says: ?"
},
{
"about": "A message is trimmed.",
"kind": "result",
"status": "done",
"message": " Torch on. \n",
"expect": "Done on the phone.\n\nThe phone says: Torch on."
},
{
"about": "No answer in time.",
"kind": "result",
"status": null,
"message": "",
"expect": "The phone did not answer in time: nothing was done."
},
{
"about": "A message is cut at message_max_chars.",
"kind": "result",
"status": "failed",
"message": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"expect": "The phone could not do it: nothing was done.\n\nThe phone says: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
]
}
+535
View File
@@ -0,0 +1,535 @@
{
"about": "The prefix (context.md §10, spec 3.1.0): one session's requests, in order — which system prompt each sends, which tools it offers, and the note on a user message. `start` is the session as it begins: `date`, `mode`, and what the prompt is made from that may change (`plan` as rendered, `memory`, `personality`, `files` — instruction texts by path or heading — `mcp` — instructions by server; each \"\" or {} for none), `could` (the requirements the session could ever meet: `plan` for any session that may enter plan mode, `display`, `page`, `forge`) and `met` (those met now besides plan, which is met in plan mode; default: all it could). `tools`: the names a case looks at; a tool's `requires` is the spec's. Steps: `user` (a user message: the request that carries it), `tool` (a tool step's request: no user message), `set` (something changes — any of the start's fields, or `met`; `by: model` when the model's own tool did it, whose result told the model: `plan` from plan_write, `mode` from plan_submit's approval, `memory` and `files` it changed itself; otherwise the person or the clock did), `call` (a call of `tool` now), `compact` (the summary is asked for: `{{transcript}}` and `{{previous_summary}}` empty — an earlier summary is already the first message), `wrapup` (the request after a step limit or a budget: the same prompt and tools, the wrap-up message as its last user message, no note; a call in its reply is not run) and `model` (the session moves to another model). A request answers `{system, tools, note}`: `system` numbers the system prompts the session has made, from 1, the same number being the same bytes; `tools` the case's tools it offers; `note` the note after the person's words, or null. `call` answers the tool's `unavailable` text, or null where it runs; `compact` answers the request's prompt, its tools and `ask`, the user message that follows every message as it was; `wrapup` answers like a request; `set` and `model` answer null; a value that became empty reads `context.note.empty`. `plan_dir` fills modes/plan.md. LLeMbas: services/context.py; CLI: session/prefix.ts, session/engine.ts.",
"cases": [
{
"about": "A date that changes during a session is a note on the next user message; the system prompt and the tools stay the same bytes.",
"start": {
"date": "2026-11-04",
"mode": "manual",
"could": [
"plan"
]
},
"tools": [
"read",
"plan_submit"
],
"steps": [
{
"op": "user"
},
{
"op": "tool"
},
{
"op": "user"
},
{
"op": "set",
"date": "2026-11-05"
},
{
"op": "tool"
},
{
"op": "user"
}
],
"expect": [
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-04.\n</session-note>"
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": null
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": null
},
null,
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": null
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
}
]
},
{
"about": "plan_submit is offered in every mode and answers its unavailable text outside plan mode; a mode the person chose is a note with the mode's text, one the approval set is not.",
"start": {
"date": "2026-11-05",
"mode": "manual",
"could": [
"plan"
]
},
"tools": [
"read",
"plan_write",
"plan_submit"
],
"steps": [
{
"op": "user"
},
{
"op": "call",
"tool": "plan_submit"
},
{
"op": "set",
"mode": "plan"
},
{
"op": "user"
},
{
"op": "call",
"tool": "plan_submit"
},
{
"op": "set",
"mode": "edit",
"by": "model"
},
{
"op": "tool"
},
{
"op": "user"
}
],
"expect": [
{
"system": 1,
"tools": [
"read",
"plan_write",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
"Not in plan mode: plan_submit is how a plan made in plan mode is put to the person for approval. Carry on with the work; keep the plan current with plan_update.",
null,
{
"system": 1,
"tools": [
"read",
"plan_write",
"plan_submit"
],
"note": "<session-note>\nThe permission mode is now plan:\nPermission mode: plan. You are planning, not implementing. Read, search and investigate as much as you need, but change nothing: no file but a plan under .agent/plans, no command that is not already allowed, nothing saved to the library.\n\nWrite the plan with plan_write, so that someone else could follow it: findings with file:line references, what will be true when it is done (objectives), and the work as phases of tasks in order, with the risks and how to verify it as the last phase. Ask with ask_user if a decision is the user's. When the plan is written, call plan_submit — that is how the user approves it, and after approval you carry on and implement it, keeping the plan current with plan_update.\n</session-note>"
},
null,
null,
{
"system": 1,
"tools": [
"read",
"plan_write",
"plan_submit"
],
"note": null
},
{
"system": 1,
"tools": [
"read",
"plan_write",
"plan_submit"
],
"note": null
}
]
},
{
"about": "The compaction request is the same prompt and tools, every message, then the compaction text with no transcript; after it the prompt is made again and the next user message says the date again.",
"start": {
"date": "2026-11-05",
"mode": "edit",
"could": [
"plan"
]
},
"tools": [
"read",
"plan_submit"
],
"steps": [
{
"op": "user"
},
{
"op": "tool"
},
{
"op": "compact"
},
{
"op": "user"
},
{
"op": "compact"
}
],
"expect": [
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": null
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"ask": "Summarise the conversation below so it can be carried forward after the earlier turns are dropped from your context. This is a working record, not a report for a reader.\n\nKeep, under these headings and in this order:\n\n## What we are doing\nThe goal, and where we have got to.\n\n## Decisions\nAnything settled, and why. A decision without its reason gets argued again.\n\n## Facts established\nNames, numbers, versions, file paths, commands, URLs and identifiers, copied exactly. Do not round them, paraphrase them or reconstruct one from memory — if it is not in the transcript, leave it out.\n\n## Files touched\nEach file read or changed that still matters, and what was done to it.\n\n## Open threads\nWhat is unfinished, and what was about to happen next.\n\nLeave out pleasantries, retracted ideas and anything already superseded. Do not answer the conversation: you are recording it. Write in the language of the conversation, and stay under 600 words."
},
{
"system": 2,
"tools": [
"read",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
{
"system": 2,
"tools": [
"read",
"plan_submit"
],
"ask": "Summarise the conversation below so it can be carried forward after the earlier turns are dropped from your context. This is a working record, not a report for a reader.\n\nKeep, under these headings and in this order:\n\n## What we are doing\nThe goal, and where we have got to.\n\n## Decisions\nAnything settled, and why. A decision without its reason gets argued again.\n\n## Facts established\nNames, numbers, versions, file paths, commands, URLs and identifiers, copied exactly. Do not round them, paraphrase them or reconstruct one from memory — if it is not in the transcript, leave it out.\n\n## Files touched\nEach file read or changed that still matters, and what was done to it.\n\n## Open threads\nWhat is unfinished, and what was about to happen next.\n\nLeave out pleasantries, retracted ideas and anything already superseded. Do not answer the conversation: you are recording it. Write in the language of the conversation, and stay under 600 words."
}
]
},
{
"about": "What the model changed itself is not said again; what the person changed is, once, in loop.json's order; an MCP server that connected later is said by its own instructions.",
"start": {
"date": "2026-11-05",
"mode": "manual",
"plan": "",
"memory": "Prefers tabs.",
"personality": "",
"files": {
"/p/AGENTS.md": "Build with make."
},
"mcp": {
"docs": "Search the docs first."
},
"could": [
"plan"
]
},
"tools": [
"read"
],
"steps": [
{
"op": "user"
},
{
"op": "set",
"by": "model",
"plan": "# Fix\n## p1 P (pending)\n[t1] [ ] a",
"memory": "Prefers tabs.\n§\nUses fish.",
"files": {
"/p/AGENTS.md": "Build with make; test with make test."
}
},
{
"op": "tool"
},
{
"op": "user"
},
{
"op": "set",
"plan": "",
"memory": "Uses fish.",
"personality": "Be brief.",
"files": {
"/p/AGENTS.md": "Build with make; test with make test.",
"/p/src/AGENTS.md": "Strict types."
},
"mcp": {
"docs": "Search the docs first.",
"tickets": "Name the ticket in every commit."
}
},
{
"op": "user"
},
{
"op": "set",
"files": {
"/p/AGENTS.md": "Build with make; test with make test."
}
},
{
"op": "user"
}
],
"expect": [
{
"system": 1,
"tools": [
"read"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
null,
{
"system": 1,
"tools": [
"read"
],
"note": null
},
{
"system": 1,
"tools": [
"read"
],
"note": null
},
null,
{
"system": 1,
"tools": [
"read"
],
"note": "<session-note>\nThe person changed the plan; it is now:\n(none)\n\nThe person changed what is remembered; it is now:\nUses fish.\n\n/p/src/AGENTS.md changed; it now reads:\nStrict types.\n\nThe person chose a different personality:\nBe brief.\n\nInstructions from an MCP server that connected since the session began:\n<server name=\"tickets\">\nName the ticket in every commit.\n</server>\n</session-note>"
},
null,
{
"system": 1,
"tools": [
"read"
],
"note": "<session-note>\n/p/src/AGENTS.md changed; it now reads:\n(none)\n</session-note>"
}
]
},
{
"about": "A move to another model makes the prompt again; the date said in the conversation still holds.",
"start": {
"date": "2026-11-05",
"mode": "auto",
"could": [
"plan"
]
},
"tools": [
"read"
],
"steps": [
{
"op": "user"
},
{
"op": "model"
},
{
"op": "user"
}
],
"expect": [
{
"system": 1,
"tools": [
"read"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
null,
{
"system": 2,
"tools": [
"read"
],
"note": null
}
]
},
{
"about": "A display the session could have is offered from the start and answers unavailable while there is none; one it never could have leaves show out.",
"start": {
"date": "2026-11-05",
"mode": "manual",
"could": [
"plan",
"display"
],
"met": []
},
"tools": [
"read",
"show"
],
"steps": [
{
"op": "user"
},
{
"op": "call",
"tool": "show"
},
{
"op": "set",
"met": [
"display"
]
},
{
"op": "call",
"tool": "show"
}
],
"expect": [
{
"system": 1,
"tools": [
"read",
"show"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
"Nothing can be shown now: this session has no screen to show a file on. Give the user the path instead.",
null,
null
]
},
{
"start": {
"date": "2026-11-05",
"mode": "manual",
"could": [
"plan"
]
},
"tools": [
"read",
"show"
],
"steps": [
{
"op": "user"
}
],
"expect": [
{
"system": 1,
"tools": [
"read"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
}
]
},
{
"about": "The wrap-up keeps the session's tool list and prompt, carries no note, and the next user message carries what changed meanwhile.",
"start": {
"date": "2026-11-05",
"mode": "edit",
"could": [
"plan"
]
},
"tools": [
"read",
"plan_submit"
],
"steps": [
{
"op": "user"
},
{
"op": "tool"
},
{
"op": "set",
"date": "2026-11-06"
},
{
"op": "wrapup"
},
{
"op": "user"
}
],
"expect": [
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-05.\n</session-note>"
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": null
},
null,
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": null
},
{
"system": 1,
"tools": [
"read",
"plan_submit"
],
"note": "<session-note>\nToday is 2026-11-06.\n</session-note>"
}
]
}
]
}
+346
View File
@@ -0,0 +1,346 @@
{
"about": "Progress (progress.md, spec 3.4.0): the text and the line every client draws for a progress object. `progress`: the object; `now`: the client's clock (Unix ms). Expect `text` — the phase's text from loop.json progress.texts, its fields filled (numbers written plainly: integers as they are, a rate with one decimal) — and `line` — `{{text}} · {{elapsed}}` with elapsed = now − since in whole seconds (5s, 1m 05s, 1h 02m), or the text alone for stopped and failed. retrying's `in` is counted down: in − floor((now − since) / 1000), never below 0. LLeMbas: services/progress.py; CLI: session/progress.ts.",
"cases": [
{
"about": "Queued, nothing more known.",
"progress": {
"phase": "queued",
"since": 1762790400000
},
"now": 1762790405000,
"expect": {
"text": "Queued",
"line": "Queued · 5s"
}
},
{
"about": "Queued behind two turns.",
"progress": {
"phase": "queued",
"since": 1762790400000,
"ahead": 2
},
"now": 1762790465000,
"expect": {
"text": "Queued: 2 ahead",
"line": "Queued: 2 ahead · 1m 05s"
}
},
{
"about": "A one-request server answering another request.",
"progress": {
"phase": "waiting_for_model",
"since": 1762790400000,
"model": "Qwen 27B",
"reason": "busy"
},
"now": 1762790412400,
"expect": {
"text": "Waiting for Qwen 27B: it serves one request at a time and is answering another",
"line": "Waiting for Qwen 27B: it serves one request at a time and is answering another · 12s"
}
},
{
"about": "Every slot taken.",
"progress": {
"phase": "waiting_for_model",
"since": 1762790400000,
"model": "coder",
"reason": "slots"
},
"now": 1762790401000,
"expect": {
"text": "Waiting for coder: all its slots are in use",
"line": "Waiting for coder: all its slots are in use · 1s"
}
},
{
"about": "Another model on the one-model server.",
"progress": {
"phase": "waiting_for_model",
"since": 1762790400000,
"model": "coder",
"reason": "group"
},
"now": 1762790400000,
"expect": {
"text": "Waiting for coder: its server holds another model now",
"line": "Waiting for coder: its server holds another model now · 0s"
}
},
{
"about": "Loading.",
"progress": {
"phase": "loading_model",
"since": 1762790400000,
"model": "Gemma 12B"
},
"now": 1762794125000,
"expect": {
"text": "Loading Gemma 12B",
"line": "Loading Gemma 12B · 1h 02m"
}
},
{
"about": "Reading the prompt: the percentage is floored.",
"progress": {
"phase": "reading_prompt",
"since": 1762790400000,
"done": 1999,
"total": 3000
},
"now": 1762790402000,
"expect": {
"text": "Reading the prompt: 1999 / 3000 tokens (66%)",
"line": "Reading the prompt: 1999 / 3000 tokens (66%) · 2s"
}
},
{
"about": "Reading the prompt with no counts from the server.",
"progress": {
"phase": "reading_prompt",
"since": 1762790400000
},
"now": 1762790402000,
"expect": {
"text": "Reading the prompt",
"line": "Reading the prompt · 2s"
}
},
{
"about": "Thinking.",
"progress": {
"phase": "thinking",
"since": 1762790400000
},
"now": 1762790459999,
"expect": {
"text": "Thinking",
"line": "Thinking · 59s"
}
},
{
"about": "Writing, the rate with one decimal.",
"progress": {
"phase": "writing",
"since": 1762790400000,
"rate": 12.46
},
"now": 1762790404000,
"expect": {
"text": "Writing: 12.5 tok/s",
"line": "Writing: 12.5 tok/s · 4s"
}
},
{
"about": "Writing before a rate is measured.",
"progress": {
"phase": "writing",
"since": 1762790400000
},
"now": 1762790400400,
"expect": {
"text": "Writing",
"line": "Writing · 0s"
}
},
{
"about": "A tool with what it does.",
"progress": {
"phase": "running_tool",
"since": 1762790400000,
"tool": "bash",
"what": "bun test"
},
"now": 1762790461000,
"expect": {
"text": "Running bash: bun test",
"line": "Running bash: bun test · 1m 01s"
}
},
{
"about": "A tool without a title.",
"progress": {
"phase": "running_tool",
"since": 1762790400000,
"tool": "recall"
},
"now": 1762790401000,
"expect": {
"text": "Running recall",
"line": "Running recall · 1s"
}
},
{
"about": "An approval, naming the tool.",
"progress": {
"phase": "waiting_for_person",
"since": 1762790400000,
"what": "approval",
"tool": "bash"
},
"now": 1762790430000,
"expect": {
"text": "Waiting for you: allow bash?",
"line": "Waiting for you: allow bash? · 30s"
}
},
{
"about": "An approval with no tool named.",
"progress": {
"phase": "waiting_for_person",
"since": 1762790400000,
"what": "approval"
},
"now": 1762790400000,
"expect": {
"text": "Waiting for you: an approval",
"line": "Waiting for you: an approval · 0s"
}
},
{
"about": "A question.",
"progress": {
"phase": "waiting_for_person",
"since": 1762790400000,
"what": "question"
},
"now": 1762790403000,
"expect": {
"text": "Waiting for you: a question",
"line": "Waiting for you: a question · 3s"
}
},
{
"about": "The plan.",
"progress": {
"phase": "waiting_for_person",
"since": 1762790400000,
"what": "plan"
},
"now": 1762790403000,
"expect": {
"text": "Waiting for you: the plan",
"line": "Waiting for you: the plan · 3s"
}
},
{
"about": "Subagents.",
"progress": {
"phase": "waiting_for_subagents",
"since": 1762790400000,
"running": 3
},
"now": 1762790490000,
"expect": {
"text": "Waiting for subagents: 3 running",
"line": "Waiting for subagents: 3 running · 1m 30s"
}
},
{
"about": "Compacting.",
"progress": {
"phase": "compacting",
"since": 1762790400000
},
"now": 1762790407000,
"expect": {
"text": "Compacting the conversation",
"line": "Compacting the conversation · 7s"
}
},
{
"about": "Retrying: `in` counts down from since.",
"progress": {
"phase": "retrying",
"since": 1762790400000,
"reason": "502 Bad Gateway",
"in": 10,
"attempt": 2
},
"now": 1762790403000,
"expect": {
"text": "Retrying in 7 s: 502 Bad Gateway",
"line": "Retrying in 7 s: 502 Bad Gateway · 3s"
}
},
{
"about": "Retrying: never below 0.",
"progress": {
"phase": "retrying",
"since": 1762790400000,
"reason": "overloaded",
"in": 2
},
"now": 1762790405000,
"expect": {
"text": "Retrying in 0 s: overloaded",
"line": "Retrying in 0 s: overloaded · 5s"
}
},
{
"about": "Stopped draws no elapsed time.",
"progress": {
"phase": "stopped",
"since": 1762790400000
},
"now": 1762790405000,
"expect": {
"text": "Stopped",
"line": "Stopped"
}
},
{
"about": "Stopped by the person.",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "person"
},
"now": 1762790405000,
"expect": {
"text": "Stopped: by you",
"line": "Stopped: by you"
}
},
{
"about": "Stopped at the step limit.",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "steps"
},
"now": 1762790400000,
"expect": {
"text": "Stopped: step limit",
"line": "Stopped: step limit"
}
},
{
"about": "Stopped when the budget ran out.",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "budget"
},
"now": 1762790400000,
"expect": {
"text": "Stopped: budget",
"line": "Stopped: budget"
}
},
{
"about": "Failed.",
"progress": {
"phase": "failed",
"since": 1762790400000,
"reason": "connection refused"
},
"now": 1762790405000,
"expect": {
"text": "Failed: connection refused",
"line": "Failed: connection refused"
}
}
]
}
-63
View File
@@ -1,63 +0,0 @@
{
"about": "A fenced block's info string read as a prototype (prompts/blocks/prototypes.md): `prototype-chat` and `prototype-page` with an optional title on the same line, and bare `prototype` as the inline kind; anything else is the code block it is (`null`). The title is the fence's, else the page's own <title>, whitespace collapsed, at most 80 characters. LLeMbas: services/prototypes.py parse_info and title_for; CLI: src/prototype/fence.ts.",
"cases": [
{
"info": "prototype-chat Monthly sales",
"code": "<p>hi</p>",
"expect": {
"kind": "chat",
"title": "Monthly sales"
}
},
{
"info": "prototype-page Bakery landing",
"code": "<!doctype html><title>Ignored</title>",
"expect": {
"kind": "page",
"title": "Bakery landing"
}
},
{
"info": "prototype",
"code": "<p>x</p>",
"expect": {
"kind": "chat",
"title": ""
}
},
{
"info": "PROTOTYPE-PAGE",
"code": "<html><head><title> From the\n page </title></head></html>",
"expect": {
"kind": "page",
"title": "From the page"
}
},
{
"info": "prototype-chat",
"code": "<title><b>Bold</b> title</title>",
"expect": {
"kind": "chat",
"title": "Bold title"
}
},
{
"info": "html",
"code": "<p>x</p>",
"expect": null
},
{
"info": "",
"code": "",
"expect": null
},
{
"info": "prototype-page A title that goes on and on and on and on and on and on and on and on and on and on and on",
"code": "",
"expect": {
"kind": "page",
"title": "A title that goes on and on and on and on and on and on and on and on and on and"
}
}
]
}
+27
View File
@@ -0,0 +1,27 @@
{
"about": "Spec 3.7.0: what a `python` call answers when it could not run, word for word (tools/python.json). `situation`: `no_page` — no page of this chat is open in the web or desktop app (the tool's `unavailable`); `no_answer` — a page is open and attached but did not answer the run request; `timeout` — the run began and passed the call's limit of `seconds` (texts.timeout, `{{seconds}}` filled). Three situations, three texts: never one for another. The server's alone (scope llembas).",
"cases": [
{
"about": "No page of this chat is open anywhere.",
"situation": "no_page",
"expect": {
"text": "Python cannot run now: no page of this chat is open. Python runs in the person's browser — ask them to open this chat in the LLeMbas web or desktop app and keep it open, then call python again."
}
},
{
"about": "A page is attached but does not answer.",
"situation": "no_answer",
"expect": {
"text": "Python did not run: a page of this chat is open, but it did not answer. It may still be loading Python, or be asleep in a background tab — ask the person to bring this chat to the front (or reload it), then call python again."
}
},
{
"about": "The run passed its time limit.",
"situation": "timeout",
"seconds": 30,
"expect": {
"text": "Python stopped: the run took longer than 30 seconds, and nothing it wrote was saved. Do less in one call, or split the work over several calls."
}
}
]
}
+323
View File
@@ -0,0 +1,323 @@
{
"about": "What a request sends back of the model's reasoning (context.md §8, spec 3.2.0). `messages` is the history a request is built from, in order: `role` user, assistant or tool; `content`; an assistant message's stored `reasoning` (absent: it came with none); a user message's `turn` — false for a delivery at a step boundary (a job's note, a team message, words added to a running turn), which does not start a turn; absent or true for one that does (the person's, or a machine message starting a turn of its own). The answer is the messages as the OpenAI chat dialect sends them — `role`, `content`, and `reasoning_content` on an assistant message after the last user message that started a turn, when its reasoning is not empty (tool calls and ids are left out of the cases: they are sent as always). The Anthropic dialect sends the same messages' thinking blocks. LLeMbas: services/llm/openai_client.py, services/generation.py; CLI: provider/openai-chat.ts, session/engine.ts.",
"cases": [
{
"about": "One turn, three steps: every reply of the turn carries its reasoning back.",
"messages": [
{
"role": "user",
"content": "Fix the failing test."
},
{
"role": "assistant",
"content": "",
"reasoning": "The test name points at the parser."
},
{
"role": "tool",
"content": "[#0001 src/parse.ts lines 1-40 of 40 sha 1c9e04ab]\n…"
},
{
"role": "assistant",
"content": "",
"reasoning": "Line 12 drops the last token."
},
{
"role": "tool",
"content": "[#0002 src/parse.ts sha 7d0a91c3]\n@@ -12 +12 @@"
}
],
"expect": [
{
"role": "user",
"content": "Fix the failing test."
},
{
"role": "assistant",
"content": "",
"reasoning_content": "The test name points at the parser."
},
{
"role": "tool",
"content": "[#0001 src/parse.ts lines 1-40 of 40 sha 1c9e04ab]\n…"
},
{
"role": "assistant",
"content": "",
"reasoning_content": "Line 12 drops the last token."
},
{
"role": "tool",
"content": "[#0002 src/parse.ts sha 7d0a91c3]\n@@ -12 +12 @@"
}
]
},
{
"about": "A second turn: the first turn's replies go without their reasoning, the current one's with it.",
"messages": [
{
"role": "user",
"content": "Where is the config loaded?"
},
{
"role": "assistant",
"content": "",
"reasoning": "Search for load."
},
{
"role": "tool",
"content": "[#0001] src/config/load.ts:40"
},
{
"role": "assistant",
"content": "In src/config/load.ts.",
"reasoning": "Found it at line 40."
},
{
"role": "user",
"content": "And who calls it?"
},
{
"role": "assistant",
"content": "",
"reasoning": "Grep for loadConfig."
},
{
"role": "tool",
"content": "[#0002] src/app.ts:120"
}
],
"expect": [
{
"role": "user",
"content": "Where is the config loaded?"
},
{
"role": "assistant",
"content": ""
},
{
"role": "tool",
"content": "[#0001] src/config/load.ts:40"
},
{
"role": "assistant",
"content": "In src/config/load.ts."
},
{
"role": "user",
"content": "And who calls it?"
},
{
"role": "assistant",
"content": "",
"reasoning_content": "Grep for loadConfig."
},
{
"role": "tool",
"content": "[#0002] src/app.ts:120"
}
]
},
{
"about": "A job's note delivered at a step boundary does not start a turn: the turn's earlier replies keep their reasoning.",
"messages": [
{
"role": "user",
"content": "Run the tests in the background and fix the lint."
},
{
"role": "assistant",
"content": "",
"reasoning": "Start the tests, then lint."
},
{
"role": "tool",
"content": "[#0001] job1 started"
},
{
"role": "user",
"content": "[A background job you started has finished:]\njob1 (npm test) exited with 0 after 5s.",
"turn": false
},
{
"role": "assistant",
"content": "",
"reasoning": "Tests pass; now the lint."
},
{
"role": "tool",
"content": "[#0002] 0 problems"
}
],
"expect": [
{
"role": "user",
"content": "Run the tests in the background and fix the lint."
},
{
"role": "assistant",
"content": "",
"reasoning_content": "Start the tests, then lint."
},
{
"role": "tool",
"content": "[#0001] job1 started"
},
{
"role": "user",
"content": "[A background job you started has finished:]\njob1 (npm test) exited with 0 after 5s."
},
{
"role": "assistant",
"content": "",
"reasoning_content": "Tests pass; now the lint."
},
{
"role": "tool",
"content": "[#0002] 0 problems"
}
]
},
{
"about": "A machine message that starts a turn of its own (a team report to an idle lead) does: the replies before it go without.",
"messages": [
{
"role": "user",
"content": "Split the work."
},
{
"role": "assistant",
"content": "Started alice.",
"reasoning": "Add one member."
},
{
"role": "user",
"content": "[Team report from alice to lead:]\nDone.",
"turn": true
},
{
"role": "assistant",
"content": "",
"reasoning": "Review alice's change."
},
{
"role": "tool",
"content": "[#0001 src/a.ts lines 1-10 of 10 sha 52b6e3a0]\n…"
}
],
"expect": [
{
"role": "user",
"content": "Split the work."
},
{
"role": "assistant",
"content": "Started alice."
},
{
"role": "user",
"content": "[Team report from alice to lead:]\nDone."
},
{
"role": "assistant",
"content": "",
"reasoning_content": "Review alice's change."
},
{
"role": "tool",
"content": "[#0001 src/a.ts lines 1-10 of 10 sha 52b6e3a0]\n…"
}
]
},
{
"about": "A reply that came with no reasoning, or an empty one, carries no field.",
"messages": [
{
"role": "user",
"content": "Hello"
},
{
"role": "assistant",
"content": "",
"reasoning": "Greet."
},
{
"role": "tool",
"content": "[#0001] ok"
},
{
"role": "assistant",
"content": "Hi."
},
{
"role": "user",
"content": "Again"
},
{
"role": "assistant",
"content": "Hi again.",
"reasoning": ""
}
],
"expect": [
{
"role": "user",
"content": "Hello"
},
{
"role": "assistant",
"content": ""
},
{
"role": "tool",
"content": "[#0001] ok"
},
{
"role": "assistant",
"content": "Hi."
},
{
"role": "user",
"content": "Again"
},
{
"role": "assistant",
"content": "Hi again."
}
]
},
{
"about": "The last message the person wrote starts the turn even when nothing has answered it yet: every earlier reply goes without.",
"messages": [
{
"role": "user",
"content": "One"
},
{
"role": "assistant",
"content": "Done.",
"reasoning": "Easy."
},
{
"role": "user",
"content": "Two"
}
],
"expect": [
{
"role": "user",
"content": "One"
},
{
"role": "assistant",
"content": "Done."
},
{
"role": "user",
"content": "Two"
}
]
}
]
}
+331
View File
@@ -0,0 +1,331 @@
{
"about": "Reports (reports.md, spec 3.8.0). `show` says what is asked. `offered`: a `session` (`scheduled` — opened by a schedule for its run; `chat`; `agent`), the schedule's `notify` (absent: the default), the `turn` (`run` — the schedule's; `person` — somebody writing into the session) and `subagent` — expect `tool`: `offered`, `absent` (not in the list), or `unavailable` with the `text` a call answers. `instruction`: `notify` and the person's `condition` — expect `text`, the instruction placed in the run's prompt (loop.json scheduled.notify.texts; \"\" for never). `result`: the number of report_write `calls` made so far in the run, this one included — expect the tool's `text`. `run`: the schedule's `notify` and `title`, the report_write `calls` of the run in order, and its final `answer` — expect `report` (title, body, summary, importance) or null, and `note`, the history line. The sentinel of 3.5.0 is read as nothing to tell. LLeMbas: services/schedule/reports.py; CLI: src/acp/scheduled.ts.",
"cases": [
{
"about": "A schedule's run, notify always: offered.",
"show": "offered",
"session": "scheduled",
"notify": "always",
"turn": "run",
"expect": {
"tool": "offered"
}
},
{
"about": "Notify when: offered.",
"show": "offered",
"session": "scheduled",
"notify": "when",
"turn": "run",
"expect": {
"tool": "offered"
}
},
{
"about": "A schedule that says nothing is `when`.",
"show": "offered",
"session": "scheduled",
"turn": "run",
"expect": {
"tool": "offered"
}
},
{
"about": "Notify never: not in the list at all.",
"show": "offered",
"session": "scheduled",
"notify": "never",
"turn": "run",
"expect": {
"tool": "absent"
}
},
{
"about": "The person writes into a run's session afterwards: in the list (a session's list does not change), and it answers its unavailable text.",
"show": "offered",
"session": "scheduled",
"notify": "always",
"turn": "person",
"expect": {
"tool": "unavailable",
"text": "This is not a scheduled run: report_write files the report of a schedule's run, and nobody scheduled this turn. Answer the person here instead."
}
},
{
"about": "A chat: not in the list.",
"show": "offered",
"session": "chat",
"turn": "person",
"expect": {
"tool": "absent"
}
},
{
"about": "An agent chat on a device: not in the list.",
"show": "offered",
"session": "agent",
"turn": "person",
"expect": {
"tool": "absent"
}
},
{
"about": "A subagent of a run: never — the run's own agent files the report.",
"show": "offered",
"session": "scheduled",
"notify": "always",
"turn": "run",
"subagent": true,
"expect": {
"tool": "absent"
}
},
{
"about": "Every run.",
"show": "instruction",
"notify": "always",
"expect": {
"text": "Reporting: when the work is done, file a report with report_write — every run, also when you found nothing and when nothing matters; then say so in it, briefly. Then end with one short line for this run's history."
}
},
{
"about": "When, with the person's own words: trimmed, one line, its closing full stop dropped.",
"show": "instruction",
"notify": "when",
"condition": " a price dropped below 20 euros,\n or the page is gone. ",
"expect": {
"text": "Reporting: file a report with report_write only if this holds: a price dropped below 20 euros, or the page is gone. If it does not hold, file no report and end with one short line saying why not. If it holds, file the report when the work is done, then end with one short line for this run's history."
}
},
{
"about": "When, with no words of their own: the default condition.",
"show": "instruction",
"notify": "when",
"condition": " ",
"expect": {
"text": "Reporting: file a report with report_write only if this holds: something needs my attention. If it does not hold, file no report and end with one short line saying why not. If it holds, file the report when the work is done, then end with one short line for this run's history."
}
},
{
"about": "A schedule that says nothing: when, with the default condition.",
"show": "instruction",
"expect": {
"text": "Reporting: file a report with report_write only if this holds: something needs my attention. If it does not hold, file no report and end with one short line saying why not. If it holds, file the report when the work is done, then end with one short line for this run's history."
}
},
{
"about": "Never: nothing is said about reports.",
"show": "instruction",
"notify": "never",
"expect": {
"text": ""
}
},
{
"about": "A word nobody knows is the default, never `always`.",
"show": "instruction",
"notify": "sometimes",
"expect": {
"text": "Reporting: file a report with report_write only if this holds: something needs my attention. If it does not hold, file no report and end with one short line saying why not. If it holds, file the report when the work is done, then end with one short line for this run's history."
}
},
{
"about": "The first report of a run.",
"show": "result",
"calls": 1,
"expect": {
"text": "The report is filed. End your reply now with one short line for this run's history; do not repeat the report."
}
},
{
"about": "A second one replaces it.",
"show": "result",
"calls": 2,
"expect": {
"text": "The report is replaced by this one: a run files one report. End your reply now with one short line for this run's history; do not repeat the report."
}
},
{
"about": "A report was written: it is the run's, and the last line of the answer is the history line.",
"show": "run",
"notify": "when",
"title": "Disk watch",
"calls": [
{
"title": "Disk almost full",
"body": "## What\n\n`/var` is at 94%.",
"summary": "The log partition is at 94% and grows 2% a day.",
"importance": "high"
}
],
"answer": "Checked the disks.\n\nFiled a report: /var is almost full.",
"expect": {
"report": {
"title": "Disk almost full",
"body": "## What\n\n`/var` is at 94%.",
"summary": "The log partition is at 94% and grows 2% a day.",
"importance": "high"
},
"note": "Checked the disks."
}
},
{
"about": "Importance left out is normal.",
"show": "run",
"notify": "always",
"title": "Disk watch",
"calls": [
{
"title": "Disk fine again",
"body": "Rotated the logs; 41% now.",
"summary": "Logs rotated, 41% used."
}
],
"answer": "Logs rotated; report filed.",
"expect": {
"report": {
"title": "Disk fine again",
"body": "Rotated the logs; 41% now.",
"summary": "Logs rotated, 41% used.",
"importance": "normal"
},
"note": "Logs rotated; report filed."
}
},
{
"about": "One report per run: the second call replaces the first.",
"show": "run",
"notify": "when",
"title": "Disk watch",
"calls": [
{
"title": "Disk almost full",
"body": "## What\n\n`/var` is at 94%.",
"summary": "The log partition is at 94% and grows 2% a day.",
"importance": "high"
},
{
"title": "Disk fine again",
"body": "Rotated the logs; 41% now.",
"summary": "Logs rotated, 41% used."
}
],
"answer": "Done.",
"expect": {
"report": {
"title": "Disk fine again",
"body": "Rotated the logs; 41% now.",
"summary": "Logs rotated, 41% used.",
"importance": "normal"
},
"note": "Done."
}
},
{
"about": "When, and the condition did not hold: no report; the model's line says why.",
"show": "run",
"notify": "when",
"title": "Disk watch",
"calls": [],
"answer": "\nNothing needs attention: every disk is under 60%.\n",
"expect": {
"report": null,
"note": "Nothing needs attention: every disk is under 60%."
}
},
{
"about": "Every run, and the model wrote no report: the answer is filed as one — the schedule's title, the first paragraph as the summary.",
"show": "run",
"notify": "always",
"title": "Disk watch",
"calls": [],
"answer": "**All disks** are under 60%.\nNothing to do.\n\n| disk | used |\n|---|---|\n| /var | 41% |",
"expect": {
"report": {
"title": "Disk watch",
"body": "**All disks** are under 60%.\nNothing to do.\n\n| disk | used |\n|---|---|\n| /var | 41% |",
"summary": "**All disks** are under 60%. Nothing to do.",
"importance": "normal"
},
"note": "**All disks** are under 60%."
}
},
{
"about": "Every run, an empty answer: nothing to file.",
"show": "run",
"notify": "always",
"title": "Disk watch",
"calls": [],
"answer": " \n",
"expect": {
"report": null,
"note": "The run ended without a reply."
}
},
{
"about": "Never: no report, whatever was answered.",
"show": "run",
"notify": "never",
"title": "Disk watch",
"calls": [],
"answer": "All quiet.",
"expect": {
"report": null,
"note": "All quiet."
}
},
{
"about": "The retired sentinel alone, under every run: no report.",
"show": "run",
"notify": "always",
"title": "Disk watch",
"calls": [],
"answer": "[SILENT]",
"expect": {
"report": null,
"note": "The run ended without a reply."
}
},
{
"about": "The sentinel on the last line, under when: no report, and the line is not the note.",
"show": "run",
"notify": "when",
"title": "Disk watch",
"calls": [],
"answer": "Nothing new since yesterday.\n[silent].",
"expect": {
"report": null,
"note": "Nothing new since yesterday."
}
},
{
"about": "The sentinel on the first line under every run: taken out, and what is left is filed.",
"show": "run",
"notify": "always",
"title": "Disk watch",
"calls": [],
"answer": "[SILENT]\nChecked the feed: nothing.",
"expect": {
"report": {
"title": "Disk watch",
"body": "Checked the feed: nothing.",
"summary": "Checked the feed: nothing.",
"importance": "normal"
},
"note": "Checked the feed: nothing."
}
},
{
"about": "A long closing line is cut for the history.",
"show": "run",
"notify": "when",
"title": "Disk watch",
"calls": [],
"answer": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"expect": {
"report": null,
"note": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…"
}
}
]
}
+443
View File
@@ -0,0 +1,443 @@
{
"about": "Which permission rule decides (permission/rules.md, spec 3.8.0). The rules by layer: `defaults` true — permission/defaults.json as the `default` layer; `user` and `project` — a configuration's permission map (a key's value an action, or a map of pattern → action, read in the order written); `made` — rules made during the session, in order, each `by` an `always` answer or a `menu`. With `request` (`permission`, `pattern`: what one call asks for): expect the action that decides, or null where no rule matches. With `set` (a rule a person makes now, by a menu): expect `result` — `unchanged` (the action is already in force), `refused` with the rule in its way as `by`, or `made` with `still`, the stricter narrower rules that still apply, in the order read. The same answers for a rule typed into a file as for one a menu wrote. LLeMbas: security/permission rules; CLI: src/permission/evaluate.ts.",
"cases": [
{
"about": "The defaults alone: a file is read, a .env asks.",
"defaults": true,
"request": {
"permission": "read",
"pattern": "src/app.ts"
},
"expect": "allow"
},
{
"about": "The same, for another call.",
"defaults": true,
"request": {
"permission": "read",
"pattern": "config/.env"
},
"expect": "ask"
},
{
"about": "A project says read: allow. A broader rule made later does not unlock the narrower ask: .env still asks.",
"defaults": true,
"project": {
"read": "allow"
},
"request": {
"permission": "read",
"pattern": ".env"
},
"expect": "ask"
},
{
"about": "…and everything the broad default decided is as the project says.",
"defaults": true,
"project": {
"read": "allow"
},
"request": {
"permission": "read",
"pattern": "notes.txt"
},
"expect": "allow"
},
{
"about": "The same rule set in a menu, in the session it was made in.",
"defaults": true,
"made": [
{
"permission": "read",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": ".env.local"
},
"expect": "ask"
},
{
"about": "The project names the narrow thing itself: allowed.",
"defaults": true,
"project": {
"read": {
"*.env": "allow"
}
},
"request": {
"permission": "read",
"pattern": ".env"
},
"expect": "allow"
},
{
"about": "The broadest rule there is, made in a menu: .env still asks.",
"defaults": true,
"made": [
{
"permission": "*",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": ".env"
},
"expect": "ask"
},
{
"about": "web_fetch: allow in a project leaves private addresses asking.",
"defaults": true,
"project": {
"web_fetch": "allow"
},
"request": {
"permission": "web_fetch",
"pattern": "private:http://127.0.0.1:8080/admin"
},
"expect": "ask"
},
{
"about": "The same, for another call.",
"defaults": true,
"project": {
"web_fetch": "allow"
},
"request": {
"permission": "web_fetch",
"pattern": "https://example.org/"
},
"expect": "allow"
},
{
"about": "The person's own config denies rm; `bash allow` made in a menu does not undo it.",
"defaults": true,
"user": {
"bash": {
"rm *": "deny"
}
},
"made": [
{
"permission": "bash",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "bash",
"pattern": "rm -rf build"
},
"expect": "deny"
},
{
"about": "…and allows what only the broad default asked about.",
"defaults": true,
"user": {
"bash": {
"rm *": "deny"
}
},
"made": [
{
"permission": "bash",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "bash",
"pattern": "make all"
},
"expect": "allow"
},
{
"about": "The same from a project's file (the next start, after the menu saved it).",
"defaults": true,
"user": {
"bash": {
"rm *": "deny"
}
},
"project": {
"bash": "allow"
},
"request": {
"permission": "bash",
"pattern": "rm -rf build"
},
"expect": "deny"
},
{
"about": "The person's own `git push *`: ask stands against a project's bash: allow.",
"defaults": true,
"user": {
"bash": {
"git push *": "ask"
}
},
"project": {
"bash": "allow"
},
"request": {
"permission": "bash",
"pattern": "git push origin main"
},
"expect": "ask"
},
{
"about": "The person's own answer is a floor of any breadth: their bash: ask stands against a project's narrower allow.",
"defaults": true,
"user": {
"bash": "ask"
},
"project": {
"bash": {
"make *": "allow"
}
},
"request": {
"permission": "bash",
"pattern": "make all"
},
"expect": "ask"
},
{
"about": "The person's own file is read last-match-wins, as it always was: their broad allow after the defaults does unlock .env — it is theirs to say.",
"defaults": true,
"user": {
"read": "allow"
},
"request": {
"permission": "read",
"pattern": ".env"
},
"expect": "allow"
},
{
"about": "Within a project's file too, a narrower stricter line keeps winning over a broader one written after it.",
"project": {
"bash": {
"git push *": "ask",
"*": "allow"
}
},
"request": {
"permission": "bash",
"pattern": "git push origin main"
},
"expect": "ask"
},
{
"about": "A project's narrow allow after its own broad deny is an exception it wrote: allowed.",
"project": {
"bash": {
"*": "deny",
"git status": "allow"
}
},
"request": {
"permission": "bash",
"pattern": "git status"
},
"expect": "allow"
},
{
"about": "An \"always\" answer never undoes a written deny, of any breadth.",
"project": {
"bash": {
"*": "deny"
}
},
"made": [
{
"permission": "bash",
"pattern": "git status",
"action": "allow",
"by": "always"
}
],
"request": {
"permission": "bash",
"pattern": "git status"
},
"expect": "deny"
},
{
"about": "An \"always\" answer for `git *` leaves the narrower `git push --force *`: deny.",
"user": {
"bash": {
"git push --force *": "deny"
}
},
"made": [
{
"permission": "bash",
"pattern": "git *",
"action": "allow",
"by": "always"
}
],
"request": {
"permission": "bash",
"pattern": "git push --force origin main"
},
"expect": "deny"
},
{
"about": "A stricter rule made later always decides.",
"defaults": true,
"made": [
{
"permission": "read",
"pattern": "*",
"action": "deny",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": "src/app.ts"
},
"expect": "deny"
},
{
"about": "No rule matches: none decides (the class and the mode do).",
"user": {
"bash": {
"ls *": "allow"
}
},
"request": {
"permission": "edit",
"pattern": "a.txt"
},
"expect": null
},
{
"about": "Choosing the action already in force changes nothing.",
"defaults": true,
"set": {
"permission": "read",
"pattern": "*",
"action": "allow"
},
"expect": {
"result": "unchanged"
}
},
{
"about": "A rule that makes something stricter is made; nothing stricter is left standing.",
"defaults": true,
"set": {
"permission": "read",
"pattern": "*",
"action": "ask"
},
"expect": {
"result": "made",
"still": []
}
},
{
"about": "A broad allow is made, and says which stricter rules still apply.",
"defaults": true,
"made": [
{
"permission": "web_fetch",
"pattern": "*",
"action": "ask",
"by": "menu"
}
],
"set": {
"permission": "web_fetch",
"pattern": "*",
"action": "allow"
},
"expect": {
"result": "made",
"still": [
{
"permission": "web_fetch",
"pattern": "private:*",
"action": "ask"
}
]
}
},
{
"about": "The person's own rule, loosened where it stands: refused, naming it.",
"user": {
"bash": {
"git push *": "ask"
}
},
"set": {
"permission": "bash",
"pattern": "git push *",
"action": "allow"
},
"expect": {
"result": "refused",
"by": {
"permission": "bash",
"pattern": "git push *",
"action": "ask"
}
}
},
{
"about": "A narrower allow under a written deny: refused — the deny takes it in whole.",
"user": {
"bash": {
"rm *": "deny"
}
},
"set": {
"permission": "bash",
"pattern": "rm -rf build",
"action": "allow"
},
"expect": {
"result": "refused",
"by": {
"permission": "bash",
"pattern": "rm *",
"action": "deny"
}
}
},
{
"about": "A broader allow over the person's narrower deny is made — and the deny still applies.",
"user": {
"bash": {
"rm *": "deny"
}
},
"set": {
"permission": "bash",
"pattern": "*",
"action": "allow"
},
"expect": {
"result": "made",
"still": [
{
"permission": "bash",
"pattern": "rm *",
"action": "deny"
}
]
}
}
]
}
+145
View File
@@ -0,0 +1,145 @@
{
"about": "Spec 3.5.0 (acp.md *Scheduled work on a linked computer*): what a device makes of a scheduled turn. `accept`: the device's Accept scheduled work (remote.scheduled; false means remote work is off as well, the same refusal); `mode`: the schedule's (absent: none chosen); `max_mode`: remote.max_mode; `approval_wait_s`: the schedule's wait (absent: none). → `{mode, wait_s}` — the session's mode and how long an approval waits — or `{refused}` with the `data.reason` of the -32602 (`scheduled_off`, `plan`), whose message is loop.json scheduled.texts.off / .plan. Written from the rules; the device's other refusals (folder, trust) are the agent chat's.",
"cases": [
{
"about": "Off by default: refused, whatever else is asked.",
"accept": false,
"mode": "edit",
"max_mode": "edit",
"expect": {
"refused": "scheduled_off"
}
},
{
"about": "No mode chosen: Edit.",
"accept": true,
"max_mode": "edit",
"expect": {
"mode": "edit",
"wait_s": 1800
}
},
{
"about": "No mode chosen, the device allows Auto: still Edit — Auto only when the schedule says so.",
"accept": true,
"max_mode": "auto",
"expect": {
"mode": "edit",
"wait_s": 1800
}
},
{
"about": "Auto chosen and allowed.",
"accept": true,
"mode": "auto",
"max_mode": "auto",
"expect": {
"mode": "auto",
"wait_s": 1800
}
},
{
"about": "Auto chosen, the device allows Edit at most: lowered.",
"accept": true,
"mode": "auto",
"max_mode": "edit",
"expect": {
"mode": "edit",
"wait_s": 1800
}
},
{
"about": "Edit chosen, the device allows Manual at most: lowered.",
"accept": true,
"mode": "edit",
"max_mode": "manual",
"expect": {
"mode": "manual",
"wait_s": 1800
}
},
{
"about": "Manual chosen.",
"accept": true,
"mode": "manual",
"max_mode": "auto",
"expect": {
"mode": "manual",
"wait_s": 1800
}
},
{
"about": "Plan is refused: nobody is there to approve a plan.",
"accept": true,
"mode": "plan",
"max_mode": "auto",
"expect": {
"refused": "plan"
}
},
{
"about": "An unknown mode is read as the default, never as anything wider.",
"accept": true,
"mode": "unrestricted",
"max_mode": "auto",
"expect": {
"mode": "edit",
"wait_s": 1800
}
},
{
"about": "The device allows Plan at most: every scheduled turn is lowered to it.",
"accept": true,
"mode": "edit",
"max_mode": "plan",
"expect": {
"mode": "plan",
"wait_s": 1800
}
},
{
"about": "The wait, in seconds, as the schedule says.",
"accept": true,
"mode": "edit",
"max_mode": "edit",
"approval_wait_s": 600,
"expect": {
"mode": "edit",
"wait_s": 600
}
},
{
"about": "Below the floor: one minute.",
"accept": true,
"mode": "edit",
"max_mode": "edit",
"approval_wait_s": 5,
"expect": {
"mode": "edit",
"wait_s": 60
}
},
{
"about": "Above the ceiling: a day.",
"accept": true,
"mode": "edit",
"max_mode": "edit",
"approval_wait_s": 999999,
"expect": {
"mode": "edit",
"wait_s": 86400
}
},
{
"about": "A fraction is cut to whole seconds.",
"accept": true,
"mode": "edit",
"max_mode": "edit",
"approval_wait_s": 90.7,
"expect": {
"mode": "edit",
"wait_s": 90
}
}
]
}
+101
View File
@@ -0,0 +1,101 @@
{
"about": "Spec 3.5.0: whether a scheduled run's reply is `silent` — loop.json scheduled.sentinel on its first or last non-empty line, compared after trimming, any case, every trailing full stop forgiven — and the reply with every sentinel line taken out (`stripped`, the text a preview shows), trimmed. The server's rule for its own runs, and the device's for a scheduled turn.",
"cases": [
{
"about": "The sentinel alone.",
"text": "[SILENT]",
"expect": {
"silent": true,
"stripped": ""
}
},
{
"about": "Lower case, with a full stop.",
"text": "[silent].",
"expect": {
"silent": true,
"stripped": ""
}
},
{
"about": "On the last line, after a sentence.",
"text": "Nothing new since yesterday.\n[SILENT]",
"expect": {
"silent": true,
"stripped": "Nothing new since yesterday."
}
},
{
"about": "On the first line, before a sentence.",
"text": "[SILENT]\nChecked the feed: nothing.",
"expect": {
"silent": true,
"stripped": "Checked the feed: nothing."
}
},
{
"about": "In the middle: not silent (only the first or last line counts), and the line still goes from the preview.",
"text": "Two new posts.\n[SILENT]\nBoth about waybread.",
"expect": {
"silent": false,
"stripped": "Two new posts.\nBoth about waybread."
}
},
{
"about": "Inside a sentence: not silent.",
"text": "I would say [SILENT] but there is news: the build broke.",
"expect": {
"silent": false,
"stripped": "I would say [SILENT] but there is news: the build broke."
}
},
{
"about": "Blank lines around it are not lines.",
"text": "\n\n [SILENT] \n\n",
"expect": {
"silent": true,
"stripped": ""
}
},
{
"about": "A space before the full stop.",
"text": "All quiet.\n[SILENT] .",
"expect": {
"silent": true,
"stripped": "All quiet."
}
},
{
"about": "Without brackets: not the sentinel.",
"text": "SILENT",
"expect": {
"silent": false,
"stripped": "SILENT"
}
},
{
"about": "Empty: not silent.",
"text": "",
"expect": {
"silent": false,
"stripped": ""
}
},
{
"about": "An ordinary reply.",
"text": "The backup finished at 03:12; 4.2 GB.",
"expect": {
"silent": false,
"stripped": "The backup finished at 03:12; 4.2 GB."
}
},
{
"about": "Two full stops are forgiven too (every trailing one is).",
"text": "[SILENT]..",
"expect": {
"silent": true,
"stripped": ""
}
}
]
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+124 -8
View File
@@ -1,6 +1,7 @@
# Context hygiene
Spec 3.0.0. What a session does to keep tool results from filling the model's context — the same in
Spec 3.2.0. What a session does to keep tool results from filling the model's context, and (§10, from
3.1.0) what it keeps still so the model's server can reuse what it has already read — the same in
a chat and in an agent session, in both projects. The texts and numbers are `loop.json` `context`;
the cases are `conformance/context.json`; what the model is told is `prompts/blocks/context.md`.
@@ -11,7 +12,8 @@ rewritten.** Changing earlier context invalidates the prompt cache from that poi
server processes everything after it again, and a cloud API charges full input price for it again —
on a long context that costs more than the measure saves. So no earlier result is ever shortened,
replaced by a stub or removed afterwards. The one deliberate break is compaction, which already
replaces the history with a summary.
replaces the history with a summary. (From 3.2.0 a turn's reasoning is sent back during the turn and
not after it, §8: the common chat templates render the history the same either way.)
## 1. Every result has an id
@@ -125,8 +127,16 @@ two results.
## 7. Compaction
Compaction is the one deliberate break of the cache, and it already exists. In 3.0.0 two things
come with it:
Compaction is the one deliberate break of the cache, and it already exists. **From 3.1.0 the
summary is asked for as the next turn of the same conversation**: the same system prompt, the same
tools, every message as it was, and then one more user message — `prompts/tasks/compact.md`, whose
`{{transcript}}` and `{{previous_summary}}` are empty in this form, since the model has the
conversation, an earlier summary included, itself. So the request
that makes the summary costs only that message; a separate request with a pasted transcript was a
full re-read of everything, and a transcript capped to fit it lost the session's middle. A tool
call in the summary's reply is not run; its text before the call is the summary, and a reply with
none fails the compaction as an empty one does. The summary request is never shown as a turn of the
session, and it is not stored as one. In 3.0.0 two things came with compaction, and still do:
- After the summary the harness adds — itself, not the model — a table of the **reads the summary
covers**: the full reads made since the previous compaction (or since the session began) in turns
@@ -151,16 +161,122 @@ come with it:
- **The dedupe table is emptied**, so no stub ever points at content that is no longer in the
context. A read after compaction is a full read; a `recall` of any earlier id still works.
## 8. Earlier reasoning
## 10. The prefix: what the model has already read
Left to the model's own chat template: the harness sends the history as it does, and neither strips
reasoning a template keeps nor adds what it drops.
A model's server keeps what it has read of a request and reuses it for the next one only as far as
the two are the same from the first byte. The system prompt and the tool list come first, so **a
change to either is a full re-read** of everything after them — on a long session minutes of work
on a local server, and the full input price again on a cloud API. Measured (2026-11-05, a local
model): a date that changed at midnight sent a 16,912-token session from 99 % cached to 0 %,
139 seconds. So, from 3.1.0:
1. **The system prompt is made once per session and sent unchanged.** It is built when the session
starts, kept with the session, and every request sends those exact bytes. It is built again only
where everything is read again anyway: after a compaction (§7), or when the session moves to
another model. A session that is resumed sends what it kept.
2. **Nothing in it is a clock.** No date or time. The date goes in a note (rule 3): the first user
message of a session carries it, and so does the next one after the date has changed.
3. **What changes during a session goes at the end, as a note** on the next user message, never
into earlier text: the permission mode (`modes/<mode>.md` as the note's body when it changes,
and its first line is in the prompt only as it was at the start), the plan when the person changed
it (the model's own `plan_write` and `plan_update` already answer with it), a memory or
instruction file the person edited, a personality chosen, an MCP server's instructions that
arrived later, the date. The note is a block after the person's words:
```
<session-note>
The permission mode is now plan: …
</session-note>
```
(`loop.json` `context.note`.) Each change is one block of the note, the blocks separated by a
blank line, in the order `context.note` lists them; a value that became empty reads
`context.note.empty`; the date is the person's own (their zone, else the machine's). A note is
part of that message from then on, like anything sent. A request with no user message (a tool
step), and words the person adds to a turn already running, carry no note; it waits for the next
message that starts a turn. A change the model made itself (its own `plan_write`, `memory`,
`settings`, a file it wrote) needs no note: its tool result already said it.
4. **The tool list is the same for the whole session.** A tool whose `requires` can come and go
during a session — `page`, `display`, `forge`, and plan mode for `plan_submit` — is offered from
the start whenever the session could ever meet it, and a call made while it is not met answers
the tool's `unavailable` text. Only what is fixed for the session may leave a tool out: the
session kind (`sessions`), the model (`vision`), a subagent's narrowing, what the project's
configuration or the person switched off before the session began. The tools stay listed in
the wrap-up request too (`loop.json` `wrap_up`): its message says they are withdrawn, and a call
in that reply is not run. A tool withdrawn after its final refusal stays in the list and answers
that refusal. **The one exception is an MCP server**: a session waits up to `mcp_wait_ms` for
the servers it is configured with before its first request, so their tools are in the first
list; a server that connects later adds its tools when it connects — one re-read, once — and its
instructions come as a note.
5. **Nothing already sent is rewritten** — the one rule above, for results; old tool output is
never pruned in place.
6. **Every request's cache use is recorded** where the provider reports it (cached input tokens),
beside the request's other usage, so a slow prompt has a cause on record.
What a server does with a matching prefix is its own business; a harness that keeps these rules has
done what it can.
## 8. Reasoning goes back to the model during its turn
From 3.2.0 (it was left to the chat template before). A model that thinks before each tool call
works on from what it thought: sent its own reasoning back, it carries on; sent its calls without it,
it reasons its way to them again, step after step. Measured on a local model: a step re-read about a
fifth fewer tokens with its reasoning sent back.
- **The current turn** is every message after the last one that started a turn: a message the
person wrote, or a machine message that starts a turn of its own (a job's or a team's note to an
idle session, `loop.json` `jobs`). What is delivered at a step boundary while a turn runs — a
job's note, a team message, words the person adds — does not start a turn, and a tool result
never does.
- **Every assistant message of the current turn carries the reasoning it came with**, as the
model gave it, in full: in the OpenAI chat dialect as `reasoning_content` on the assistant message
(beside its `content` and `tool_calls`), and in the Anthropic dialect as its thinking blocks with
their signatures, unchanged and first (which that API already requires for tool use). Reasoning
read from inline tags (`<think>`; `quirks.json` `reasoning-fields`) goes back the same way, as
`reasoning_content`, and never as text in `content`. A message that came with no reasoning
carries none — no empty field.
- **Assistant messages of earlier turns carry none.** The common templates (Qwen3.x, Nemotron's
`truncate_history_thinking`, gpt-oss) drop it there themselves, so what the server reads of the
history is the same bytes either way and nothing is re-read; with a template that would keep it,
the turn boundary re-reads at most the previous turn. A compaction's summary starts the history
afresh: nothing before it carries reasoning.
- **What is stored is unchanged**: a session keeps each message's reasoning as before; this rule
is only about what a request carries (`conformance/reasoning.json`).
- A subagent, a team member and the main agent each have their own turns: a member's turn starts
with its brief or with a message that woke it.
## 11. No absolute paths in the prompt
From 3.2.0. An absolute path costs tokens on every request, says where a machine keeps its files,
and is copied by the model into calls where a relative one would do. So in an agent session (a
device's disk):
- **The system prompt, every note and the harness's own task messages (`tasks/init.md`) name no
absolute path of the machine.** The environment
block names the project by its root's last path component and says paths are relative to its
root (`loop.json` `context.env`): `Project: app (paths are relative to its root)`. Where the
session was started in a directory below the root, one more line names that directory relative
to the root: `Started in: packages/web (relative to the project root)`. There is no
`Working directory:` or `Project root:` line with an absolute path any more.
- **A file in the project is named relative to its root** (an instruction file, `docs/AGENTS.md`); a
file under the person's home directory outside the project as `~/…` (the global instructions,
`~/.config/lembas/AGENTS.md`). Only a file outside both is named by its absolute path.
- **Relative paths are resolved against the project root** — by every file tool (`read`, `write`,
`edit`, `multiedit`, `apply_patch`, `glob`, `grep`, `list`, `view_image`, `show`) and as the
directory `bash` starts in (its `cwd` argument, relative, likewise). Where the person started
below the root is a fact told to the model, not a second base; it still ends the instruction
chain (`filesystem.md`). **Absolute paths are still accepted** everywhere, as before, and answers
still name paths as `filesystem.md` says.
- A chat on the server is not a machine's disk: its paths are the server's tree's, short and the
same for every instance (`/home/<name>`, `blocks/workspace.md`). Its prompt names nothing longer.
`conformance/paths.json`: the environment lines, and how a path is resolved.
## 9. What the model is told
`prompts/blocks/context.md`, in every session that has `recall`.
## Not in 3.0.0
## Not in 3.2.0
Eliding old content in batches behind a threshold, and measuring quality and tokens with and without
these measures, are left for a later spec. Every measure above ships with its unit and conformance
+171
View File
@@ -0,0 +1,171 @@
# Display
Spec 3.7.0. **One display in every client** — the web UI, Desktop, the CLI, Android — for the
things every one of them draws: a tool call, the end of a reply that did not finish, the card that
waits for the person, and a number. `progress.md` says what a session is doing *now*; this says
what stays on the screen afterwards. The data is `loop.json` `display`; the cases
`conformance/display.json`.
Each client keeps its own look — a terminal row, a card, a chip — and its own translation of the
fixed words. What is the same is **what is said, from which data, in which state**.
## 1. A tool call's title
One rule, and one title per call: **the call's short title** — the same string in the transcript,
as `what` of `running_tool` (`progress.md` §2) and as `title` of the link's `tool_call`
(`acp.md`). It is made from the call's arguments alone, so it is known the moment the call starts
and never changes afterwards:
1. `questions` (a list, `ask_user`): its `header`s, joined with ` · `.
2. `patch` (a string, `apply_patch`): the files it names — every `*** Add File: `,
`*** Update File: ` and `*** Delete File: ` line's path, else every `+++ ` line's path without
a leading `b/` (`/dev/null` left out) — joined with `, `.
3. Otherwise the first of these arguments that is a string with anything but white space in it,
in this order (`display.title.keys`): `summary`, `command`, `code`, `pattern`, `query`, `url`,
`path`, `file_path`, `from`, `description`, `name`, `id`, `title`, `key`, `target`, `to`,
`action`.
4. Then: trimmed, **its first line only**, trimmed again, and cut to **80 characters**
(`progress.what_max`) — 79 and `…` — counted in code points.
A call with none of these has **no title**: the client draws the tool's name alone, and
`running_tool` goes without `what`.
The order puts what a call *does* before where: a `grep` is titled by its pattern, not its
directory; a `bash` by its command, not its description; `phone_action` by its `summary`. The
tool's own name (or the client's label for it — `Bash`, `Search files`; a client's own table) is
drawn beside the title and is not part of it.
The short title is for a call **as it is listed**. The approval card (§5) is not titled by it: a
card shows what is asked in full — the whole command, the change — and names the tool
(`acp.md` `session/request_permission`: `toolCall.title` the whole command or the tool's name,
`_meta.lembas.tool` the tool).
A tool the spec marks `block: plan` or `block: hidden` is not drawn as a call at all (§3).
## 2. A call's states
A drawn call is in exactly one of four states (`display.states`), and every client tells the four
apart at a glance — by a mark, a colour or a word of its own; never by the title, which is the
same in all four:
| State | When | What is shown beside the title |
|---|---|---|
| `running` | from the call's start until its result | a mark that it is running (a spinner, `…`); no duration is required — a client that shows one counts it from the call's start, as `progress.md` §3 writes elapsed time |
| `done` | its result came and is not an error | **how long it took** (below) |
| `failed` | its result is an error — the tool's own failure, a non-zero exit a tool reports as one, a timeout | how long it took, and the **first line of the error** where there is room |
| `denied` | it was not run: the person, a rule, the mode or the hardline refused it | **no duration**; the first line of the reason where there is room |
A call that was `running` when its turn was stopped, or whose result never came (the session
ended, the device went away), is drawn `failed` once that is known — never left spinning.
**The duration** of a finished call is the time from its start to its result, as the
implementation that ran it measured it, written the one way (`display.duration`): under a minute
in seconds with one decimal (`0.4s`, `8.4s`) — a time that would round to `60.0s` is a minute,
`1m 00s`; from a minute `1m 05s`; from an hour `2h 03m` —
`progress.md`'s elapsed form with tenths under a minute. A duration is not a locale number (§6):
it is written with `.` everywhere. A stored call whose duration was not kept shows none.
**Facts from the result** (`display.facts`) go after the title, never in its place:
- **an edit** (`block: edit`) shows **`+{{added}} −{{removed}}`** (`display.change`; the minus is
U+2212) once its change is known: the lines its diff adds and removes. Counted from the unified
diff by its hunks — after each `@@ -a,b +c,d @@` header, the next lines that begin with `+`, `-`
or a space until `b` old lines and `d` new lines are used up (`\ No newline at end of file` counts
for nothing; a missing `,b` or `,d` is 1); a `+` there is one added, a `-` one removed. Nothing
outside a hunk is counted, so a file header never is and a removed line that itself begins with
`-- ` always is. Several files in one diff add up.
- **a command** (`block: shell`) shows **`exit {{code}}`** (`display.exit`) when its exit code is
known and not 0.
- **a search** (`block: search`) shows **`{{count}} hits`** (`display.hits`, `display.hit` for 1)
where the implementation knows the count.
Anything else an implementation knows (the lines read, a job's id) it may add the same way.
## 3. The kinds of block
A tool's `block` (`tools/<name>.json`; `display.blocks`) says how its call is read, and every
client distinguishes these — at least by what it shows collapsed and what it opens to:
| `block` | Collapsed | Opened |
|---|---|---|
| `shell` | the command (the title), `exit N` | the output |
| `edit` | the path, `+N −M` | the change as a diff — a client may show the first of it without a click |
| `read` | the path (or the id) that was read | the text that came back, where the client keeps it |
| `search` | the pattern or the query, the hits | the hits |
| `web` | the query or the address | the results or the page's text |
| `task` | the task handed to a subagent | what the subagent did — its own calls, its progress (`subagents.md` §12) — and its report |
| `tool` | the tool's name and the title | the result |
| `plan` | **not drawn**: the plan card refreshes instead | |
| `hidden` | **not drawn** | |
A tool the client does not know (an MCP tool, a custom tool) is `tool`.
## 4. How `stopped` and `failed` end a reply
A turn that did not finish ends with the progress `stopped` or `failed` (`progress.md` §4). That
progress is not only the last thing on the progress line: **its line stays on the finished
reply** — the text alone, no elapsed time (`progress.md` §3):
- `Stopped: by you` · `Stopped: step limit` · `Stopped: budget` · `Stopped` (no reason known)
- `Failed: {{reason}}` — the error, one line
Every client draws it **at the end of that reply**, in the transcript, where it remains when the
next turn begins and the progress line has moved on — `failed` in the client's error colour,
`stopped` in its muted one. Nothing else says the same thing beside it: a client does not also
print the raw error or a second "cancelled" notice of its own wording. A reply with no text at all
(stopped before the first token) still gets the line, on its own.
Where the reply is shown again from what was stored — a reload, a resumed session, another client
— it is drawn again from the stored end; an implementation that stores a reply stores how it
ended (`stopped` with its reason, `failed` with its reason). A turn that finished normally shows
nothing.
## 5. What the card offers
When a session waits for the person (`waiting_for_person`), every client offers the same actions
(`display.actions`), under these words or their translation:
**An approval** (`what: approval`; `acp.md` `session/request_permission`):
| Action | Words | Answer |
|---|---|---|
| `once` | Allow once | the call runs; nothing is remembered |
| `always` | Always allow | the call runs and the offered pattern is allowed from now on — **offered only where the request offers it** (`always` absent: `permission/arity.json` `exact_only`, a `confirm: always` tool). A client with more than one place to remember it (this session, this project) may offer each |
| `deny` | Deny | the call is not run |
| `deny_reason` | Deny, and say why | the call is not run and the person's words go to the model as the reason (`feedback`) |
A client may also let the person **correct a command before allowing it once** (the answer's
`command`); what is written is judged again. Closing the card without choosing is `deny`.
The card shows what is asked about itself — the command, or the change as a diff — and the call's
`purpose` where one was given.
**A question** (`what: question`; `ask_user`, `acp.md` `_lembas/question`): the options as given,
the recommended one first and marked; several may be chosen where `multiple`; and **always a row
of the person's own — "Something else"** (`something_else`) — that takes free text and answers
`custom`. A client may offer asking back (`back`) and skipping one of several questions
(`skipped`). Closing the card is `dismissed`.
**A plan** (`what: plan`; `plan_submit`, `acp.md` `_lembas/plan`): **Approve** — together with
**the mode the work continues in** (`approve_edit`: Approve, continue in Edit; `approve_manual`:
Approve, continue in Manual; never a mode beyond what the session may have) — and **Revise**
(`revise`), which takes the person's words as feedback. Closing the card is `dismissed`: nothing
is decided.
A client that cannot offer one of these (a notification with two buttons) offers what fits and
opens the full card for the rest; it never answers for the person.
## 6. Numbers
A number a person reads is written **in the client's own locale format** — its grouping and its
decimal mark, from the platform's number formatter and the locale the client runs in (the
browser's, the phone's, a terminal's `LC_NUMERIC` / `LC_ALL` / `LANG`), not from a rule here. That is every count and
measure: tokens (`12,480` · `12 480` · `12.480`), the rate (`12.5` · `12,5`), `done` / `total` and
`percent`, hits, lines, `+added −removed`, costs and credits.
Not numbers in this sense, and written as they are everywhere: durations (§2, `progress.md` §3),
ids (`s1`, `job7`, `#12`), an exit code, a line number in a path (`a.ts:120`), a version, a port.
The texts in `conformance/` are written in the **plain format** — no grouping, `.` for the
decimal mark — which is what an implementation's text function produces when it is given no
locale; a client passes its locale's formatter to the same function. Nothing sent between
implementations is ever formatted: `progress` carries numbers, and each client formats its own.
+7 -2
View File
@@ -18,7 +18,8 @@ one access level for the whole working directory, decided by the CLI's permissio
- **Absolute** paths begin with `/`, the root of the tree: the organisation's root on the server,
the file system's root on a device.
- **Relative** paths resolve against the session's **start directory** (its working directory).
- **Relative** paths resolve against the session's **start directory** (its working directory) —
on a device, from spec 3.2.0, against the project root (*Node kinds*, below).
- `.` and `..` are resolved by their text, before anything is looked up; `..` above `/` stays at
`/`. Repeated `/` count as one, and a trailing `/` changes nothing. On the server there are no
links: a path is what it says. On a device, a link is followed, and where the CLI's rules look at
@@ -42,7 +43,11 @@ one access level for the whole working directory, decided by the CLI's permissio
A session has a **boundary** (what it may see at all: the root, a directory, one repository) and a
**start directory** inside it. On a device the boundary is the project root (the directory the
CLI's trust is given to) and the start directory is where the session started.
CLI's trust is given to) and the start directory is where the session started. From spec 3.2.0 a
device resolves relative paths against the **project root**, not the start directory (`context.md`
§11): the model is told the project and, when it started below the root, that directory relative to
the root — one base for every relative path, whatever the directory. The start directory still
ends the instruction chain (below).
## Access levels
+891 -4
View File
@@ -23,7 +23,7 @@
}
},
"wrap_up": {
"about": "One more request with no tools and a user message saying which limit was reached: answer now — what is done, what is not, what would come next. The transcript says the prompt was stopped, so an answer given because the room ran out is never mistaken for one the model chose to give.",
"about": "One more request, with the session's tool list unchanged (context.md §10, rule 4) and a user message saying which limit was reached: answer now — what is done, what is not, what would come next. The transcript says the prompt was stopped, so an answer given because the room ran out is never mistaken for one the model chose to give. A tool call in that reply is not run.",
"message": "The {{limit}} for this prompt has been reached and the tools have been withdrawn. Answer now from what you have: what is done, what is not, and what would come next."
},
"nudges": {
@@ -34,7 +34,7 @@
"about": "Calls in one step run together, at most 4; a call that waits on the user (ask_user, plan_submit) runs alone; two calls on one file run in order. A tool's error is its result, never the end of the prompt.",
"max": 4
},
"capacity": "A subagent (task) is not started on a model whose server cannot hold it beside the prompt's own model — or beside the model of a subagent already running: another model of a connection that holds one model at a time, or the same model when it serves one request at a time (models/schema.json capacity).",
"capacity": "A subagent (task) is not started on a model whose server cannot hold it beside the prompt's own model — or beside the model of a subagent already running: another model of a connection that holds one model at a time, or the same model when it already serves as many of this session's requests as it can at once (models/schema.json capacity: `parallel`, `single_session` being parallel 1). Spec 3.3.0: which model a subagent may run on at all, and the refusals for the session's own one-model server and a one-request model, are subagents.md and `subagents` below, checked first. A team's members are not refused for a full model: they wait for a slot (team.md, Capacity).",
"jobs": {
"about": "Background work owned by a session: a command (bash `background: true`, or one still running when its timeout passed) or a subagent (task `background: true`). One id sequence per session (job1, job2, …), one list (job_list), one way to read (job_output), to stop (job_stop) and, for a subagent, to message (job_send); a subagent's own tools see only the jobs it started. A job that ends wakes the session that owns it: while a prompt runs, as a user message at the next step boundary; otherwise as a new turn of its own, marked `machine` so a UI shows it as the harness's, not the person's. A session that is not open keeps the note until it is resumed. Every such message begins with its mark, said rather than hidden: a model refuses an unmarked one as an injection (conformance/jobs.json gives the texts).",
"marks": {
@@ -61,8 +61,211 @@
},
"lifecycle": "A subagent's own background commands stop when it ends, and its report says so. A session's jobs stop when the session is deleted. A front end asked to exit while jobs run asks the person first; one with nobody to ask waits for the jobs the prompt started, then stops the rest."
},
"subagents": {
"about": "Spec 3.3.0 (subagents.md): which model a subagent — a task subagent or a team member — runs on, and when subagents are offered. The session's own model unless the person named another in this session; no setting chooses one. The texts are said word for word, checked in this order: not_named, same_group, one_request. conformance/subagents.json.",
"texts": {
"not_named": "Use another model for subagents only when the person names it.",
"same_group": "That model is on the same one-model server as this chat's model; name a model on another server.",
"one_request": "This model serves one request at a time: name another model, on another server, for subagents."
},
"named": {
"about": "A model is named when its served id, its id at its connection or its display name occurs as a whole word, without case, in a message the person typed in this session (never model text, tool output, files, notes, marked messages or reports; a compacted message still counts). Before the name: not a letter, digit, _, -, /, . or :. After it: not a letter, digit, _, - or /, nor a . or : followed by a letter or digit. White space in a display name matches any run of white space.",
"before": "[\\p{L}\\p{N}_\\-/.:]",
"after": "[\\p{L}\\p{N}_\\-/]|[.:][\\p{L}\\p{N}]"
},
"setting": {
"about": "How the agents {min, max} setting (team.md §2) is shown to a person: one range from 1 to the cap with two handles, `min` and `max` naming them; `label` beside it, `hint` (or `short` where one line has no room) saying what the numbers count — the session's own agent included, so 1 is that agent alone and Max 4 is it and up to 3 subagents; and `own` beside it when the session's model cannot serve subagents itself (subagents.md §4).",
"label": "Subagents",
"min": "Min",
"max": "Max",
"hint": "The count includes this agent: 1 is this agent alone, with no subagents; Max 4 is this agent and up to 3 subagents.",
"short": "1 is this agent alone",
"own": "This model serves one request at a time: subagents need another model, on another server, named in the chat."
}
},
"team": {
"about": "Teams (spec 3.2.0, team.md; which model a member runs on and when a team is offered: spec 3.3.0, subagents.md; the main agent, the tree, permissions and a subagent's life: spec 3.4.0, subagents.md §5–§13). The texts are said word for word; {{size}} is the team's size after the call (team.md §3), {{names}} names joined with \", \" in tree order. conformance/team.json, conformance/delegation.json.",
"agents": {
"about": "The chat setting agents {min, max}: the agents a team may have, the lead included. 1 ≤ min ≤ max ≤ cap. min and max are a new chat's defaults; cap is the instance's (LLeMbas) or the global configuration's (the CLI).",
"min": 1,
"max": 4,
"cap": 32
},
"names": {
"about": "A subagent's name: unique among the subagents that have not ended; `lead` is the main agent's, `all` addresses everyone, `parent` (3.4.0) the sender's parent.",
"pattern": "^[a-z][a-z0-9-]{0,31}$",
"lead": "lead",
"reserved": [
"all",
"lead",
"parent"
],
"parent": "parent",
"id_prefix": "s"
},
"marks": {
"message": "[Team message from {{from}} to {{to}}:]",
"report": "[Team report from {{from}} to {{to}}:]",
"assignment": "[Team assignment from {{from}} to {{to}}:]",
"request": "[Team request {{id}} from {{from}} to {{to}}:]",
"decision": "[Team decision on {{id}} from {{from}} to {{to}}:]",
"context_full": "[Team notice to {{to}}: your context is full]"
},
"unavailable": {
"about": "What a team tool answers while its requirement `team` is not met (team.md §2). one_agent is also each team tool's own `unavailable`, and what task answers while a team is offered, max is 1 and the lead has no member. one_request: no model can serve as a subagent any more (subagents.md §4) — the session's model's capacity changed after the prompt was made.",
"one_agent": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"one_request": "This model serves one request at a time now, so there is no team. Do the work yourself."
},
"work": {
"about": "What a manager may not do itself (team.md §6): every call whose risk class is write or execute — an MCP tool's is read when it says readOnlyHint, else execute — but `job_stop`, and a `bash` call that the default rules alone allow in manual mode (reading commands). The tool list is unchanged; these answer texts.manager.",
"write": [
"apply_patch",
"edit",
"mkdir",
"multiedit",
"mv",
"rm",
"skill_manage",
"write"
],
"execute": [
"bash",
"branch",
"commit",
"merge",
"pr",
"python",
"release",
"tag"
],
"kept": [
"job_stop"
]
},
"read_max": 50,
"texts": {
"added": "Added {{name}} ({{role}}): it is working. Its report comes to you when it finishes. The team is {{size}} of {{max}} agents.",
"added_waiting": "Added {{name}} ({{role}}): it waits for a free slot — the model serves {{parallel}} requests at once and all are busy — and starts when one frees. Its report comes to you when it finishes. The team is {{size}} of {{max}} agents.",
"added_under": "Added {{name}} ({{role}}) under {{parent}}: it is working. Its report goes to {{parent}} when it finishes. The team is {{size}} of {{max}} agents.",
"added_waiting_under": "Added {{name}} ({{role}}) under {{parent}}: it waits for a free slot — the model serves {{parallel}} requests at once and all are busy — and starts when one frees. Its report goes to {{parent}} when it finishes. The team is {{size}} of {{max}} agents.",
"sent": "Sent to {{to}}.",
"stopped": "Stopped {{names}}. The team is {{size}} of {{max}} agents.",
"manager": "You lead a team: give this to a member (team_add or team_send).",
"full": "The team is full: it has as many agents as the person allows ({{max}}). Give the work to a member already on it (team_send), or stop one (team_stop) first.",
"bad_name": "{{name}} cannot be a name: use lowercase letters, digits and hyphens, beginning with a letter, at most 32 characters.",
"all_name": "all addresses the whole team; it cannot be a name.",
"taken": "There is already an agent called {{name}} in this team. Choose another name.",
"no_goal": "Say the team's goal in `goal`, in one line, with your first member: every member is told it.",
"unknown": "No agent called {{name}} in this team. The team: {{names}}.",
"self": "That is you: send it to someone else.",
"nobody": "Nobody else is on the team yet: add a member with team_add.",
"not_yours": "{{name}} is not under you: you can stop only the members you lead, directly or through your members.",
"nobody_to_stop": "No member is under you: there is nobody to stop.",
"no_report": "(no report)",
"ended": "[ended: {{reason}}]",
"only_main": "Only the main agent adds, assigns, replaces and stops subagents: ask it (team_send to lead).",
"not_manager": "{{name}} is not a sub-manager: place a subagent under the main agent (lead) or under one added with lead: true.",
"wider": "A subagent's mode cannot be looser than its parent's ({{parent_mode}}).",
"request_not_narrower": "Request options go with a mode stricter than the parent's: without one there is nothing to ask for.",
"request_kind": "{{kind}} is not a request option: use read, write or execute.",
"requestable": "Your mode does not allow this, but the main agent may: ask for it with team_request (the tool, the pattern, why), then try again once it allows.",
"not_delegated": "Your mode does not allow this, and you may not ask for it: tell your parent what you need.",
"not_requestable": "You may not ask for {{tool}}: your request options are {{kinds}}.",
"requested": "Asked the main agent ({{id}}): you are told its decision. Carry on with what you can meanwhile.",
"no_request": "No open request {{id}}.",
"decided": "{{decision}} {{id}} for {{name}}.",
"allowed": "Allowed",
"refused": "Refused",
"decision_allowed": "Allowed: {{tool}} {{pattern}}. Try it again now.",
"decision_refused": "Refused: {{tool}} {{pattern}}.",
"no_parent": "You are the main agent: you have no parent.",
"finished": "Reported to {{to}}. Your task is done: stop here.",
"has_ended": "{{name}} has ended: replace it (team_replace) or add another.",
"cycle": "{{name}} cannot go under {{parent}}: that is under it.",
"assigned": "Assigned to {{name}}: it is told now.",
"replaced": "Replaced {{name}}: {{id}} takes its place, briefed with its task and findings. The team is {{size}} of {{max}} agents.",
"replace_brief": "{{task}}\n\nYou take over from {{name}} ({{id}}), which ended. What it found:\n{{findings}}",
"no_findings": "(no findings)",
"noted": "Noted (finding {{n}}).",
"not_yours_findings": "You may read only your own findings and those of the subagents under you.",
"context_full": "Save what you found with team_findings, then tell your parent with team_send that you are gone and what is left undone. This is your last turn: at most {{steps}} steps.",
"gone": "{{name}} ({{id}}) ran out of context and has ended. Its findings: team_findings with of {{name}}.",
"request_body": "{{tool}} {{pattern}} — {{why}}"
},
"read": {
"about": "team_read's answer: the tree, then the room. Agents in tree order (an agent, then its members in the order they were added, depth first), indented two spaces per level below the lead. `last`: `active now` while working, else how long ago its last turn ended (durations as jobs write them: \"5s ago\", \"1m 05s ago\"). A message's text: its first line after the colon, every further line indented two spaces. Messages above `since` the caller may see, oldest first, at most read_max; `more` when there are others after the last shown. Spec 3.4.0: the row adds the id, the mode (with request options) and the context use; open slots follow the tree, ended subagents after them.",
"tree": "Team ({{size}} of {{max}} agents):",
"agent": "{{indent}}- {{name}} ({{id}}) — {{role}} · {{state}} · {{model}} · {{mode}} · {{context}} · {{last}}",
"lead_role": "the main agent",
"states": {
"working": "working",
"waiting": "waiting for a slot",
"finished": "finished",
"idle": "idle",
"paused": "paused: context full",
"done": "done",
"out_of_context": "out of context",
"stopped": "stopped"
},
"active": "active now",
"room": "Room since #{{since}}:",
"message": "#{{n}} {{from}} → {{to}}: {{text}}",
"report": "#{{n}} {{from}} → {{to}} (report): {{text}}",
"none": "No messages since #{{since}}.",
"more": "More after #{{last}}: team_read with since {{last}}.",
"slots": "Open slots: {{n}} — fill them with team_add.",
"ended": "Ended:",
"ended_agent": "- {{name}} ({{id}}) — {{role}} · {{state}} · {{findings}} findings",
"context": "{{percent}}% context",
"request": "+ {{kinds}}"
},
"main_only": {
"about": "Spec 3.4.0 (subagents.md §6, §8): the tools only the main agent has; a subagent's call to one, or to task, answers texts.only_main.",
"tools": [
"team_add",
"team_assign",
"team_decide",
"team_replace",
"team_stop"
]
},
"context": {
"about": "Spec 3.4.0 (subagents.md §9): a subagent does not compact. When its context reaches pause_at of its model's window it is paused and given one final turn of at most final_steps steps, whose user message is the context_full mark and texts.context_full.",
"pause_at": 0.85,
"final_steps": 8
},
"request": {
"about": "Spec 3.4.0 (subagents.md §7): the kinds a request option may name — risk classes — and the ids of requests, r1, r2, … per session.",
"kinds": [
"read",
"write",
"execute"
],
"id_prefix": "r"
},
"whoami": {
"about": "Spec 3.4.0 (subagents.md §8): team_whoami's answer, one line each; `request` only with request options, `parent` only for a subagent. {{percent}} is floor(used × 100 / window).",
"lines": {
"who": "You are {{name}} ({{id}}): {{role}}.",
"parent": "Your parent: {{parent}}.",
"task": "Your task: {{task}}",
"mode": "Your mode: {{mode}}.",
"request": "You may ask the main agent for: {{kinds}} (team_request).",
"model": "Your model: {{model}}.",
"limits": "Limits: the team is {{size}} of {{max}} agents; at most {{steps}} steps a turn; {{spawn}}",
"spawn_yes": "you add subagents.",
"spawn_no": "only the main agent adds subagents.",
"context": "Context: {{used}} of {{window}} tokens ({{percent}}%)."
}
},
"findings": {
"about": "Spec 3.4.0: team_findings read's answer — the header, then one line per finding, oldest first; none: texts.no_findings after the header.",
"header": "Findings of {{name}} ({{id}}):",
"item": "{{n}}. {{text}}"
}
},
"context": {
"about": "Context hygiene (spec 3.0.0, context.md): every measure acts when a result is inserted, and nothing already sent to the model is ever rewritten — changing earlier context throws away the prompt cache from that point. conformance/context.json gives the texts.",
"about": "Context hygiene (spec 3.0.0, the prefix from 3.1.0; context.md): every measure acts when a result is inserted, and nothing already sent to the model is ever rewritten — changing earlier context throws away the prompt cache from that point. conformance/context.json gives the texts.",
"ids": {
"about": "Every tool result gets an id: `#` and its number in the session, counting from 1, in lowercase hex, at least 4 digits (`#0001`, `#000a`, `#10000`) — unique in the session and never reused (not after a compaction either), so `recall` finds any of them. It is the first thing in the result, in brackets.",
"digits": 4
@@ -105,6 +308,690 @@
"line": "Read a file again for its content; recall shows a result by its id.",
"rows": 50
},
"reasoning": "Earlier turns' reasoning is left to the model's chat template: the harness sends the history as it does, neither stripping reasoning the template keeps nor adding what it drops."
"reasoning": "Spec 3.2.0 (context.md §8): every assistant message of the current turn — the messages after the last one that started a turn (the person's, or a machine message that starts a turn of its own; a delivery at a step boundary does not) — carries the reasoning it came with (OpenAI chat: `reasoning_content`; Anthropic: its thinking blocks, unchanged); assistant messages of earlier turns carry none. What is stored keeps it. conformance/reasoning.json.",
"env": {
"about": "Spec 3.2.0 (context.md §11): the environment block's lines about where the session works, in an agent session. `project` always, `name` being the project root's last path component; `started` only when the session started in a directory below the root, `path` being that directory relative to the root. No absolute path. conformance/paths.json.",
"project": "Project: {{name}} (paths are relative to its root)",
"started": "Started in: {{path}} (relative to the project root)"
},
"note": {
"about": "A note on the next user message (context.md §10, rule 3): what changed since the system prompt was made, after the person's words. Lines in this order, each only when it applies. `plan_ended` is the mode block for a session that leaves plan mode for a mode with no text of its own (a chat). `plan_own` is the plan block for a session that does not resend earlier tool results (a chat): the model's own plan, as its tools left it. `personal` is the {{path}} of the instructions block for the person's own instructions. Spec 3.2.0, where a team is offered (team.md §10): `team` — the size setting, on the first user message and after it changes, followed in the same block by `team_lead` when min ≥ 2 ({{members}} = min − 1), or `team_one` in its place when max is 1; `team_stopped` — members the person stopped, a block of its own. Spec 3.3.0 (subagents.md §4): `team_own` after `team` (and after `team_lead`) in the same block when the session's model cannot serve subagents itself — it serves one request at a time — and another server's model could. Spec 3.8.0 (pages.md §5): `pages_on` when HTML pages are switched on for the chat after its prompt was made ({{pages_text}} = prompts/blocks/html-pages.md as sent), `pages_off` when they are switched off.",
"open": "<session-note>",
"close": "</session-note>",
"date": "Today is {{date}}.",
"mode": "The permission mode is now {{mode}}:\n{{mode_text}}",
"plan_ended": "Plan mode has ended: make the changes the work needs; nothing is refused for planning any more.",
"plan": "The person changed the plan; it is now:\n{{plan}}",
"plan_own": "Your plan, as your plan tools left it:\n{{plan}}",
"memory": "The person changed what is remembered; it is now:\n{{memory}}",
"instructions": "{{path}} changed; it now reads:\n{{text}}",
"personal": "the person's own instructions",
"personality": "The person chose a different personality:\n{{personality}}",
"pages_on": "HTML pages are now on for this chat:\n{{pages_text}}",
"pages_off": "HTML pages are now off for this chat: write no more `html-view` blocks.",
"mcp": "Instructions from an MCP server that connected since the session began:\n{{instructions}}",
"team": "The team may have {{min}} to {{max}} agents, you included.",
"team_lead": "Work through subagents from the start: you lead, and they do the work. The person opened {{members}} slots for them: fill them with team_add.",
"team_one": "The person allows one agent: work alone; the team tools and task are unavailable.",
"team_own": "This model serves one request at a time, so subagents cannot run on it: they need another model, on another server, that the person names in this chat.",
"team_stopped": "The person stopped {{names}}; they have left the team.",
"empty": "(none)"
},
"mcp_wait_ms": 3000
},
"progress": {
"about": "Spec 3.4.0 (progress.md): one fixed set of phases every client shows the same way. `texts` are the shared i18n keys progress.<phase> (a variant: progress.<phase>.<variant>); `line` is drawn for every phase but stopped and failed; elapsed in whole seconds (5s, 1m 05s, 1h 02m). conformance/progress.json.",
"phases": [
"queued",
"waiting_for_model",
"loading_model",
"reading_prompt",
"thinking",
"writing",
"running_tool",
"waiting_for_person",
"waiting_for_subagents",
"compacting",
"retrying",
"stopped",
"failed"
],
"fields": {
"queued": {
"ahead": "int?"
},
"waiting_for_model": {
"model": "string",
"reason": "busy|slots|group"
},
"loading_model": {
"model": "string"
},
"reading_prompt": {
"done": "int?",
"total": "int?"
},
"thinking": {},
"writing": {
"rate": "number?"
},
"running_tool": {
"tool": "string",
"what": "string?"
},
"waiting_for_person": {
"what": "approval|question|plan",
"tool": "string?"
},
"waiting_for_subagents": {
"running": "int"
},
"compacting": {},
"retrying": {
"reason": "string",
"in": "int",
"attempt": "int?"
},
"stopped": {
"reason": "person|steps|budget?"
},
"failed": {
"reason": "string"
}
},
"texts": {
"queued": "Queued",
"queued.ahead": "Queued: {{ahead}} ahead",
"waiting_for_model": "Waiting for {{model}}: {{reason}}",
"loading_model": "Loading {{model}}",
"reading_prompt": "Reading the prompt: {{done}} / {{total}} tokens ({{percent}}%)",
"reading_prompt.bare": "Reading the prompt",
"thinking": "Thinking",
"writing": "Writing: {{rate}} tok/s",
"writing.bare": "Writing",
"running_tool": "Running {{tool}}: {{what}}",
"running_tool.bare": "Running {{tool}}",
"waiting_for_person": "Waiting for you: {{what}}",
"waiting_for_subagents": "Waiting for subagents: {{running}} running",
"compacting": "Compacting the conversation",
"retrying": "Retrying in {{in}} s: {{reason}}",
"stopped": "Stopped",
"stopped.reason": "Stopped: {{reason}}",
"failed": "Failed: {{reason}}"
},
"reason": {
"busy": "it serves one request at a time and is answering another",
"slots": "all its slots are in use",
"group": "its server holds another model now"
},
"what": {
"approval": "allow {{tool}}?",
"approval.bare": "an approval",
"question": "a question",
"plan": "the plan"
},
"stopped_reason": {
"person": "by you",
"steps": "step limit",
"budget": "budget"
},
"line": "{{text}} · {{elapsed}}",
"no_elapsed": [
"stopped",
"failed"
],
"what_max": 80,
"pace_per_second": 4
},
"scheduled": {
"about": "Spec 3.5.0 (acp.md *Scheduled work on a linked computer*): a schedule's run as an agent turn on a linked computer, and the watch command of monitor mode. `setting` is how the device's switch is shown; `modes` the modes a schedule may choose (`default_mode` when it chose none), lowered to remote.max_mode; `approval_wait_seconds` how long an approval in a scheduled turn waits (the schedule's wait, clamped); `sentinel` the word a reply says when there is nothing to tell; `monitor` the watch command's limits. conformance/scheduled.json, silent.json, monitor.json. Spec 3.8.0 (reports.md): `notify` — a schedule's notify-when: its `values`, the `default`, the `default_condition` of `when`, the instruction `texts` placed in the run's prompt ({{condition}} the person's words), what the tool answers (`result`), and the limits of the history line and of a summary made from an answer. `sentinel` is retired: told to no model, and a reply that still carries it leaves no report. conformance/reports.json. `notify.one_shot_default`: what the creator of a schedule that runs once may store when the person chose nothing.",
"setting": {
"key": "remote.scheduled",
"label": "Accept scheduled work",
"hint": "Let your schedules run here as agent turns, in the folders remote work may use. Off by default."
},
"modes": [
"manual",
"edit",
"auto"
],
"default_mode": "edit",
"approval_wait_seconds": {
"default": 1800,
"min": 60,
"max": 86400
},
"sentinel": "[SILENT]",
"statuses": [
"ok",
"silent",
"failed",
"cancelled"
],
"monitor": {
"timeout_seconds": {
"default": 60,
"min": 1,
"max": 600
},
"excerpt_chars": 2000,
"output_max_bytes": 1048576
},
"texts": {
"off": "This computer does not accept scheduled work. Turn on \"Accept scheduled work\" on it (lembas service scheduled on).",
"plan": "A scheduled run cannot use plan mode: nobody is there to approve a plan. Choose Manual, Edit or Auto.",
"denied": "Nobody answered this approval within {{minutes}} minutes, so it counts as denied.",
"monitor_asks": "The watch command would need approval in {{mode}} mode ({{reason}}), and a watch has nobody to ask. Allow the command in the project's permission rules, or choose a wider mode for the schedule.",
"monitor_denied": "The watch command is refused here: {{reason}}.",
"no_reply": "The run ended without a reply."
},
"notify": {
"values": [
"always",
"when",
"never"
],
"default": "when",
"one_shot_default": "always",
"default_condition": "something needs my attention",
"labels": {
"always": "Every run",
"when": "When…",
"never": "Never"
},
"texts": {
"always": "Reporting: when the work is done, file a report with report_write — every run, also when you found nothing and when nothing matters; then say so in it, briefly. Then end with one short line for this run's history.",
"when": "Reporting: file a report with report_write only if this holds: {{condition}}. If it does not hold, file no report and end with one short line saying why not. If it holds, file the report when the work is done, then end with one short line for this run's history."
},
"result": {
"filed": "The report is filed. End your reply now with one short line for this run's history; do not repeat the report.",
"replaced": "The report is replaced by this one: a run files one report. End your reply now with one short line for this run's history; do not repeat the report."
},
"note_max": 200,
"summary_max": 300
}
},
"phone": {
"about": "Spec 3.6.0 (phone.md): `phone_action`, carried out by the LLeMbas app on the person's phone and confirmed there. `capability` is what the app declares with each message it sends; `fields` what each action reads (anything else in a call is dropped before the phone sees it); `required` the fields each action needs (a list inside the list: any one of them); `check` the order the fields' values are checked in; `wait_seconds` how long a call waits for the phone's answer; `texts` what the model is told, `what` what a bad field should have been. conformance/phone.json.",
"capability": "phone_actions",
"actions": [
"alarm",
"timer",
"calendar_event",
"sms_draft",
"email_draft",
"dial",
"navigate",
"add_stop",
"search_nearby",
"stop_navigation",
"open_app",
"open_url",
"media",
"torch",
"settings_panel",
"automation_intent"
],
"fields": {
"alarm": [
"time",
"days",
"label"
],
"timer": [
"seconds",
"label"
],
"calendar_event": [
"title",
"start",
"end",
"all_day",
"location",
"notes"
],
"sms_draft": [
"to",
"body"
],
"email_draft": [
"to",
"cc",
"subject",
"body"
],
"dial": [
"number"
],
"navigate": [
"destination",
"stops",
"mode",
"replace_route"
],
"add_stop": [
"stop",
"destination"
],
"search_nearby": [
"query",
"near"
],
"stop_navigation": [],
"open_app": [
"app"
],
"open_url": [
"url"
],
"media": [
"command"
],
"torch": [
"on"
],
"settings_panel": [
"panel"
],
"automation_intent": [
"task",
"app",
"values"
]
},
"required": {
"alarm": [
"time"
],
"timer": [
"seconds"
],
"calendar_event": [
"title",
"start"
],
"sms_draft": [
[
"to",
"body"
]
],
"email_draft": [
[
"to",
"subject",
"body"
]
],
"dial": [
"number"
],
"navigate": [
"destination"
],
"add_stop": [
"stop",
"destination"
],
"search_nearby": [
"query"
],
"stop_navigation": [],
"open_app": [
"app"
],
"open_url": [
"url"
],
"media": [
"command"
],
"torch": [
"on"
],
"settings_panel": [
"panel"
],
"automation_intent": [
"task"
]
},
"statuses": [
"done",
"declined",
"failed"
],
"wait_seconds": 300,
"message_max_chars": 1000,
"texts": {
"done": "Done on the phone.",
"declined": "The person declined it on the phone: nothing was done. Do not try again unless they ask.",
"failed": "The phone could not do it: nothing was done.",
"no_answer": "The phone did not answer in time: nothing was done.",
"says": "The phone says: {{message}}",
"unknown_action": "\"{{action}}\" is not an action. Use one of: {{actions}}. Nothing was sent to the phone.",
"missing": "{{action}} needs {{fields}}. Nothing was sent to the phone.",
"bad": "{{field}} is not {{what}}. Nothing was sent to the phone."
},
"what": {
"time": "a time as HH:MM (24-hour)",
"days": "a list of days from mon, tue, wed, thu, fri, sat, sun",
"seconds": "a whole number of seconds from 1 to 86400",
"start": "a date and time as YYYY-MM-DDTHH:MM, or a date as YYYY-MM-DD for a whole day",
"end": "a date and time as YYYY-MM-DDTHH:MM, or a date as YYYY-MM-DD for a whole day",
"to": "a list of recipients",
"cc": "a list of recipients",
"number": "a phone number",
"destination": "a place: lat and lon together, or a query, or a name",
"stop": "a place: lat and lon together, or a query, or a name",
"stops": "a list of places, each lat and lon together, or a query, or a name",
"mode": "one of drive, walk, bike, transit",
"near": "one of me, route",
"url": "an http or https address",
"command": "one of play, pause, toggle, next, previous",
"on": "true or false",
"panel": "one of wifi, bluetooth, internet, volume, nfc, location, do_not_disturb",
"values": "named text values"
},
"check": [
"time",
"days",
"seconds",
"start",
"end",
"to",
"cc",
"number",
"destination",
"stop",
"stops",
"mode",
"near",
"url",
"command",
"on",
"panel",
"values"
]
},
"display": {
"about": "Spec 3.7.0 (display.md): one display in every client. `title`: how a tool call's one short title is made from its arguments (the same string in the transcript, as running_tool's `what` and as the link's tool_call title) — `questions` and `patch` first, then the first non-blank string among `keys`; first line, cut to progress.what_max. `states`: the four states of a drawn call; `no_duration`: the states that show none. `duration`: a finished call's time (tenths under a minute). `change`, `exit`, `hits`/`hit`: the facts after the title. `blocks`: the kinds of block every client distinguishes; `not_drawn`: those that are no call in the transcript. `end`: the phases whose line stays on the finished reply. `actions`: what each card offers, with its English words (shared i18n keys display.actions.<card>.<action>). `plain`: the number format of the conformance texts. conformance/display.json.",
"title": {
"questions_join": " · ",
"patch_files": [
"*** Add File: ",
"*** Update File: ",
"*** Delete File: "
],
"patch_join": ", ",
"keys": [
"summary",
"command",
"code",
"pattern",
"query",
"url",
"path",
"file_path",
"from",
"description",
"name",
"id",
"title",
"key",
"target",
"to",
"action"
]
},
"states": [
"running",
"done",
"failed",
"denied"
],
"no_duration": [
"running",
"denied"
],
"duration": {
"tenths_under_seconds": 60
},
"change": "+{{added}} −{{removed}}",
"exit": "exit {{code}}",
"hits": "{{count}} hits",
"hit": "{{count}} hit",
"blocks": [
"shell",
"edit",
"read",
"search",
"web",
"task",
"tool",
"plan",
"hidden"
],
"not_drawn": [
"plan",
"hidden"
],
"end": [
"stopped",
"failed"
],
"actions": {
"approval": {
"once": "Allow once",
"always": "Always allow",
"deny": "Deny",
"deny_reason": "Deny, and say why"
},
"question": {
"something_else": "Something else"
},
"plan": {
"approve_edit": "Approve, continue in Edit",
"approve_manual": "Approve, continue in Manual",
"revise": "Revise"
}
},
"plain": {
"group": "",
"decimal": "."
}
},
"pages": {
"about": "Spec 3.8.0 (pages.md): HTML pages in answers — experimental, off unless switched on. `fence`: the info word of a page's fenced block; `title_max` and `untitled` for its title; `variables`: the CSS variables the frame provides; `note` what a client that cannot render shows in a page's place and `where` what it may add; `projection` the one line a page is for anything that reads a reply as text; `never`: where pages are never offered, whatever the switches say. conformance/pages.json. `static` (pages.md §6): a page is static everywhere — the `elements` and `attributes` a client keeps when it rebuilds the document (anything else is dropped; `aria-*` and `data-*` attributes are kept), the `addresses` an attribute or a CSS url() may hold, and the `image_types` of an inline data: image.",
"fence": "html-view",
"title_max": 80,
"untitled": "Page",
"variables": [
"--page-bg",
"--page-ink",
"--page-muted",
"--page-accent",
"--page-line"
],
"note": "This answer has a page: {{title}}",
"where": "Open it on the web or in the desktop app to see it.",
"projection": "[page: {{title}}]",
"never": [
"subagent",
"phone_assistant",
"agent_chat"
],
"static": {
"elements": [
"html",
"head",
"title",
"style",
"body",
"main",
"header",
"footer",
"section",
"article",
"aside",
"nav",
"div",
"span",
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"ul",
"ol",
"li",
"dl",
"dt",
"dd",
"table",
"caption",
"colgroup",
"col",
"thead",
"tbody",
"tfoot",
"tr",
"th",
"td",
"figure",
"figcaption",
"blockquote",
"pre",
"code",
"em",
"strong",
"b",
"i",
"u",
"s",
"small",
"sub",
"sup",
"mark",
"abbr",
"time",
"br",
"hr",
"a",
"img",
"details",
"summary",
"svg",
"g",
"defs",
"path",
"rect",
"circle",
"ellipse",
"line",
"polyline",
"polygon",
"text",
"tspan",
"desc",
"linearGradient",
"radialGradient",
"stop",
"clipPath",
"marker",
"symbol",
"use"
],
"attributes": [
"class",
"id",
"style",
"title",
"lang",
"dir",
"role",
"hidden",
"colspan",
"rowspan",
"scope",
"headers",
"span",
"href",
"src",
"alt",
"width",
"height",
"open",
"datetime",
"xmlns",
"viewBox",
"preserveAspectRatio",
"x",
"y",
"x1",
"y1",
"x2",
"y2",
"cx",
"cy",
"r",
"rx",
"ry",
"d",
"points",
"dx",
"dy",
"transform",
"fill",
"fill-opacity",
"fill-rule",
"stroke",
"stroke-width",
"stroke-opacity",
"stroke-dasharray",
"stroke-linecap",
"stroke-linejoin",
"opacity",
"font-family",
"font-size",
"font-weight",
"text-anchor",
"dominant-baseline",
"offset",
"stop-color",
"stop-opacity",
"gradientUnits",
"gradientTransform",
"clip-path",
"marker-start",
"marker-mid",
"marker-end",
"markerWidth",
"markerHeight",
"refX",
"refY",
"orient"
],
"attribute_prefixes": [
"aria-",
"data-"
],
"address_attributes": [
"href",
"src"
],
"addresses": [
"#fragment",
"data:image"
],
"image_types": [
"png",
"jpeg",
"gif",
"webp"
]
}
}
}
+12 -5
View File
@@ -12,22 +12,29 @@
"max_output": { "type": "integer", "minimum": 1, "description": "The most tokens one reply may have." },
"temperature": { "type": "number", "minimum": 0, "maximum": 2, "description": "The sampling temperature the model is set up with. LLeMbas: the administrator's, which it also applies to a request that does not set one." },
"top_p": { "type": "number", "minimum": 0, "maximum": 1, "description": "Nucleus sampling, as temperature." },
"efforts": { "type": "array", "items": { "enum": ["minimal", "low", "medium", "high", "xhigh", "max"] }, "description": "The reasoning efforts the model takes, in offering order. Narrowed when a server refuses one (quirks.json effort-refused)." },
"effort": { "enum": ["minimal", "low", "medium", "high", "xhigh", "max", "off"], "description": "The effort a new conversation starts with; off sends none." },
"efforts": { "type": "array", "items": { "enum": ["minimal", "low", "medium", "high", "xhigh", "max"] }, "description": "The reasoning efforts the model takes, in offering order. Narrowed when a server refuses one (quirks.json effort-refused). Absent: each project's fallback (the CLI's: low, medium, high); [] — the model takes none, and its one effort level is `default`." },
"thinking_switch": { "type": "boolean", "description": "Spec 3.2.0: the model's server turns thinking off for a request that sends `chat_template_kwargs.enable_thinking: false` (Qwen3.x and Nemotron 3.x templates on llama.cpp, vLLM, SGLang). Only then is the level `off` offered. Absent: false." },
"effort": { "enum": ["minimal", "low", "medium", "high", "xhigh", "max", "off", "default"], "description": "The level a new conversation starts with, when it is one of the levels the model offers (see `levels`); otherwise `medium` when the model takes it, else its first effort, else `default`. `off` — thinking switched off — exists only with thinking_switch; `default` — no effort sent, the model's own — only for a model that takes no efforts." },
"effort_style": { "enum": ["top", "kwargs", "both"], "description": "OpenAI Chat dialect: where the effort goes — top-level `reasoning_effort`, `chat_template_kwargs.reasoning_effort` (all llama.cpp reads), or both (the default)." },
"vision": { "type": "boolean", "description": "Takes images. Never sent images otherwise: most servers refuse the whole request." },
"html_pages": { "type": "boolean", "default": false, "description": "Spec 3.8.0 (pages.md): this model can write HTML pages — a complete, self-contained page in an `html-view` block of its reply. False by default; pages are offered only when this is true, the instance's switch is on and the chat's is." },
"tools": { "type": "boolean", "description": "Takes tool calls. false: it can only talk; never sent a tools array." },
"notes": { "type": "string", "maxLength": 300, "description": "What the model is good at, in a line: other models are told about it in the roster, for handing work over." },
"capacity": {
"type": "object",
"description": "How much the model's server can do at once, so a helper or a subagent on it is not started where it would evict or wait for the model already working.",
"description": "How much the model's server can do at once, so a subagent on it is not started where it would evict or wait for the model already working (subagents.md §3).",
"properties": {
"group": { "type": "string", "description": "Models that share one server holding one model at a time (llama-swap): starting another model of the group unloads this one. The CLI: a model's `group`, or its connection when the connection sets one_model_at_a_time. LLeMbas: the connection's name when it sets one_model_at_a_time, which is what /v1/models says." },
"single_session": { "type": "boolean", "description": "The model serves one request at a time: a second one waits behind the first." }
"group": { "type": "string", "description": "Models that share one server holding one model at a time (llama-swap): starting another model of the group unloads this one, so a subagent on another model of the session's model's group is refused (spec 3.3.0, subagents.md §3). The CLI: a model's `group`, or its connection when the connection sets one_model_at_a_time. LLeMbas: the connection's name when it sets one_model_at_a_time, which is what /v1/models says." },
"single_session": { "type": "boolean", "description": "The model serves one request at a time: a second one waits behind the first. The same as `parallel: 1`, which a server that knows `parallel` sends beside it for older clients." },
"parallel": { "type": "integer", "minimum": 1, "description": "Spec 3.2.0: how many requests the model's server serves at once (llama.cpp's slots, a vLLM or SGLang batch); one more waits behind them. Read as: `parallel` when given, else 1 when single_session is true, else no limit (a hosted API). Where both are given and disagree, `parallel` wins. The session's model is its own subagents' model only when it serves at least 2; a one-request session needs a named model on another server (spec 3.3.0, subagents.md §3, §4)." }
},
"additionalProperties": false
}
},
"levels": {
"about": "Spec 3.2.0. The effort levels a chat offers for a model, in order: `off` when thinking_switch is true, then the model's `efforts` — or, when it takes none, the one level `default`. What each sends (OpenAI chat): `off` — `chat_template_kwargs.enable_thinking: false` and no `reasoning_effort` anywhere; `default` — neither; an effort — `reasoning_effort` where effort_style puts it, and no `enable_thinking`. The Anthropic dialect: `off` sends no `thinking`. A level the model does not offer (an `off` for a model without the switch, from an older client or a stored chat) is read as the start level (`effort`'s rule). How it is shown: one level — no effort control at all; two, one of them `off` — a Thinking on/off switch, on being the other level; more — a slider or a list, in this order. conformance/levels.json.",
"control": ["none", "switch", "slider"]
},
"required": ["id"],
"additionalProperties": true
}
+145
View File
@@ -0,0 +1,145 @@
# HTML pages in answers
Spec 3.8.0. **Experimental, and off unless switched on.** A reply stays Markdown; where seeing
answers better than reading, the model may add **a page** to it: a complete, self-contained HTML
document in a fenced block — **static: HTML, CSS and inline SVG, no script** (§6). A client that
can, shows the page in a sealed frame at that place in the reply; every other reader sees a
one-line note. The prompt text is `prompts/blocks/html-pages.md`;
the names and texts `loop.json` `pages`; the model flag `models/schema.json` `html_pages`; the
cases `conformance/pages.json`. (It takes the place of the 1.x *prototypes*, which 2.0 removed:
one kind of block instead of two, no panel, no network.)
## 1. The fence
A page is a fenced code block whose info string begins with the word **`html-view`**
(`pages.fence`), followed by a short title:
````
```html-view Monthly sales
<!doctype html>
<html>…</html>
```
````
- **Opening line**: up to three spaces, then three or more backticks — or three or more tildes —
then `html-view`, then optionally white space and the title, to the end of the line. The word
is exact (`html`, `html-views`, `HTML-VIEW` are ordinary code blocks).
- **Closing line**: up to three spaces, the same character at least as many times as the
opening, and nothing else but white space.
- **One page per fence**: everything between the two lines is the page, as written.
- **An unclosed fence is not a page.** While a reply streams, a client shows a placeholder for a
page still being written; a reply that ends inside the fence has no page there — it is the
code block it is.
- **Backticks inside a page** (a template string, a code sample) do not end it unless a line is
a closing fence: a page that has a line of three backticks is written in a fence of four, as
any Markdown block is.
- **The title**: the rest of the opening line, white space collapsed, cut to `pages.title_max`
characters; when the line gives none, the page's own `<title>`; when it has none either,
`pages.untitled`.
## 2. What the model is told
`prompts/blocks/html-pages.md`, as bullets of the system prompt when pages are offered (§4) —
in short: the answer stays Markdown and must make sense without the page; **what the person
asks to see in the answer is a page, not an HTML file opened with `show`** (3.8.1: without
this a model wrote a file and showed it, and the person got a card to open instead of the thing
they asked for); **what has to run is not a page** — the model says a page cannot run anything
and, where it has `write` and `show`, writes an HTML file and shows that, which a client runs
in its sealed viewer; a page is a complete
document in an `html-view` fence with a short title, one page per fence; it is **static** — HTML,
CSS and inline SVG, nothing that runs and nothing loaded from anywhere; a chart is inline SVG the
model writes out, shapes and numbers it worked out itself; tables and layout are CSS; colours
come from the frame's variables so the page follows light and dark.
**The frame's variables**, set on the page's root by the client that shows it, always used with
a fallback (`pages.variables`):
| Variable | Is |
|---|---|
| `--page-bg` | the background the page sits on |
| `--page-ink` | text |
| `--page-muted` | secondary text, axis labels |
| `--page-accent` | the one accent colour: a series, a highlight |
| `--page-line` | rules, borders, grid lines |
## 3. A reader that cannot show it
- **A client that does not render pages** (a terminal, a phone, a notification) shows in the
page's place the note `pages.note` — *This answer has a page: {{title}}* — and may add where it
can be seen (`pages.where`). It never shows the page's source as if it were the answer.
- **Anything that reads a reply as text** — search, a title, read-aloud, compaction, a summary,
a preview, the plain-text form of a report — sees each page as the one line
**`[page: {{title}}]`** (`pages.projection`) in its place, on a line of its own. The **text
projection** of a reply is the reply with every page replaced so; everything else is unchanged.
- The model's own earlier replies go back to it as it wrote them (the prefix stays still,
`context.md` §10); the projection is for readers, not for the conversation.
## 4. When it is offered
All of these, or the block is not in the prompt and a page fence is an ordinary code block:
1. **the instance's switch** is on (off by default: the feature is experimental);
2. **the model's flag** `html_pages` is true (`models/schema.json`; false by default — a model
that cannot write a working page is simply not asked to);
3. **the chat's switch** is on. A scheduled run has no chat to switch: for a run, the instance
and the model decide — so a report may carry a chart.
And never, whatever the switches say:
- to **a subagent** (its reply is read by an agent, not shown);
- in **the phone assistant** (spoken, and shown on a small screen);
- in **an agent chat** — a session on a device, served by the CLI, the terminal's included: the
CLI is never offered it and never offers it. (A terminal still *reads* replies that have
pages — a report, a chat seen over the link — and shows the note of §3.)
## 5. Switched on or off during a chat
The system prompt of a chat is not rebuilt (`context.md` §10). When the chat's switch changes
after the prompt was made, the model is told by a line of the session note on the next user
message: `context.note.pages_on` — with the block's text as `{{pages_text}}` — or
`context.note.pages_off`. The instance's switch and the model's flag are settled when the prompt
is made; a change of those reaches a chat the same way, as the chat's switch going off or
becoming available.
## 6. A page is static
**Everywhere, in every client: HTML, CSS and inline SVG — nothing that runs, nothing that
reaches anywhere.** A frame with scripts on cannot be sealed by policy alone: a script can still
send data out (a WebRTC datagram to a server it chooses), and even without script a document can
make the browser look a name up (`<link rel="dns-prefetch">`, `preconnect`, `prefetch`). So the
rule is about the document, not only the frame around it (`loop.json` `pages.static`;
`conformance/pages.json`, `show: static`):
- **No script of any kind**: no `<script>`, no event-handler attribute (`on…`), no
`javascript:` address.
- **Only the listed elements** (`pages.static.elements`: text, lists, tables, figures, `style`,
and the SVG shapes) — so no `<link>`, `<meta>`, `<base>`, no frames (`iframe`, `frame`,
`embed`, `object`), no media (`audio`, `video`, `source`, `track`, `canvas`), no forms
(`form`, `input`, `button`, `select`, `textarea`), no `<template>`, `<slot>`, `<foreignObject>`.
- **Only the listed attributes** (`pages.static.attributes`): presentation and structure.
- **No address but two**: `#fragment` (a link or a reference within the page) and an inline
`data:image/png|jpeg|gif|webp;base64,…` image. Nothing else in `href`, `src`, `xlink:href` or
any other attribute — no `http:`, `https:`, `//host`, relative paths, `data:` of another kind.
- **CSS that fetches nothing**: no `@import`, and no `url(…)` other than `url(#fragment)` or
such an inline image — in a `<style>` element and in a `style` attribute alike.
A chart is therefore **inline SVG the model writes out**: bars, lines and pie slices as SVG
shapes, with the numbers it computed; a table is a table, styled with CSS.
**What a client that shows pages must do**, all of it:
1. **Rebuild the document from the allow-list** before showing it: parse what the model wrote,
keep the listed elements and attributes and the two kinds of address, drop everything else
(the element with its content for `script`, `style` that fetches, and the forbidden
elements; the attribute alone for a forbidden attribute). What is shown is the rebuilt
document, never the model's text as it came.
2. Show it in a **frame of its own origin with scripts off** — nothing allowed to the frame:
no script, no forms, no pop-ups, no navigation of itself or its parent, no cookie or storage
of the app's, no network.
3. Give it the five variables, a **fixed height with its own scrolling** (a static document
cannot report its height), and an **Open larger** control that shows the same rebuilt
document larger, in place, under the same rules.
**A client that cannot guarantee all of this shows the note of §3 instead** — a terminal, a
phone, and any client whose frame cannot be held to it. A page never reaches the app that shows
it, and never reaches anywhere else.
+12
View File
@@ -26,6 +26,18 @@
"job_stop": "allow",
"job_send": "allow",
"report": "allow",
"report_write": "allow",
"team_add": "allow",
"team_send": "allow",
"team_read": "allow",
"team_stop": "allow",
"team_whoami": "allow",
"team_finish": "allow",
"team_findings": "allow",
"team_request": "allow",
"team_decide": "allow",
"team_assign": "allow",
"team_replace": "allow",
"web_search": "allow",
"memory": "allow",
"session_search": "allow",
+2 -1
View File
@@ -32,7 +32,8 @@
"read": "rules",
"write": "allow only for files under the plans directory; anything else is refused",
"execute": "only what the rules already allow; anything else is refused",
"interact": "rules"
"interact": "rules",
"refused": "Plan mode: nothing changes but the plan. Put what this would do into the plan with plan_write or plan_update; it can be done once the person approves the plan."
}
},
"unattended": "With nobody to answer, whatever a mode would ask is refused instead, and the model is told so up front (prompts/modes/unattended.md)."
+69
View File
@@ -0,0 +1,69 @@
# Permission rules: which one decides
Spec 3.8.0. The rules are data (`defaults.json`, the person's own config, a project's, and those
made while a session runs); the modes say what happens to a call no rule settles (`modes.json`);
the hardline is under all of it (`hardline.json`). This says **which rule decides a call when
several match** — in both implementations, for a rule a person typed into a file exactly as for
one a menu wrote. Cases: `conformance/rules.json`.
## 1. A rule, and where it was made
A rule is `{ permission, pattern, action }`: the permission key (a tool's access; `*` is every
key), a pattern over what the call asks for (a command line, a path, an address; `*` is
anything), and `allow`, `ask` or `deny`. Every rule has a **layer**, by where it was made:
| Layer | Is | Read |
|---|---|---|
| `default` | the rules every session starts from (`defaults.json`) | first |
| `user` | the person's own configuration — theirs alone, on their machine or their account | then |
| `project` | a project's configuration (a trusted project's `.agent/config.yaml`; the server: none) | then |
| `made` | made during the session: an **"always" answer** to an approval card, or a rule **set in a menu** | last |
Within a layer, rules are read in the order they are written.
## 2. The rule that decides
For a call's permission and what it asks for, among the rules that match both:
1. **The last one read is the candidate** — later layers after earlier ones, later lines after
earlier ones.
A candidate from the `project` or `made` layer then gives way to whichever of these is stricter
than it (`deny` over `ask` over `allow`) — the strictest of them decides:
2. **A narrower rule.** A rule is *narrower* than another when everything its permission and
pattern take in, the other's take in too, and they are not the same (`read *.env` under
`read *`; `read *` under `* *`). Any matching rule of the `default`, `user` or `project` layer
that is narrower than the candidate counts. So `read: allow` in a project leaves
`read *.env: ask` asking, and `bash: allow` leaves `bash "git push *": ask`: a later, broader
rule changes what a broader rule decided, never what somebody wrote for the narrower case. To
allow the narrow thing, name it.
3. **The person's own answer.** What the `user` layer alone says of the call — its last matching
rule, of any breadth. A project, an "always" answer and a menu cannot loosen what the person's
own configuration says.
4. **A written deny, for an "always" answer.** When the candidate was made by an "always" answer:
the last matching rule of the `default`, `user` or `project` layer, if it denies.
A candidate from the `default` or `user` layer decides as it is: the person's own file is read
last-match-wins, as it always was. Where no rule matches, the call is asked about or allowed by
its class and the mode.
Several patterns in one call (a command line of several commands, several paths) are each
decided this way, and the strictest answer is the call's.
## 3. Making a rule
When a person makes a rule — an "always" answer, or one set in a menu:
- **Choosing the action already in force changes nothing**: no rule is added and nothing is
written. (The action in force is what §2 gives for the new rule's own permission and pattern.)
- **A rule that could never take effect is refused**, naming the rule in its way: a `user` rule,
or a written `deny` of any layer, that is stricter and takes in *all* of the new rule (the new
rule is the same as it, or narrower). It is changed where it was written.
- Otherwise the rule is **made**: in force at once, and — where the implementation saves it (a
trusted project's configuration) — saved as a `project` rule. Because §2 treats `made` and
`project` alike, the session it was made in and the next start from the saved file decide
every call the same way.
- The person is told what it did: where it holds, whether it was saved, and **which stricter
rules still apply** — every rule of the `default`, `user` or `project` layer that is narrower
than the new rule and stricter than it.
+99
View File
@@ -0,0 +1,99 @@
# Phone actions
Spec 3.6.0. `phone_action` (`tools/phone_action.json`) lets a chat's model do something on the
person's phone — set an alarm, start a route, draft a message — when the person is writing from the
LLeMbas app on that phone. The model proposes; **the app shows the person a card and does nothing
until they confirm it there**; the app carries it out with the phone's own apps and answers what
happened, which is the call's result. The texts and numbers are `loop.json` `phone`.
It is the server's tool alone (`scope: llembas`, `sessions: chat`). The CLI never offers it: a
terminal has no phone behind it.
## 1. Who offers it
- **The capability.** The app declares `phone_actions` (`loop.json` `phone.capability`) with each
message it sends. A message sent from anywhere else — the web, Desktop, another app — declares
nothing.
- **`requires: phone`.** The tool is offered in a chat once a message has been sent to it with the
capability, and stays offered for the rest of the chat (the tool list is the session's,
`context.md` §10): a chat started on the phone and continued on the web keeps the tool, and a web
chat continued on the phone gains it from that message on (the list changes once, so the prompt
is made again once).
- **Unavailable.** A call answers the tool's `unavailable` text, word for word, when the message
being answered was not sent with the capability (there is no phone to confirm on), and in a chat
nobody attends (a schedule's, a subagent's). Nothing reaches any phone then.
- **Confirm: always.** Every call is put to the person, in every mode; nothing remembers an answer.
The card is the phone's own: the server never asks a second time on another screen. Its risk is
`interact`: no mode refuses it, Plan mode included, because nothing on disk changes and the
person decides on the phone.
## 2. A call
`action` is one of `phone.actions`; `summary` is the line the phone shows. Each action reads only
its `phone.fields`; anything else in the call is dropped before the phone sees it. The call is
checked before anything is sent, in this order, and the first problem is the call's result:
1. `action` not one of the actions: `texts.unknown_action` (`{{actions}}` the list, joined with
`, `).
2. The action's `phone.required`, each entry in turn: a field is present when it is not null, not
an empty string (after trimming) and not an empty list or object; a list inside the list is
present when any one of its fields is. Every entry that is missing, in order, goes in one
`texts.missing`: a field by its name, a group as its names joined with ` or `, the entries
joined with ` and ` (`add_stop needs stop and destination.`).
3. The fields present, in `phone.check` order (only those the action reads): one that is not what
it should be is `texts.bad` with `{{field}}` its name and `{{what}}` from `phone.what`:
- `time`: `HH:MM`, hours 00–23, minutes 00–59.
- `days`: a list, each one of `mon` … `sun`.
- `seconds`: an integer (never a boolean) from 1 to 86400.
- `start`, `end`: `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM` (not checked as a calendar date).
- `to`, `cc`: a list of strings, each non-empty after trimming.
- `number`: at least three digits, and nothing but digits, spaces and `+ ( ) - . / # *`.
- `destination`, `stop`: an object with numeric `lat` and `lon` together (each in its range),
or a non-empty `query`, or a non-empty `name`. `stops`: a list of such places.
- `mode`, `near`, `command`, `panel`: one of the schema's values.
- `url`: begins `http://` or `https://` (any case) and has something after it.
- `on`: a boolean.
- `values`: an object of strings.
A call that passes is the **action** the phone receives: `action`, `summary` (trimmed; the action's
name when empty) and the action's fields that are present, as the model gave them, strings trimmed.
## 3. The answer
The server waits up to `phone.wait_seconds` for the phone's answer: `status` (`done`, `declined`
or `failed`) and an optional `message`, at most `phone.message_max_chars` characters (cut there).
The call's result is the status's text — `texts.done`, `texts.declined`, `texts.failed` — and,
when there is a message, a blank line and `texts.says` with it. A status the phone does not know is
`failed`. No answer in time is `texts.no_answer`, with no message; the card goes away.
What the person pressed is theirs: **declined** means they said no, and the model is told not to
try again unless asked. **Failed** is the phone's: an app missing, a permission refused, a map app
that cannot do what was asked.
## 4. Navigation
Map apps differ, and the phone says when one cannot: the model is not told which app the person
uses.
- `navigate` starts a route to `destination` through `stops`, in order; `mode` is how the person
travels (`drive` when not said). `replace_route` replaces a route already running without the
phone asking first.
- `add_stop`: **no map app adds a stop to a running route**, so the phone plans again — from where
the person is, to `stop`, then to `destination`. The model gives `destination` as the person told
it when the route began: the tool's description tells it to keep it.
- `search_nearby` looks for `query` around the person (`near: me`) or along the running route
(`near: route`).
- `stop_navigation` ends the route where the map app allows it; one that does not answers
`failed` with why.
## 5. The other actions
- `alarm` and `timer` are the phone's clock app; `days` repeats an alarm.
- `calendar_event` opens the calendar's new-event screen filled in; the person saves it.
- `sms_draft` and `email_draft` are **drafts**: the messaging or mail app opens with them, and the
person sends. `dial` opens the dialer with the number; the person places the call.
- `open_app` names an app as the person does; `open_url` opens an address in the browser.
- `media` controls what is playing; `torch` switches the torch.
- `settings_panel` opens the phone's quick panel or page for a setting; the person changes it.
- `automation_intent` runs an automation the person made in an automation app (Tasker when `app`
is not said), by its name, with `values` as its inputs.
+108
View File
@@ -0,0 +1,108 @@
# Progress
Spec 3.4.0. **One way to say what a session is doing**, the same in every client — the web UI,
Desktop, the CLI, Android — and for every agent in it, the main agent and each subagent alike.
Before 3.4.0 each client invented its own subset from a free `status` text; that text stays, for
compatibility, and beside it goes a structured **progress** object with one of a fixed set of
**phases**. The texts are `loop.json` `progress`; the cases `conformance/progress.json`.
## 1. The object
```json
{ "phase": "running_tool", "since": 1762790400000, "tool": "bash", "what": "bun test" }
```
- **`phase`** — one of the thirteen names below, never another. A session doing nothing has no
progress: `null`.
- **`since`** — when this phase began, Unix time in **milliseconds** (an integer). A change of the
phase's data (tokens read, the rate) keeps `since`; a new phase, or the same phase for another
thing (another tool call, another model), starts a new one.
- The phase's **data**, as listed: every field named here, with these names and these types. A
field that is not known is left out (never `null`, never a guess), and the text says less.
## 2. The phases
In the order a turn usually meets them. `{{x}}` in a text is the field `x`; the texts are
`loop.json` `progress.texts`, word for word, and they are the shared i18n keys
`progress.<phase>` (and `progress.<phase>.<variant>`, `progress.reason.<reason>`,
`progress.what.<what>`) in every client's translations.
| Phase | Data | Text (`progress.texts`) |
|---|---|---|
| `queued` | `ahead?: int` — turns before it | `Queued` · with `ahead`: `Queued: {{ahead}} ahead` |
| `waiting_for_model` | `model: string` (its display name, else its id); `reason: "busy" \| "slots" \| "group"` | `Waiting for {{model}}: {{reason}}` |
| `loading_model` | `model: string` | `Loading {{model}}` |
| `reading_prompt` | `done: int`, `total: int` — prompt tokens processed of all | `Reading the prompt: {{done}} / {{total}} tokens ({{percent}}%)` · without `total`: `Reading the prompt` |
| `thinking` | — | `Thinking` |
| `writing` | `rate?: number` — tokens a second, as measured over this reply | `Writing: {{rate}} tok/s` · without `rate`: `Writing` |
| `running_tool` | `tool: string` (the tool's name); `what?: string` — the call's short title (the command, the path, the query; from 3.7.0 exactly `display.md` §1), one line, at most 80 characters | `Running {{tool}}: {{what}}` · without `what`: `Running {{tool}}` |
| `waiting_for_person` | `what: "approval" \| "question" \| "plan"`; `tool?: string` (approval: the tool asked about) | `Waiting for you: {{what}}` |
| `waiting_for_subagents` | `running: int` — subagents working or waiting now | `Waiting for subagents: {{running}} running` |
| `compacting` | — | `Compacting the conversation` |
| `retrying` | `reason: string` — the server's error, one line; `in: int` — seconds until the retry, counted down by the client from `since`; `attempt?: int` | `Retrying in {{in}} s: {{reason}}` |
| `stopped` | `reason?: "person" \| "steps" \| "budget"` | `Stopped` · with `reason`: `Stopped: {{reason}}` |
| `failed` | `reason: string` — the error, one line | `Failed: {{reason}}` |
The fixed words a field stands for:
- `reason` of `waiting_for_model` (`progress.reason`): `busy` — *it serves one request at a time
and is answering another*; `slots` — *all its slots are in use*; `group` — *its server holds
another model now*.
- `what` of `waiting_for_person` (`progress.what`): `approval` — *allow {{tool}}?* (*an approval*
without `tool`); `question` — *a question*; `plan` — *the plan*.
- `reason` of `stopped` (`progress.stopped_reason`): `person` — *by you*; `steps` — *step limit*;
`budget` — *budget*.
- `percent` is `floor(done × 100 / total)`; numbers are written as integers, `rate` with one
decimal (`12.5`), in the client's own number format.
## 3. The line a client draws
**`{{text}} · {{elapsed}}`** (`progress.line`) for every phase but `stopped` and `failed`, which
draw their text alone. `elapsed` is now − `since`, written in whole seconds as a ticking clock writes durations
(`5s`, `1m 05s`, `1h 02m`), and kept moving by the client at least once a second while the
phase lasts. `retrying`'s `in` is likewise counted down from `since` (never below 0).
Every client draws the same line for the same object — the same words, from the same keys — and
its own look around it (a spinner, a colour, a bar for `reading_prompt`). Where a line has no room
(a phone's notification, a tree row) the text alone, without `· elapsed`, is enough; nothing else
is shortened.
## 4. When each phase holds
What decides the phase, so that two implementations agree on the same moment:
- `queued` — a prompt waits behind a turn that runs (the device's turn queue; the server's per
chat). `waiting_for_model` — the turn may start but its model may not take it yet: a one-request
server answering another request (`busy`), every slot of the model held (`slots`; `team.md` §8),
another model of its one-model server in use (`group`). `loading_model` — only where the
implementation is told the model is being loaded (the server sees it; a device that cannot tell
skips it).
- `reading_prompt` — the request is sent and no output has come; with `done`/`total` from the
server's prompt-progress frames (`quirks.json` `prompt-progress`), without them where none come.
- `thinking` — reasoning streams; `writing` — reply text (or a tool call's arguments) streams.
- `running_tool` — from a tool call's start to its end; with calls in parallel, the one that
started first. `waiting_for_person` — an approval card, a question or a plan to approve is open
for this agent. `waiting_for_subagents` — the agent's turn waits on subagents: a `task` call in
the foreground, or the main agent with nothing to do but its subagents' reports (`subagents.md`
§9).
- `compacting` — a compaction runs. `retrying` — a failed request will be sent again after a wait.
- `stopped` / `failed` — the turn ended other than by finishing: stopped by the person, a step limit
or a budget; failed with an error. They are the last progress of that turn and stay until the
next one begins; a turn that finished normally ends with `null`. From 3.7.0 their line also stays on
the finished reply itself (`display.md` §4).
## 5. Where it is sent
- **`/api/v2` (LLeMbas)**: every frame of a chat's stream that carries the `status` text carries
`progress` beside it — the object, or `null` — and a frame is sent when the progress changes:
a new phase at once, a data-only change (`done`, `rate`) at most four times a second. `status`
stays as it was, its text unchanged, for clients that do not read `progress`.
- **The link (`acp.md`, capability `progress`)**: the `phase` event `{ progress, agent? }` —
`agent` the subagent's id (`subagents.md` §5) when the progress is a subagent's, absent for the
main agent's — under the same pacing; `progress` in `_lembas/session/status`, so a client
reattaching draws it at once. The device sends it; the server passes it on in `/api/v2` as its
own.
- **The subagent tree** (`subagents.md` §12): every agent carries its current `progress`.
A client that reads `progress` draws it and ignores `status`; one that does not, draws `status` as
before.
+1 -1
View File
@@ -2,7 +2,7 @@
kept by the agent, and how git is used there is the user's answer, asked once and written down. -->
## AGENTS.md
This project has no AGENTS.md yet. It is the file every later session here starts from, so making it is part of the work:
- Make it at the first natural pause in real work, once you know what the project is — not before you have done anything, and not in plan mode. It goes at the project root: {{root}}/AGENTS.md.
- Make it at the first natural pause in real work, once you know what the project is — not before you have done anything, and not in plan mode. It goes at the project root: `AGENTS.md`.
- Before you write it, ask the user how git is to be used here, with ask_user, in one call: {{git_question}} Mark the options you would recommend.
- Write their answer under a "## Git" heading. Above it, say briefly what the project is, how to build, run and test it, and the conventions that matter.
- If the user does not want the file, do not bring it up again this session.
+11
View File
@@ -0,0 +1,11 @@
<!-- Spec 3.8.0 (pages.md); 3.8.1: a page for what is to be seen, a shown file for what has to run. Offered only when the instance, the model and the chat all say so; never
to a subagent, the phone assistant or an agent chat. The fence word, the variables and what a
static page may hold are loop.json `pages`. -->
- Your answer is Markdown, as always. Where seeing answers better than reading — a chart, a comparison laid out as a table with colour, a diagram, a timeline — you may add a page to it: a complete, self-contained HTML document in a fenced block whose info string is `html-view` followed by a short title, for example ```html-view Monthly sales. One page per block. It is shown at that place in your answer, in a sealed frame of a fixed height that scrolls.
- When the user asks to see something in your answer — "show me", "draw", "visualise", a chart, a diagram, a table laid out — and it can be drawn without running anything, write it as a page here. Do not write it to an HTML file and open that with `show` instead: a page is what appears in the conversation, at the place you put it, and stays there when the conversation is opened again.
- A page is static: HTML, CSS and inline SVG only. Nothing in it runs and nothing is loaded: no `<script>` and no event handlers; no `<link>`, `<meta>`, `<base>`, frames, objects, audio, video, canvas or forms; no address anywhere except `#fragment` and an inline `data:image/…` picture. Anything else is removed before the page is shown.
- So a page cannot be interactive. When what is asked for has to run — a calculator, a game, a clock, an animation driven by script, anything that reacts to a click or to typing — do not write it as a page, and do not pretend one can do it: say in a sentence that a page in an answer cannot run anything, and, if you have the `write` and `show` tools, write it as an HTML file and open that with `show`, where the user can run it in a sealed viewer.
- Draw a chart as inline SVG you write out yourself: work the numbers out first, then write the bars, lines or slices as SVG shapes with their labels. Lay out and style tables and text with CSS in a `<style>` element — no `@import`, no `url(…)` to anywhere.
- Follow the reader's light or dark theme with the frame's CSS variables, always with a fallback: --page-bg (background), --page-ink (text), --page-muted (secondary text), --page-accent (the accent colour) and --page-line (rules and borders) — for example `color: var(--page-ink, #222)`.
- If the page itself contains a line of three backticks, open and close its block with four.
- Not every reader sees the page: on a phone or in a terminal there is only a note with its title. So the Markdown around it must make sense without it — say what the page shows, and put the conclusion in words. Add a page only when it earns its place; to change one, write the whole new page in a new block.
-9
View File
@@ -1,9 +0,0 @@
<!-- From LLeMbas prompts core.prototypes (© Jaroslav Beneš, relicensed MIT). {{prototype_sources}} is the
one sentence that differs with the instance's network setting; {{prototype_surface}} says where the
prototype is seen on this surface (rendered live in the web UI; saved as a file in a terminal). -->
- You can show live HTML. Write a complete HTML page in a fenced block whose language is `prototype-chat` or `prototype-page`, with a short title on the same line — for example ```prototype-chat Monthly sales. It runs in the reader's browser, sealed off from everything else. {{prototype_surface}}
- `prototype-chat` is shown inside your message. Use it for small things: a chart, a diagram, a calculator, a styled table or a short summary card. Keep it under about 600 pixels tall, and do not size anything with `100vh`.
- `prototype-page` opens in a panel beside the conversation, with a desktop and a phone view. Use it for anything that is a page or a screen: a website or landing-page design, an app mock-up, a dashboard, a long report, a game.
- {{prototype_sources}}
- To match the reader's theme, use these CSS variables, always with a fallback: --lembas-bg, --lembas-surface, --lembas-ink, --lembas-ink-muted, --lembas-accent and --lembas-border — for example `color: var(--lembas-ink, #222)`.
- Make one only when seeing it answers better than reading, and say in a sentence or two what it shows. To change one, write the whole new version in a new block.
+1 -1
View File
@@ -1,5 +1,5 @@
<!-- LLeMbas CLI: the subagent's standing, said once at the end of its system prompt in place of
the mode text; LLeMbas's helper says the same. The variables are what differs per run. -->
the mode text; LLeMbas's subagent says the same. The variables are what differs per run. -->
You are the "{{name}}" subagent. You work for the main agent, not for the user directly, on one task it gave you; you cannot ask the user anything. {{instructions}}
Your final reply is your report to the main agent — make it complete on its own: the result, then the evidence (file:line), then anything you could not settle.{{report}}{{read_only}}
+14
View File
@@ -0,0 +1,14 @@
<!-- LLeMbas CLI and LLeMbas, spec 3.2.0 (team.md), 3.4.0 (subagents.md §5–§13): how the main agent
leads its subagents, in the system prompt whenever the team tools are offered. Constant: the
size the person allows comes in a session note, never here. -->
# Leading subagents
You are the main agent of this session. You can add subagents with team_add: agents that work in the background, each on the part of the work it owns, while you lead. Only you add, assign, replace and stop them. A small job you may do yourself. Once you have a subagent you manage and no longer do the work: tools that change things are refused to you, and reading stays yours, for review.
- Plan first: what the goal is, what the parts are, and what each one needs from the others. Split by area of ownership, not by step, so that one subagent owns a thing from start to finish.
- Name each subagent after what it owns and give it a position (`role`). Brief it so that it can work without you: what to do, what done means, what to leave alone, and what to report.
- Keep the tree flat while it is small — up to six or eight subagents, each reporting to you. Beyond that, add a sub-manager for each area (`lead: true`) and place that area's subagents under it (`parent`); it directs them and reports to you, and you still add and stop every one.
- A subagent's mode is yours by default and never looser. Give a stricter one where the person wants less done unasked; with it you may give `request` options, and you decide its requests with team_decide — allow only what the task needs.
- Keep within the size the person allows, which a session note tells you; when it says slots are open, fill them. Stop a subagent whose part is done or no longer needed, to make room.
- Coordinate through the room: team_send to the subagent who owns a thing, `all` only for what everyone needs. team_read shows the tree and the room when you need to look; nothing from it reaches you unasked except reports, requests and messages addressed to you.
- A subagent whose context fills saves its findings and ends. Read them with team_findings, then replace it (team_replace) if its part is not done.
- Step in when a subagent is stuck, when two disagree, or when the plan has to change: decide, and tell those it concerns (team_assign for new work).
- Review every report against what you asked for — read the work itself where it matters — and send back what is not done. Then give your own answer to the person.
+16
View File
@@ -0,0 +1,16 @@
<!-- LLeMbas CLI and LLeMbas, spec 3.2.0 (team.md), 3.4.0 (subagents.md §13): a subagent's standing,
said once at the end of its system prompt in place of blocks/subagent.md. The variables are what
differs per subagent; each stands on a line of its own, so no punctuation of theirs matters. -->
You are "{{name}}" ({{id}}), a subagent of this session, and you report to "{{manager}}".
Your position: {{role}}
The team's goal: {{goal}}
{{instructions}}
You work for your parent on the part you own, and you cannot ask the person anything: ask your parent with team_send to `parent`. Only the main agent (`lead`) adds, assigns and stops subagents. Other subagents own other parts. Message the one who owns a thing when you need it from them, and `all` only for what everyone needs; messages to you arrive as you work. team_read shows the tree and the room; team_whoami shows who you are, your mode and how full your context is.
Your context is limited and you do not compact: write what you find with team_findings as you go. When your context fills you are told, and you have one last turn to save your findings and tell your parent.
When your task is done, call team_finish with your report to "{{manager}}" — make it complete on its own: the result, then the evidence (file:line), then anything you could not settle. A final reply without it is also your report, and a message may then wake you again.{{read_only}}
{{lead}}
@@ -0,0 +1,8 @@
<!-- LLeMbas CLI and LLeMbas, spec 3.4.0 (subagents.md §5, §13): what a sub-manager is told, in
place of the whole of blocks/team_lead.md that a member with `lead: true` got in 3.2.0. -->
# Directing an area
You are a sub-manager: the main agent places subagents under you, and you direct them. You do not add, assign, replace or stop subagents — ask the main agent with team_send to `lead` when your area needs one more, another task for one, or one stopped. You manage and no longer do the work: tools that change things are refused to you, and reading stays yours, for review.
- Split your area's work among the subagents under you, tell each what it owns with team_send, and keep them from overlapping.
- Their reports come to you. Review each against what you asked — read the work itself where it matters — and send back what is not done.
- Read the findings of a subagent under you with team_findings, especially of one that ran out of context; tell the main agent whether it needs replacing.
- When your area is done, call team_finish with your report to the main agent.
+34 -9
View File
@@ -182,15 +182,6 @@
"llembas": [],
"llembas_text": "identical"
},
"blocks/prototypes.md": {
"scope": "cli",
"llembas": [],
"variables": {
"prototype_sources": "whether the page may load anything over https (the instance's network setting), as one sentence",
"prototype_surface": "where it is seen on this surface: empty in the web UI, which renders it; in a terminal, that it is saved as a file the person can open, and that the web UI renders it"
},
"why": "spec 3.0.0: a chat has no prototypes (show replaces them); the CLI keeps the text while a client still offers them over the link"
},
"blocks/library.md": {
"scope": "cli",
"llembas": [],
@@ -240,6 +231,40 @@
"show": "when the session has a screen (`show` is offered): the sentence saying to open a file the user should see with show — a page, a chart, a document you made — rather than pasting it; otherwise empty",
"python": "when `python` is offered: the sentence saying quick calculations and file work can be done in Python in the user's browser, and that it cannot run when no browser page is open; otherwise empty"
}
},
"blocks/team_lead.md": {
"scope": "shared",
"llembas": [],
"llembas_text": "identical",
"why": "spec 3.2.0: LLeMbas reads it from the vendored spec (harness_spec.prompt), not from a fragment"
},
"blocks/team_member.md": {
"scope": "shared",
"llembas": [],
"llembas_text": "identical",
"why": "spec 3.2.0, 3.4.0: LLeMbas reads it from the vendored spec (harness_spec.prompt), not from a fragment",
"variables": {
"name": "the member's name in the team",
"role": "its position, one line (team_add's role)",
"manager": "its parent: lead, or the sub-manager it was placed under",
"goal": "the team's goal as it was when the member was added: the `goal` its team_add gave, else its manager's (team.md §4)",
"instructions": "its agent's own instructions (prompts/agents/<name>.md for a built-in one), as in blocks/subagent.md",
"read_only": "in plan mode: the sentence saying it can read and search but change nothing (as in blocks/subagent.md); otherwise empty",
"lead": "for a sub-manager (added with `lead: true`): the whole of blocks/team_submanager.md (spec 3.4.0; before, blocks/team_lead.md); otherwise empty",
"id": "the subagent's id (s1, s2, …; spec 3.4.0)"
}
},
"blocks/team_submanager.md": {
"scope": "shared",
"llembas": [],
"llembas_text": "identical",
"why": "spec 3.4.0: LLeMbas reads it from the vendored spec (harness_spec.prompt), not from a fragment"
},
"blocks/html-pages.md": {
"scope": "shared",
"llembas": [],
"llembas_text": "identical",
"why": "spec 3.8.0 (pages.md): takes the place of blocks/prototypes.md, the 1.x text the CLI alone had kept. LLeMbas reads it from the vendored spec (harness_spec.prompt), not from a fragment; the CLI never sends it (pages.md §4: an agent chat is never offered pages)."
}
}
}
-2
View File
@@ -23,6 +23,4 @@ Leave out pleasantries, retracted ideas and anything already superseded. Do not
{{previous_summary}}
## Transcript
{{transcript}}
+1 -1
View File
@@ -1,6 +1,6 @@
<!-- Source: OpenCode command/template/initialize.txt (MIT, © 2025 opencode), shortened, and made to
ask about git the way blocks/agents-missing.md does (LLeMbas CLI's /init). -->
Create or update `AGENTS.md` at the project root, {{root}}/AGENTS.md: the file every later session here starts from. Every line should answer "would an agent likely get this wrong without being told?" — if not, leave it out.
Create or update `AGENTS.md` at the project root: the file every later session here starts from. Every line should answer "would an agent likely get this wrong without being told?" — if not, leave it out.
{{focus}}
+3 -2
View File
@@ -2,16 +2,17 @@
"about": "What OpenAI-compatible servers really do, and how both harnesses cope. Each quirk is detected, handled, and — where marked — learned, so the next request does not trip it again. The CLI keeps what it learned in ~/.local/state/lembas/learned.json; LLeMbas on the model row or in process memory.",
"quirks": [
{ "id": "stream-options-refused", "servers": "older llama.cpp, some proxies", "symptom": "400 or 422 to a request carrying stream_options", "handling": "retry once without it, before anything was streamed", "learned": true },
{ "id": "effort-refused", "servers": "llama.cpp chat templates (Qwen3.8 refuses high)", "symptom": "an error whose text names the effort and says unexpected or supported (conformance/effort.json)", "handling": "retry once without an effort, before anything was streamed; narrow the model's efforts to those the message advertises", "learned": true },
{ "id": "effort-refused", "servers": "llama.cpp chat templates (Qwen3.8 refuses high)", "symptom": "an error whose text names the effort and says unexpected or supported (conformance/effort.json)", "handling": "retry once without an effort (and without enable_thinking), before anything was streamed; narrow the model's efforts to those the message advertises. A narrowed list keeps the level off when the model has thinking_switch (models/schema.json levels)", "learned": true },
{ "id": "effort-placement", "servers": "llama.cpp", "symptom": "a top-level reasoning_effort is silently dropped", "handling": "send it top-level and as chat_template_kwargs.reasoning_effort (effort_style both)", "learned": false },
{ "id": "prompt-progress", "servers": "llama.cpp with return_progress", "symptom": "prompt_progress {total, cache, processed, time_ms} frames before the reply", "handling": "ask for it, show how far the prompt has been read; a 400 to the field is learned and it is not asked again", "learned": true },
{ "id": "reasoning-fields", "servers": "llama.cpp, vLLM, DeepSeek, OpenRouter", "symptom": "reasoning arrives as reasoning_content, reasoning, or inline <think>/<thinking>/<reasoning> tags (conformance/think.json)", "handling": "all three read as reasoning; reasoning is never sent back as context", "learned": false },
{ "id": "reasoning-fields", "servers": "llama.cpp, vLLM, DeepSeek, OpenRouter", "symptom": "reasoning arrives as reasoning_content, reasoning, or inline <think>/<thinking>/<reasoning> tags (conformance/think.json)", "handling": "all three read as reasoning. From spec 3.2.0 an assistant message of the current turn carries its reasoning back as reasoning_content, and earlier turns' carry none (context.md §8); inline tags are never sent back as text", "learned": false },
{ "id": "error-in-200-stream", "servers": "llama.cpp", "symptom": "an error object inside a 200 event stream, sometimes as an unterminated last line", "handling": "read as the error it is, not as an empty reply", "learned": false },
{ "id": "tool-call-without-index", "servers": "some llama.cpp builds", "symptom": "tool-call fragments with no index", "handling": "fragments without an index continue the last call", "learned": false },
{ "id": "swap-banner", "servers": "llama-swap", "symptom": "a loading banner streamed before the reply while the model loads", "handling": "not shown as the reply", "learned": false },
{ "id": "model-unloaded", "servers": "llama-swap", "symptom": "a 'model unloaded' frame mid-reply, when another client loaded a different model", "handling": "treated as a server error: retried once", "learned": false },
{ "id": "zero-usage", "servers": "several", "symptom": "a usage block of all zeros", "handling": "ignored; the count is estimated (marked ~) instead", "learned": false },
{ "id": "no-context-length", "servers": "llama-swap /v1/models, most OpenAI-compatible servers", "symptom": "/models lists ids without a context length", "handling": "ask llama-server's /props (through llama-swap's /upstream/<model>), Ollama's /api/show, else unknown — never assume one", "learned": true },
{ "id": "thinking-default", "servers": "llama.cpp, vLLM and SGLang serving Qwen3.x and Nemotron 3.x", "symptom": "a request that sends no effort still thinks, at the effort the server was started with — no effort is not no thinking", "handling": "thinking is switched off only by chat_template_kwargs.enable_thinking: false, on a model marked thinking_switch (models/schema.json levels); a request's own reasoning_effort overrides the server's default, and a value the template does not know is effort-refused", "learned": false },
{ "id": "max-completion-tokens", "servers": "OpenAI reasoning models", "symptom": "max_tokens refused", "handling": "send max_completion_tokens where configured", "learned": false }
]
}
+129
View File
@@ -0,0 +1,129 @@
# Reports
Spec 3.8.0. **A schedule's run does not answer into a conversation: it files a report, or it does
not.** Before 3.8.0 every run's answer was a message — a chat per run, a notification per run — and
a run with nothing to say hid behind the word `[SILENT]`. Now the model writes a report with a tool
when there is something to tell, the schedule's **notify when** says when that is, and a run
without a report leaves one line in the schedule's history. The tool is `tools/report_write.json`;
the values and texts `loop.json` `scheduled.notify`; the cases `conformance/reports.json`. (The
subagents' `report` tool is another thing and keeps its name.)
## 1. The tool
`report_write(title, body, summary, importance?)`:
- `title` — what the report is about, as a headline; `body` — the report itself, in Markdown;
`summary` — one or two sentences a person reads in a list or a notification; `importance` —
`normal` (the default) or `high` (the person should look now).
- **A run files at most one report.** A second call in the same run **replaces** the first: the
run's report is the last one written. The result says which happened, word for word
(`scheduled.notify.result.filed`, `.replaced`), and both tell the model the same thing next:
*the report is filed; end with one short line for the run's history.*
- It is a tool of the session (`risk: interact`), allowed without asking: it writes nothing on
the machine and reaches nobody but the schedule's owner.
## 2. When it is offered: `requires: scheduled`
`report_write` is offered **only in a session a schedule opened for its run**, and only when the
schedule's notify-when is not `never` (§3). In such a session a turn that is not the schedule's —
the person writing into a run's chat afterwards — is not a run: the tool stays in the list (the
list of a session does not change, `context.md` §10 rule 4) and answers its `unavailable` text,
word for word. Everywhere else — a chat, an agent chat, a subagent, the phone assistant — it is
not in the list at all.
| The session | Notify when | The turn | `report_write` |
|---|---|---|---|
| a schedule's run | `always`, `when` | the run | offered |
| a schedule's run | `always`, `when` | the person's own | `unavailable` |
| a schedule's run | `never` | any | not in the list |
| anything else | — | any | not in the list |
A subagent of a run is never offered it: the run's own agent files the report.
## 3. Notify when
A schedule says when its owner wants to hear from it (`scheduled.notify.values`):
| Value | The form says | The model is told | The tool |
|---|---|---|---|
| `always` | Every run | write a report every run — also when nothing was found, and when nothing matters | offered |
| `when` | When… — with the person's own words; `scheduled.notify.default_condition` (*something needs my attention*) when they wrote none | write a report **only** when the condition holds; otherwise end with one line saying why not | offered |
| `never` | Never | nothing about reports | not offered |
A schedule that says nothing is `when` with the default condition (`scheduled.notify.default`).
The side that creates a schedule may choose otherwise for **a schedule that runs once**: a
person who asks for one thing, once, wants its answer, so a one-shot may be created as `always`
(`scheduled.notify.one_shot_default`). The value is the schedule's from then on, and is always
sent and stored as one of the three — only a schedule that truly carries none is read as `when`.
**The instruction** is `scheduled.notify.texts.<value>`, word for word, `{{condition}}` the
person's words (trimmed, one line, without a full stop at the end) — `never` has no text. It is
part of **the run's prompt**: the server composes that prompt for every run — the schedule's
instruction, the run's time, then this — and a device that runs the turn adds nothing (`acp.md`
*Scheduled work*). So one side writes the words, and a model reads the same ones wherever it runs.
## 4. What a run leaves
When the run ends, by what happened in it:
| Notify when | `report_write` was called | The run leaves |
|---|---|---|
| any | yes | **the report** (the last one written), and the history line |
| `always` | no | the final answer **filed as the report** — title the schedule's, body the answer, summary the answer's first paragraph on one line (as written, white space collapsed) cut to `scheduled.notify.summary_max` characters with `…`, importance `normal` — unless the answer is empty: then no report, and the note `scheduled.texts.no_reply` |
| `when` | no | no report; the history line says why not (the model's own line) |
| `never` | — | no report; the history line |
**The history line** (`note`) is the final answer's first line that is not blank, trimmed and cut
to `scheduled.notify.note_max` characters with `…`; `scheduled.texts.no_reply` where there is
none. A run that failed or was cancelled leaves its failure, as before, and no report — unless
one was already written, which is kept: what the model found is not thrown away with the error.
**Notifications come from the report**, not from the run: one notification for a report (its
`title`; `importance: high` may be shown as urgent), none for a run without one. A failed run
still says it failed.
## 5. `[SILENT]` is retired
The sentinel of 3.5.0 (`scheduled.sentinel`) is no longer told to a model: the notify-when
texts replace the hint — but for a run on a device that has no `reports` capability (§6). A reply that still carries it — an older prompt, a model's habit — is
read as **no report**: its sentinel lines (first or last line, as `conformance/silent.json`
strips them) are taken out before the history line is made, and under `always` an answer that is
only the sentinel files nothing. The run's status is never `silent` under 3.8.0; a device that
still answers `silent` (§6) is read as `ok` without a report.
## 6. A run on a linked computer
A schedule may run as an agent turn on a device (`acp.md` *Scheduled work on a linked computer*).
The report travels **with the turn's answer** — there is no method of its own:
- The server marks the turn: `scheduled.notify` (`always`, `when` or `never`) in `_meta.lembas`
of `session/new` and `session/prompt`, beside the schedule's ids. The prompt it sends already
carries the instruction (§3).
- A device with the capability **`reports`** offers `report_write` to the run's model by §2 —
the tool is the device's own, it keeps the last report written in the turn — and puts it into
the prompt's answer: `_meta.lembas.scheduled.report: { title, body, summary, importance }`,
absent when none was written. Its `status` is `ok`, `failed` or `cancelled`; `text` the final
answer.
- The server then applies §4 to that answer exactly as to a run of its own: the `always`
fallback, the history line and the notification are the server's, never the device's.
- A device **without** the capability (before 3.8.0) is not sent `notify`, offers no tool, and
**must not be sent an instruction that names `report_write`** — its model would be told to
call a tool it does not have. Its run's prompt is the one of 3.5.0 instead: for `when`, the
`[SILENT]` hint as it was (say the sentinel alone when there is nothing to tell); for `always`
and `never`, no hint at all. This is the one place the sentinel is still told to a model. The
server files by §4 from its `text` alone — under `always` the answer is the report; under
`when` there is none, and the model's closing line is the note. `silent` from such a device is
`ok` without a report.
Why with the answer, and not a call relayed while the turn runs: a report is the run's *outcome*.
Carried in the answer it is atomic with the run's end — a link that drops mid-turn cannot leave a
report without a run, a prompt sent again gets the same answer with the same report (`turnId`),
and "the second call replaces the first" needs no protocol at all.
## 7. Reading reports
Reports are the server's: it stores them (the owner, the schedule and run, title, summary, body,
importance, unread, the chat a reply continues in) and lists them for every client over
`/api/v2/reports`. A report's body is Markdown as a reply is, and may carry pages (`pages.md`),
which a scheduled run may be offered. Replying to a report continues it as a conversation that
stays with the report.
+362
View File
@@ -0,0 +1,362 @@
# Subagents
Spec 3.3.0; §5–§13 spec 3.4.0. **Which model a subagent runs on, and when subagents are offered at all.** A
**subagent** is any agent a session's agent starts to work for it: a `task` subagent (in the
foreground or as a background job) and a team's member (`team.md`) alike. The same rules in a chat
on the server and in an agent session on a device, in both projects. The texts are `loop.json`
`subagents`; the cases `conformance/subagents.json`.
## 1. The word
**Subagent** is the word in every text a person or a model reads: the UI (the web UI, Desktop,
Android, the CLI, the admin pages), the prompt texts and the tool texts. A team's members are
subagents too. The word *helper* is retired. Tool names, their former names (`aliases`) and
stored identifiers do not change.
## 2. The model a subagent runs on
**The session's own model**, always — unless **the person has named another model** in this
session. Nothing else chooses one: there is **no setting** for a subagent's model anywhere — not
in a chat, not in a person's or an instance's settings, not in the configuration, and an agent
definition's own `model` (the CLI's agent files) is not used for a subagent either.
- **Named** means: in a message **the person typed** in this session, the model's served id, its
id at its connection, or its display name occurs as a whole word, letters compared without case.
Only the person's own words count — never the model's text, a tool's output, a file, a note, a
job's or a team's marked message, or a subagent's report. A message that was compacted away
still counts: what the person named stays named for the whole session.
- **A whole word**: the character before the name is not a letter, a digit, `_`, `-`, `/`, `.` or
`:`; the character after it is not a letter, a digit, `_`, `-` or `/`, nor a `.` or `:` followed
by a letter or a digit. So `coder-30b.` at the end of a sentence names `coder-30b`, and
`coder-30b-instruct` does not. Runs of white space in a display name match any run of white
space.
- The `model` parameter of `task` and of `team_add` takes a model the person may use, by the same
names. When it is **not the session's model and the person has not named it**, the call is
refused, word for word, with `subagents.texts.not_named`:
> Use another model for subagents only when the person names it.
The session's own model given as `model` is the default spelled out, and is never refused for
not being named.
- A team's members are of the lead's session: what the person named there counts for every
`team_add` in the team, a sub-manager's included. A member's default is the session's model, not
its manager's.
## 3. Capacity: the logical restrictions, and no others
What a model's server can do at once is `models/schema.json` `capacity`: `parallel` (`single_session`
being `parallel: 1`; neither said — no limit), and `group`, the server that holds one model at a
time. With **S** the session's model and **M** the subagent's, checked in this order, after
`not_named`:
1. **M is another model on S's one-model server** (both have the same `group`): refused with
`subagents.texts.same_group` — starting it would unload the lead's model:
> That model is on the same one-model server as this chat's model; name a model on another server.
2. **M is S, and S serves one request at a time** (`parallel` 1): refused with
`subagents.texts.one_request` — the subagent would take the only slot from the lead:
> This model serves one request at a time: name another model, on another server, for subagents.
There is **no fallback**: nothing else is picked for the person, ever. A model the person named,
on another server, is the way out — and a model that serves one request at a time is fine there.
These apply to `task` and to `team_add` alike, and before anything is started. Beyond them nothing
is refused for being the wrong model: a member past the free slots waits for one (`team.md` §8),
and `task` keeps its rule for a model that is already full (`loop.json` `capacity`).
## 4. When subagents are offered
The size setting `agents {min, max}` (`team.md` §2) is shown as **Subagents** — `subagents.setting`:
the label, and **Min** and **Max** for `min` and `max` (defaults 1 and 4, at most `cap` 32, kept
with the chat). **The numbers count the session's own agent**: Min 1 / Max 1 is the agent alone,
with no subagents; Max 4 is the agent and up to three subagents (`subagents.setting.hint`). A UI
shows the setting as **one range from 1 to `cap` with two handles, Min and Max** (Min never past
Max): a slider in a graphical UI, two numbers on one line in a terminal, each moved on its own. It, the team tools and `blocks/team_lead.md` are **offered** when both hold:
1. Subagents are enabled for the session (`team.md` §2, rule 1).
2. **At least one model could serve as a subagent**: S itself, when it serves two or more requests
at once (`parallel ≥ 2`, or no limit); or **any other model the person may use that is not on
S's one-model server** (no `group`, or another one) — whatever its own `parallel`.
So a session on a one-request model is offered subagents when another server has a model, and
**its first note says so** (`context.note.team_own`, after `team`): the session's model cannot
serve subagents itself, and they need a model the person names. A UI showing the setting says the
same beside it (`subagents.setting.own`). Nothing is offered when neither holds — the same as
before 3.3.0 for a single model.
What counts as **usable** is each project's: LLeMbas — the models the person may use in the chat's
picker; the CLI — the models of the server it is logged in to.
---
# Subagents v2 — the main agent and its tree
Spec 3.4.0. **How subagents are organised, what each may do, and how each ends.** The owner's model:
one permanent **main agent** per session, which alone makes subagents and places them in a tree;
permissions are inherited and never widened; a subagent is temporary and ends with its task or its
context. Sections 5–13 **supersede `team.md` where they say something different** — who adds a
subagent (§6), who stops one (§10), the states (§9), what a member is told (§13) — and keep the
rest of it: the size setting and its counting (§2–§3), the room and who receives what (§5),
delivery and waking (§7), a manager's refusals (§6 there), capacity and waiting for a slot (§8).
The tool names `team_*` stay (nothing stored or trained breaks); `task` and `report` are unchanged
for a one-off subagent. The texts are `loop.json` `team` (3.4.0 additions marked there); the cases
`conformance/team.json` (the tree, the tools, the lifecycle) and `conformance/delegation.json`
(permissions).
## 5. Words
- **The main agent** is the session's own agent: the chat's agent on LLeMbas, the session's in the
CLI. It is **permanent**: it compacts and never ends. In the room and in every tool it is called
`lead` (the name is kept from 3.2.0); a person reads it as *the main agent*.
- **A subagent** is an agent the main agent added (`team_add`). It has:
- **`id`** — `s1`, `s2`, … in the order the session's subagents were added, never reused in the
session (a replacement gets a new one);
- **`name`** — the main agent's choice (`team.names.pattern`), unique among the subagents that
have not ended, `lead`, `all` and `parent` reserved;
- **`position`** — its designation, one line, given by the main agent (`team_add`'s `role`:
*the API's tests*, *reviews the parser*);
- **`parent`** — the main agent, or a **sub-manager** the main agent placed it under;
- **`task`** — its brief, as given (and as replaced by `team_assign`);
- **`mode`** and **`request`** — its permission mode and its request options (§7);
- **`model`** — `subagents.md` §2–§3, unchanged.
- **A sub-manager** is a subagent added with `lead: true`. It **directs** the subagents the main
agent places under it — they report to it, it messages them, it reviews their work — and it does
**not** add, assign, replace or stop subagents: only the main agent does (§6). Like every manager
it does not do the work itself (`team.md` §6, unchanged).
- **The tree**: the main agent at the root, every subagent under its parent, in the order added.
**Under** an agent and **its subtree** keep their `team.md` meaning.
## 6. Only the main agent makes subagents
- **`team_add`, `team_assign`, `team_replace`, `team_stop` and `team_decide`** are the main agent's.
A subagent's call to any of them is refused, word for word, with `team.texts.only_main`:
> Only the main agent adds, assigns, replaces and stops subagents: ask it (team_send to lead).
A subagent's tool list never has `task` (a one-off subagent is the main agent's too), and a call
to it by a former name is refused with the same text.
- **`team_add`** takes, beside 3.2.0's `name`, `role` (the position), `task`, `goal`, `lead`,
`agent`, `model`: **`parent`** — the name of a sub-manager to place it under (default: the main
agent; refused with `team.texts.not_manager` for a subagent that is not a sub-manager, and
`unknown` for no such name), **`mode`** — its mode (default: its parent's; §7), **`request`** —
its request options (§7). Its refusals, in order: `unavailable`, `only_main`, then 3.2.0's (`all_name`,
`bad_name`, `taken`, `no_goal`, `full`), then `unknown` and `not_manager` for `parent`, then the mode's (`wider`, `request_not_narrower`,
`request_kind`), then the model's (§2–§3). `parent` and the reserved names are refused as
`taken`.
- **The person** can tell the main agent to spawn — it is the main agent's call, as any — or set
**Min above 1**: then **`min − 1` slots** exist from the start of the main agent's reply (the
first one after the setting was told, `team.md` §10). A **slot** is a place in the tree for a
subagent not added yet: it is shown (§12) and `team_read` lists it, it is **not** an agent and
does not count toward the size, and each subagent added fills one. Open slots are
`max(0, min − 1 − subagents that have not ended)`. The main agent is told to use them in its
note (`context.note.team_lead`, which 3.4.0 words as slots), and is a manager from the start
(`team.md` §6).
- **Min/Max** (3.3.0) are unchanged: they count the main agent; 1 is the main agent alone. The
model rules (§2–§3) are unchanged.
## 7. Permissions: inherited, never widened
**A subagent's mode is its parent's or stricter** — `permission/modes.json` `order`, loosest first:
`auto`, `edit`, `manual`, `plan`. The main agent's mode is the session's.
- `team_add`'s and `team_assign`'s `mode`, looser than the parent's, is refused, word for word,
with `team.texts.wider`:
> A subagent's mode cannot be looser than its parent's ({{parent_mode}}).
When the parent's own mode becomes stricter during the session (the person switches the main
agent to manual), every subagent looser than its parent is made as strict as it, down the tree,
at once; a looser switch changes no subagent.
- **Request options** (`request`: a list of the risk classes `read`, `write`, `execute`) may be
given **only with a mode stricter than the parent's** — otherwise refused with
`team.texts.request_not_narrower` ("Request options go with a mode stricter than the parent's:
without one there is nothing to ask for."); an unknown kind with `team.texts.request_kind`. They
let the subagent **ask the main agent** for a call of that class that its own mode does not
allow; **the main agent is the check**.
**Who decides a subagent's call.** The hardline and the deny rules first, as for any call. Then:
1. The call is evaluated in the **subagent's mode**, with the session's rules and approvals and
the subagent's own grants (below). **Allow** — it runs. **Deny** (a rule, the hardline, plan
mode's refusal) — refused, as always.
2. **Ask** — the call is evaluated in the **main agent's mode** (the session's rules and
approvals, no grants):
- **Allow** — the main agent could allow it: the subagent was narrowed. If the call's risk class
is in its `request`, refused with `team.texts.requestable` — it asks with `team_request`, the
main agent decides with `team_decide`, and once allowed the same call runs. Otherwise refused
with `team.texts.not_delegated`:
> Your mode does not allow this, and you may not ask for it: tell your parent what you need.
- **Ask** — **nobody in the tree can allow it: it goes to the person**, as an approval card that
names the subagent (its name and position), the same card and the same answers as the main
agent's own; unattended, refused as `modes.json` `unattended` says. So in an all-Edit tree a
subagent's `bash` reaches the person — not the main agent, which could not allow it either.
- **Deny** — refused with that reason.
A sub-manager is never asked: it may not allow more than the main agent, and the main agent is
the check.
**`team_request`** (a subagent with request options; its tool list has it only then): `tool`, the
permission `pattern` it needs (as a rule writes it: `git push *`, a path) and `why`. Refused with
`team.texts.not_requestable` when the tool's risk class is not in its options. Posted to the main
agent as a request, under its own mark (`team.marks.request`), the body `team.texts.request_body`,
with an id (`r1`, `r2`, … per session); the answer `team.texts.requested` says it waits for the main agent's decision.
**`team_decide`** (the main agent): `id`, `allow` (a boolean), `note`. Allowed — the subagent gets
a **grant**: the rule `{ permission: <tool's key>, pattern, action: allow }` for itself alone, for
the rest of its life; **a grant only ever applies where the main agent's own mode would allow the
call** (step 2's evaluation, done again at the call), so it can never widen past the main agent.
Either way the subagent is told, under `team.marks.decision`: `team.texts.decision_allowed` or
`decision_refused`, then the note after a blank line. The answer to the main agent is
`team.texts.decided` (`decision` being `allowed` or `refused`). Refused:
`team.texts.no_request` for an id that is not an open request.
## 8. What each agent has
| Tools | Main agent | Sub-manager | Subagent |
|---|---|---|---|
| `team_whoami`, `team_read`, `team_send`, `team_findings` | ✓ | ✓ | ✓ |
| `team_finish` | — | ✓ | ✓ |
| `team_request` | — | with request options | with request options |
| `team_add`, `team_assign`, `team_replace`, `team_stop`, `team_decide` | ✓ | — | — |
Fixed when the prompt is made (the main agent's) or when the subagent is added (`context.md` §10,
rule 4). What each does:
- **`team_whoami`** — who the caller is: `team.whoami`, one line each, in its order — id, name, position, parent, task, mode and
request options, model, the limits (the size and Max, the steps a turn may take, whether it may
add subagents) and its **context use** (tokens in its context now, of its model's window, and the
percentage). For the main agent: the same, its position *the main agent*, without the parent and task lines.
- **`team_read`** — the roster: the tree (every agent and open slot, §12's fields) and the room,
as in 3.2.0 (`team.read`; 3.4.0's row adds the id, the mode and the context use).
- **`team_send`** — a message `to` names, `all`, or **`parent`** (3.4.0): the caller's parent
(refused for the main agent with `team.texts.no_parent`). Otherwise 3.2.0.
- **`team_finish`** — `report`: the subagent's task is done. The report goes to its parent (the
report mark, as a final reply's), and the subagent **ends** (§9): its turn stops after this call,
it leaves the size, and its findings and transcript stay.
- **`team_findings`** — `write` (`text`): a finding kept for the caller, numbered from 1; `read`
(`of`: a name or an id, default the caller): the findings of the caller, or of an agent in its
subtree (the main agent: anybody's), ended ones included — as `team.findings` writes them. A
name that has been used more than once means its latest holder; an id is exact. Otherwise refused with
`team.texts.not_yours_findings`. The person reads every agent's (§12).
- **`team_assign`** — `name`, `task`, and optionally `role` (a new position), `parent` (another
sub-manager, or `lead`), `mode` (§7): a new task for a subagent that has not ended. Its task
becomes this one; it is told under `team.marks.assignment`, and a finished one is woken. Refused:
`unknown`, `team.texts.ended` for one that has ended, `not_manager`, `wider`; a move under its
own subtree with `team.texts.cycle`.
- **`team_replace`** — `name`, and optionally `task`: the subagent ends (stopped, if it has not
already), and a new one takes its place — the same name, position, parent, mode, request options
and model, a new id — briefed with `task` (default: the old task) followed by the old one's
findings (`team.texts.replace_brief`). Its subagents move under the new one. Refused: `unknown`.
- **`team_stop`** — the main agent's only (3.2.0 let a manager stop its subtree); otherwise 3.2.0.
- **`team_decide`** — §7.
## 9. A subagent's life
States (`team.read.states`): **`working`** (a turn runs), **`waiting`** (it has work and waits for
a slot, `team.md` §8), **`finished`** (its last turn ended with a final reply, which was its report;
a message wakes it — 3.2.0), **`paused`** (its context is full; its last turn runs), and the ends:
**`done`** (`team_finish`), **`out_of_context`** (its last turn after `paused` ended), **`stopped`**
(the main agent's `team_stop`, a replacement, or the person). The main agent is `working`,
`waiting` or `idle`.
**An ended subagent** — `done`, `out_of_context`, `stopped` — leaves the size and its slot frees;
its name may be used again; it keeps its id, and the tree keeps it (§12) with its findings and
transcript for the rest of the session. Messages to it by name are refused as `unknown`.
The subagents under a sub-manager that ended by itself (`done`, `out_of_context`) move under its
parent until the main agent replaces it, and then back under the replacement; a stopped one's
subtree is stopped with it (§10).
**When its context fills.** A subagent does not compact. When its context reaches
`team.context.pause_at` of its model's window (default 0.85, the fraction compaction would start
at), after the step that took it there:
1. it is **`paused`**: nothing new reaches it — a message to it is posted in the room and not
delivered; whoever replaces it reads it with `team_read`;
2. it is given **one final turn**, at most `team.context.final_steps` steps (8), whose user message
is `team.texts.context_full`, under its own mark: save what it found with `team_findings`, and
tell its parent with `team_send` that it is gone and what is left;
3. when that turn ends it is **`out_of_context`**, and its parent is sent `team.texts.gone` — then,
after a blank line, that turn's final reply if it gave one — as its report (the report mark): the name, that it ran out of context, and how to read its
findings. **The parent decides** — the main agent replaces it (`team_replace`) or uses the
findings; a sub-manager tells the main agent.
**The main agent is permanent**: it compacts as every session does (`context.md` §7) and never
ends; deleting the session ends every subagent.
**Waiting for subagents.** The main agent's turn may end while subagents work; their reports wake
it (3.2.0 §7). Its progress is `waiting_for_subagents` (`progress.md`) while its turn waits on
them — a foreground `task` — and the session shows the subagents' own phases in the tree.
## 10. Stopping
Only the main agent stops (`team_stop`, 3.2.0's refusals but `not_yours`, which no longer arises),
and **the person** (§12) — said to the main agent as a note (`context.note.team_stopped`). A
stopped subagent's subtree is stopped with it, unless the main agent moved it first. A sub-manager
that wants a subagent of its own stopped asks the main agent.
## 11. Transcripts and findings
Every subagent's conversation is kept — its brief, what it wrote, every tool call with its output —
for as long as the session: **viewable read-only by the person, live while it runs and after it
ended**. Nobody types into it; the person speaks to a subagent only through the main agent (or by
stopping it). Findings (§8) are kept the same way, readable by its parent, the main agent, and the
person.
## 12. What clients show
**The tree** — the main agent, every subagent under its parent, open slots, and ended subagents
(after the live ones, dimmed, with how each ended):
| Field | Shown as |
|---|---|
| `name`, `id`, `position` | `parser` (`s2`) — *reviews the parser* |
| `state` | `team.read.states`, its word |
| `model` | display name |
| `mode` | the mode's name, and request options as `+ write` etc. |
| `context` | `{used, window}` → `42%` (a bar where there is room) |
| `progress` | its current phase line (`progress.md` §3) |
| messages | the room's messages to and from it: how many unread by the person, the last one's first line |
- **Web UI, Desktop and the CLI** show the whole tree, the room, each subagent's findings and its
context (the CLI: `/context <name>`), and open any subagent's transcript read-only, live and after
it ended; the person can stop any subagent there.
- **Android** shows a reduced list — name, position, state, progress line, context % — and opens a
transcript read-only.
**The data**, the same in `/api/v2` (LLeMbas: a chat's stream carries the tree as it changes) and on
the link (`acp.md`, capability `tree`):
```json
{ "min": 1, "max": 4, "size": 2, "open_slots": 0,
"agents": [
{ "id": "lead", "name": "lead", "position": "the main agent", "parent": null, "state": "working",
"model": "qwen-27b", "mode": "edit", "request": [], "manager": true,
"context": { "used": 41200, "window": 131072 }, "progress": { "phase": "thinking", "since": 1762790400000 } },
{ "id": "s1", "name": "parser", "position": "reviews the parser", "parent": "lead", "state": "working",
"model": "qwen-27b", "mode": "manual", "request": ["write"], "manager": false, "task": "…",
"context": { "used": 9100, "window": 131072 }, "progress": { "phase": "running_tool", "since": 1762790401000, "tool": "read", "what": "src/parse.ts" },
"findings": 2, "messages": 3 }
],
"ended": [ { "id": "s0", "name": "scout", "position": "…", "parent": "lead", "state": "done", "ended": 1762790300000, "findings": 1 } ] }
```
## 13. What each is told
- The main agent: `blocks/team_lead.md` (3.4.0: it alone adds; slots; positions; modes and request
options; replacing a subagent that ran out of context) and the notes of `team.md` §10.
- A subagent: `blocks/team_member.md` (3.4.0: its id and position, `team_whoami`, `team_findings`,
`team_finish`, that its context is limited and it will be told when it fills); a sub-manager,
`blocks/team_submanager.md` in place of the whole lead block it got in 3.2.0.
## 14. In an agent chat
The main agent of an agent chat is the CLI on the linked device: it starts and runs the
subagents there, under every rule above. The server carries the chat's Subagents setting down with
every turn and the tree, approvals, findings and transcripts up, and offers no subagents of its own
to an agent chat. The protocol: `acp.md`, *Subagents in an agent chat* (capabilities `agents` and
`tree`).
+263
View File
@@ -0,0 +1,263 @@
# Teams
Spec 3.2.0; the model a member runs on and when a team is offered, 3.3.0 (`subagents.md`); the main agent, the tree, permissions and a subagent's life, 3.4.0 (`subagents.md` §5–§13). **Subagents that work together.** A session's agent — the **lead** — may add
**members**, background agents that each own a part of the work, and lead them as a manager: it
plans, splits the work, coordinates and reviews, and the members do it. Members talk to each other
and to their managers in the team's **room**. A member may itself lead an area with members of its
own, so a team grows from a few agents side by side into a small company with one goal. The same in
a chat on the server and in an agent session on a device, in both projects.
The tools are `tools/team_add.json`, `team_send.json`, `team_read.json`, `team_stop.json`; the texts
and numbers `loop.json` `team` (and the size notes in `context.note`); the prompt texts
`prompts/blocks/team_lead.md` and `team_member.md`; the cases `conformance/team.json`.
> **Spec 3.4.0 supersedes parts of this page** (`subagents.md` §5–§13, *Subagents v2*): the lead is
> **the main agent**, and **only it adds, assigns, replaces and stops** — a member with `lead: true`
> is a **sub-manager** that directs the members placed under it (`team_add`'s `parent`) and does not
> add or stop (§4, §9 below); members have a mode no looser than their parent's and may ask the main
> agent for more (`subagents.md` §7); a member ends with `team_finish` or when its context fills
> (`subagents.md` §9); the room carries assignments, requests and decisions besides messages and
> reports; the tree goes over the link (§11). Everything else here stands as written: the size
> setting and its counting, the room and who receives what, delivery and waking, a manager's
> refusals, capacity and waiting for a slot. "Member" here and "subagent" there are the same thing.
## 1. Words
- **Agent**: the lead or a member. Every agent has a **name**: the lead is `lead`; a member the name
it was added under. Names are unique in the team.
- **Member**: an agent added with `team_add`, by the lead or by a member that leads. Its **manager**
is the agent that added it. The members an agent added, and theirs, down the tree, are **under**
it; with the agent itself they are its **subtree**.
- **Manager**: an agent with at least one member, and the lead from the start when the team's `min`
is 2 or more (§2). A manager does not do the work (§6).
- **Team**: the lead and every member, one per lead session; **its size** is how many agents it has
now (§3).
- **Room**: the team's messages, numbered from 1 in the order they were posted, each with `n`, `from`
(a name), `to` (as addressed: names, or `all`), its recipients (resolved when it was posted), the
text, the time, and whether it is a report.
## 2. The size setting, and when a team is offered
A chat has the setting **`agents: {min, max}`** — the agents the team may have, the lead included.
**The numbers count the chat's own agent**: `1` is that agent alone, with no subagents; `max` 4 is
that agent and up to three subagents. Nothing that shows or reads the setting counts subagents only.
- `1 ≤ min ≤ max ≤ cap`. `cap` is the instance's (LLeMbas) or the global configuration's (the CLI),
default `loop.json` `team.agents.cap` (32); a project's configuration never raises it. A value
outside is refused where it is set, with what the bounds are, never clamped silently; a stored
setting the cap was lowered under is read as `max = min(max, cap)`, `min = min(min, max)`.
- Defaults for a new chat: `min` 1, `max` 4 (`team.agents`) — the lead and up to three members. LLeMbas
keeps a per-person default for new chats, seeded with those; the CLI reads them from its
configuration.
- The setting is kept with the chat. A change during a session is told to the lead as a note on its
next user message (`context.md` §10; `context.note.team`, below), never by changing the system
prompt.
**A team is offered** — the setting shown, the team tools listed, `blocks/team_lead.md` in the
system prompt — when both hold, and only then:
1. Subagents are enabled for the session: LLeMbas — the instance allows them and the chat's model
has its subagent tool; the CLI — its subagents are not switched off in the configuration.
2. **At least one model could serve as a subagent** (spec 3.3.0, `subagents.md` §4): the chat's
model, when it serves at least two requests at once (`capacity.parallel ≥ 2`, or neither
`parallel` nor `single_session` is set — a hosted API; `models/schema.json`); or any other model
the person may use that is not on the chat's model's one-model server (`capacity.group`).
The setting is shown as **Subagents**, with **Min** and **Max** (`loop.json` `subagents.setting`):
**one range from 1 to `cap` with two handles**, Min and Max, where Min never passes Max — a slider in
a graphical UI; in a terminal, the two numbers on one line, each moved on its own. Beside it, its
hint (`subagents.setting.hint`, or `short` where a line has no room): the count includes the agent,
and 1 is the agent alone. Never *fewest* / *most*, and never a count of subagents alone.
Both are fixed for as long as the system prompt is (`context.md` §10, rule 4: a model switch makes
a new prompt and a new list). Otherwise the setting is not shown and none of the four tools is
listed, and the session's `task` works as before.
While the tools are listed they need **`team`** (`requires`): met when `max ≥ 2` and a model could
still serve as a subagent (rule 2) — or, for the lead, when its team still has a member (so a lead whose person
lowered `max` to 1 can still talk to, read and stop the members it has). A call while it is not
met answers, word for word, `team.unavailable.one_request` when no model could serve as a subagent
any more (the model's metadata changed after the prompt was made), else `team.unavailable.one_agent`
— which is also the tools' own `unavailable` text.
The meaning of the setting:
- **`max = 1`**: one agent, no team, and no subagent of any kind: `task` answers `one_agent` too
(while the lead has no member; with members left from a larger setting, `full`).
- **`min ≥ 2`**: the lead works through a team from the start — it is a manager before its first
member (§6), and the note asks for at least `min − 1` members.
- **`min = 1`, `max ≥ 2`**: the lead decides; a small job it may do alone. Once it has a member it is
a manager.
## 3. Size, and what counts
**The size** of a team is: the lead, every member (whatever its state — a finished member can be
woken by a message, so it keeps its place), and every `task` subagent running in the team, started by
any agent in it (the CLI's background `task` jobs and foreground ones alike, while they run).
A stopped member does not count: stopping is how room is made.
- **`team_add` is refused past `max`** — when the size would become more than `max`, with
`team.texts.full`. So is `task`, while a team is offered: with `full`, or with `one_agent` when
`max` is 1 and the lead has no member. A `job_send` that would start a finished background
`task` subagent again is refused the same way.
- **Lowering `max` stops nobody.** Members already there stay; nothing new is added until the size
is under the new `max`.
- The size is across **the whole tree**: a member that leads adds within the same `max` as the lead.
## 4. Members
- `team_add` starts the member **at once, in the background**, under the caller: the existing job
machinery (a hidden chat on LLeMbas with its `chat_jobs` row, a subagent job in the CLI), running
unattended — no `ask_user`, the chat's own permission ceiling, its mode no looser than its
manager's (`permission/modes.json`).
- **Its agent** is `general` (the default: it does the work) or `explore` (read-only). **Its model**
is the session's (the lead's) unless `model` gives one the person named in this session — as
`task`'s, refused with `subagents.texts` otherwise (`subagents.md` §2, §3).
- **Its tools** are those its agent gives a subagent, plus `team_send` and `team_read`; one added
with `lead: true` also has `team_add` and `team_stop`. They are fixed when it is made (§10 rule 4:
a subagent's narrowing). `report` (`offered: subagent`) sends its manager a message before its
final reply: posted in the room to the manager, delivered with the message mark.
- **Its system prompt** is built once, when it is added: what a subagent of that agent gets, with
`blocks/team_member.md` in place of `blocks/subagent.md` — its name, role, manager, the team's
goal, the agent's own instructions, and for one with `lead: true` the whole of
`blocks/team_lead.md`. Its first user message is its brief (`task`), as given.
- **The team's goal** is what a member is told the team is for: the `goal` the caller gave in
`team_add`, else the caller's own goal. The lead's own goal is the last `goal` it gave; **the
lead's first `team_add` must give one** (`team.texts.no_goal`). A member already working keeps the
goal it was told; a new goal reaches it only as a message.
- **`team_add`'s refusals are checked in this order**, the first that applies answering:
`unavailable` (§2); `all_name` (the name `all`); `bad_name` (not `team.names.pattern`); `taken`
(the name of an agent on the team, `lead` included); `no_goal`; `full`. Then the member is added:
`added`, or `added_waiting` when it has to wait for a slot (§8). An unknown `agent` or `model`
answers as `task` does; then `model`'s refusals, `not_named`, `same_group`, `one_request`
(`subagents.md`), in that order — before anything is added.
- **Members are not jobs to the model.** `job_list` does not show them and the `job_*` tools do not
take them; the team tools do. (An implementation may run them on its job machinery.)
- **States**: `working` (a turn is running), `waiting` (it has work, and waits for a slot, §8),
`finished` (its last turn ended; it can be woken). The lead is `working`, `waiting` or `idle`.
- A member's background commands stop when its turn ends (`loop.json` `jobs.lifecycle`). Deleting
the lead's session stops the whole team.
## 5. The room: who receives what
- **`team_send`** posts one message: `to` a list of names, or `["all"]` (a lone string is read as a
one-name list). Names are deduplicated, kept in the order given. `all` anywhere in the list means
all, and the other names in it are ignored.
- **Recipients**: for named agents, exactly those named; for `all`, every agent of the team but the
sender — the lead and every member, whoever manages them (the room is one channel for the whole
company). Resolved when the message is posted: an agent added later does not get it.
- **Refused, and nothing posted**, checked in this order: `all` when nobody else is on the team
(`nobody`); a name that is not on the team (`unknown`, the first such name in the order given);
the sender's own name among them (`self`). The answer when
posted: `team.texts.sent`, `to` as addressed.
- **What an agent receives** is only what is addressed to it, by name or as `all`, and — a manager
— **the reports of its own members**. A manager is not sent its members' messages to each other;
it reads them with `team_read`, on demand, so nothing floods its context.
- **A report**: a member's final reply, when its turn ends, is posted to its manager (`report`
true) and delivered to it. An empty reply reads `team.texts.no_report`; a turn that ended
otherwise than by the model stopping adds `team.texts.ended` (`steps`, `budget`, `error — <text>`),
after a blank line. A sub-manager's final reply is likewise its report to its manager.
- **The person's** messages go to the lead as its user messages, not into the room; the lead's
answers to the person are not room messages either. The person sees the whole room and the tree
in the UI (LLeMbas: the Team panel; the CLI: `/team`), and can stop a member there — said to the
lead as a note (`context.note.team_stopped`).
- **`team_read`** answers the tree — every agent, the whole team, in tree order: name, role, its
manager, state, model, last activity — and the room's messages numbered above `since` (default 0)
that the caller may see, oldest first, at most `team.read_max` (50), and how to read on. **Who may
see a message**: the lead every one; any other agent those whose sender or one of whose recipients
is in its subtree — for a member that leads nobody, what it sent and what it received.
## 6. A manager does not do the work
A manager's **work** calls are refused, before the permission check — nothing is asked — with
`team.texts.manager`, word for word:
> You lead a team: give this to a member (team_add or team_send).
**Work** is a call whose risk class (`risk`; an MCP tool's: `read` when it says `readOnlyHint`, else
`execute`) is `write` or `execute`, with two exceptions that stay a manager's:
- `job_stop` — managing what runs is not work;
- a `bash` call **the default rules alone allow in manual mode** (`permission/defaults.json`, the
`permission` conformance area's evaluation with no rules of the person's): reading commands —
`git status`, `git diff`, `cat`, `ls`, `grep` — for review.
So with the spec's tools: **refused** — `write`, `edit`, `multiedit`, `apply_patch`, `mkdir`, `mv`,
`rm`, `skill_manage` (write); `bash` beyond reading, `python`, `commit`, `branch`, `pr`, `merge`,
`tag`, `release` (execute); an MCP tool that does not say it only reads. **Kept** — every `read`
tool (`read`, `glob`, `grep`, `list`, `search`, `recall`, `web_search`, `web_fetch`, …), every
`interact` tool (`ask_user` for the lead, `plan_*`, `task`, `memory`, `show`, `job_send`, `report`,
the team tools, …) and `job_stop`. `team.work` lists the same, and a new tool is placed by its risk
class.
**The tool list does not change** when an agent becomes a manager (`context.md` §10, rule 4): the
same tools are listed and the refused ones answer the refusal. An agent is a manager while it has
a member — a finished one included; one whose members were all stopped is not, unless it is the
lead and `min ≥ 2` with the team offered. `task` stays: a one-off subagent is delegation, and counts
toward the size (§3).
## 7. Delivery, and waking
A message or a report reaches its recipient **as a marked message** — the jobs mechanism
(`loop.json` `jobs`): while the recipient's turn runs, as a user message at its next step boundary
(which does not start a turn: `context.md` §8); otherwise it **wakes** the recipient — a finished
member, or the idle lead — as a new turn of its own, marked `machine`, with its context intact, as
`job_send` restarts a finished subagent. A woken agent needs a slot (§8). Several waiting at one step
boundary go in one user message, in room order, separated by a blank line.
Every one begins with its mark, on a line of its own, then the text:
```
[Team message from parser to lead:]
The grammar is done; the tests are next.
```
- message: `[Team message from {{from}} to {{to}}:]` — `to` as addressed: the names joined with
`, `, or `all`; the same for every recipient.
- report: `[Team report from {{from}} to {{to}}:]` — `to` the manager.
A session that is not open keeps them until it is resumed, as a job's note.
## 8. Capacity: a member waits for a slot
A model serves `parallel` requests at once (`models/schema.json`). **An agent holds a slot of its
model while its turn runs** — the lead, a member, a `task` subagent. An agent with work (added, woken,
given a message while finished, the lead given the person's message) starts when its model has a
free slot and none of its `capacity.group`'s other models is busy; otherwise it is `waiting`.
`team_add` is never refused for a full model (only for size, and for the model rules of
`subagents.md` §3: another model on the lead's one-model server, or a one-request session model):
its answer says the member waits.
Waiting agents start **in order**: the lead first (the person waits on it), then the others in the
order they began waiting. A slot frees when a turn ends or an agent is stopped. `task` keeps its own
rule (`loop.json` `capacity`: refused where its model is full), and its subagent holds a slot.
## 9. Stopping
`team_stop` stops one member **and its whole subtree**, or with `all` every member under the caller:
their turns stop where they are, their background commands with them, messages waiting for them
are dropped, and they **leave the team** — the size drops, their slots free, their names may be
used again. No report comes back from a stopped member. Refused, in this order: `all` with nobody
under the caller (`nobody_to_stop`); a name not on the team (`unknown`); the caller itself or an
agent not under it (`not_yours`). The answer, `stopped`, names the stopped in tree order.
## 10. What the lead is told
- `blocks/team_lead.md` — constant, no numbers — is in the system prompt whenever the team tools
are listed: how to lead.
- The size is in a **note** (`context.md` §10, `context.note`): on the first user message of the
session, and on the next one after the setting changed — `team` (`min`, `max`), with `team_lead`
after it when `min ≥ 2` (`members` = `min − 1`); when `max` is 1, `team_one` instead. One block.
A member the person stopped is its own block, `team_stopped`, with the names. Members are told
nothing of the size: `team_add`'s answer says how big the team is.
## 11. Over the link
*3.4.0: the tree and the room are carried — `acp.md` capability `tree`; what follows is how a device
without it is still shown.*
An agent chat's team runs on the device, as its jobs do. Spec 3.2.0 does not carry the room over
ACP yet: a device with the `jobs` capability reports each member as a subagent job (`job` events,
`description` being `<name>: <role>`), so the client's job strip shows them, and the room is shown
on the device (`/team`). Carrying the room is a later spec's.
+289
View File
@@ -0,0 +1,289 @@
{
"name": "phone_action",
"scope": "llembas",
"sessions": "chat",
"risk": "interact",
"exclusive": true,
"block": "tool",
"purpose": false,
"requires": [
"phone"
],
"unavailable": "This needs the LLeMbas app on the person's phone, and this message did not come from it: nothing was done on any phone. Say what you would have done, and that they can ask again from the app.",
"confirm": "always",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Do something on the person's phone: they are writing to you from the LLeMbas app on it, and the app carries it out with the phone's own apps. The person confirms every call on the phone before anything happens; the result says done, declined or failed, with what the phone said.\n\nUse it only for what the person asked for, one action per call. `summary` is the one line the phone shows them: say what will happen, in their language.\n\n- alarm: `time` (HH:MM, 24-hour); `days` to repeat it; `label`.\n- timer: `seconds`; `label`.\n- calendar_event: `title`, `start` (YYYY-MM-DDTHH:MM, the phone's local time; YYYY-MM-DD with all_day); `end`, `all_day`, `location`, `notes`.\n- sms_draft: `to` (numbers, or names as the person said them), `body`. A draft: the person sends it.\n- email_draft: `to`, `cc`, `subject`, `body`. A draft: the person sends it.\n- dial: `number`. Opens the dialer with it; the person places the call.\n- navigate: `destination`; `stops` on the way, in order; `mode` (drive, walk, bike, transit); `replace_route` to start over rather than ask.\n- add_stop: `stop`, and `destination` — the route's destination as the person told you. Keep the destination of a route you started: no map app can add to a running route, so the phone plans again to the stop and then the destination.\n- search_nearby: `query` (\"petrol station\"), `near` me or the route.\n- stop_navigation: ends the route. Not every map app can; the phone says so if not.\n- open_app: `app`, as the person names it.\n- open_url: `url` (http or https).\n- media: `command` (play, pause, toggle, next, previous) for what is playing.\n- torch: `on`.\n- settings_panel: `panel` — the phone's quick panel or page for it; the person flips the switch.\n- automation_intent: `task`, the name of an automation the person made (Tasker by default, or `app`); `values` it is given.\n\nA place is lat and lon when you know them, else a `query` the map app searches; `name` is what the person calls it.\n\nDeclined means they said no on the phone: do not try again unless they ask. Failed says why; nothing was done.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"alarm",
"timer",
"calendar_event",
"sms_draft",
"email_draft",
"dial",
"navigate",
"add_stop",
"search_nearby",
"stop_navigation",
"open_app",
"open_url",
"media",
"torch",
"settings_panel",
"automation_intent"
],
"description": "What to do"
},
"summary": {
"type": "string",
"description": "One line the phone shows the person: what will happen"
},
"time": {
"type": "string",
"description": "alarm: HH:MM, 24-hour"
},
"days": {
"type": "array",
"items": {
"type": "string",
"enum": [
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
"sun"
]
},
"description": "alarm: the days it repeats on; none for once"
},
"label": {
"type": "string",
"description": "alarm, timer: its name on the phone"
},
"seconds": {
"type": "integer",
"minimum": 1,
"maximum": 86400,
"description": "timer: how long"
},
"title": {
"type": "string",
"description": "calendar_event: the event's title"
},
"start": {
"type": "string",
"description": "calendar_event: YYYY-MM-DDTHH:MM, local; YYYY-MM-DD with all_day"
},
"end": {
"type": "string",
"description": "calendar_event: as start"
},
"all_day": {
"type": "boolean",
"description": "calendar_event: a whole day"
},
"location": {
"type": "string",
"description": "calendar_event: where"
},
"notes": {
"type": "string",
"description": "calendar_event: its description"
},
"to": {
"type": "array",
"items": {
"type": "string"
},
"description": "sms_draft: numbers or names; email_draft: addresses"
},
"cc": {
"type": "array",
"items": {
"type": "string"
},
"description": "email_draft: addresses"
},
"subject": {
"type": "string",
"description": "email_draft"
},
"body": {
"type": "string",
"description": "sms_draft, email_draft: the text"
},
"number": {
"type": "string",
"description": "dial: the phone number"
},
"destination": {
"type": "object",
"description": "navigate, add_stop: where the route ends",
"properties": {
"name": {
"type": "string",
"description": "What the person calls it: \"Home\", \"Lidl on Main Street\""
},
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude, when known"
},
"lon": {
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude, when known"
},
"query": {
"type": "string",
"description": "What the map app searches when there are no coordinates"
}
}
},
"stops": {
"type": "array",
"items": {
"type": "object",
"description": "A place: lat and lon when you know them, else a query the map app searches (an address, or a name and a town); name is what the person calls it",
"properties": {
"name": {
"type": "string",
"description": "What the person calls it: \"Home\", \"Lidl on Main Street\""
},
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude, when known"
},
"lon": {
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude, when known"
},
"query": {
"type": "string",
"description": "What the map app searches when there are no coordinates"
}
}
},
"description": "navigate: places on the way, in order"
},
"stop": {
"type": "object",
"description": "add_stop: the place to add",
"properties": {
"name": {
"type": "string",
"description": "What the person calls it: \"Home\", \"Lidl on Main Street\""
},
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude, when known"
},
"lon": {
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude, when known"
},
"query": {
"type": "string",
"description": "What the map app searches when there are no coordinates"
}
}
},
"mode": {
"type": "string",
"enum": [
"drive",
"walk",
"bike",
"transit"
],
"description": "navigate: how the person travels (drive when not said)"
},
"replace_route": {
"type": "boolean",
"description": "navigate: replace a route already running without asking"
},
"query": {
"type": "string",
"description": "search_nearby: what to look for"
},
"near": {
"type": "string",
"enum": [
"me",
"route"
],
"description": "search_nearby: around the person, or along the running route"
},
"app": {
"type": "string",
"description": "open_app: the app, as the person names it; automation_intent: the automation app (Tasker when not said)"
},
"url": {
"type": "string",
"description": "open_url: an http or https address"
},
"command": {
"type": "string",
"enum": [
"play",
"pause",
"toggle",
"next",
"previous"
],
"description": "media"
},
"on": {
"type": "boolean",
"description": "torch: on or off"
},
"panel": {
"type": "string",
"enum": [
"wifi",
"bluetooth",
"internet",
"volume",
"nfc",
"location",
"do_not_disturb"
],
"description": "settings_panel"
},
"task": {
"type": "string",
"description": "automation_intent: the automation's name"
},
"values": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "automation_intent: named values it is given"
}
},
"required": [
"action",
"summary"
]
}
}
+4
View File
@@ -6,6 +6,10 @@
"exclusive": true,
"block": "tool",
"purpose": false,
"requires": [
"plan"
],
"unavailable": "Not in plan mode: plan_submit is how a plan made in plan mode is put to the person for approval. Carry on with the work; keep the plan current with plan_update.",
"aliases": {
"cli": [
"plan_exit"
+5 -1
View File
@@ -9,7 +9,11 @@
"requires": [
"page"
],
"unavailable": "Python cannot run now: no open browser page is attached to this chat.",
"unavailable": "Python cannot run now: no page of this chat is open. Python runs in the person's browser — ask them to open this chat in the LLeMbas web or desktop app and keep it open, then call python again.",
"texts": {
"no_answer": "Python did not run: a page of this chat is open, but it did not answer. It may still be loading Python, or be asleep in a background tab — ask the person to bring this chat to the front (or reload it), then call python again.",
"timeout": "Python stopped: the run took longer than {{seconds}} seconds, and nothing it wrote was saved. Do less in one call, or split the work over several calls."
},
"aliases": {
"cli": [],
"llembas": []
+53
View File
@@ -0,0 +1,53 @@
{
"name": "report_write",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"scheduled"
],
"unavailable": "This is not a scheduled run: report_write files the report of a schedule's run, and nobody scheduled this turn. Answer the person here instead.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "File this run's report for the person who set the schedule. They read it later, in their list of reports, and are notified of it — so write it to be read cold, by someone who does not see this conversation.\n\n- Call it when your instructions for this run say a report is wanted, once, when the work is done.\n- title: what it is about, as a headline. summary: one or two sentences for the list and the notification. body: the report itself, in Markdown — what you found, what you did, what needs their decision.\n- importance: high only when they should look now.\n- A run files one report: calling it again replaces the first.\n- After it, end your reply with one short line for the run's history. Do not repeat the report.",
"parameters": {
"type": "object",
"properties": {
"title": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"description": "A headline: what the report is about."
},
"body": {
"type": "string",
"minLength": 1,
"description": "The report, in Markdown."
},
"summary": {
"type": "string",
"minLength": 1,
"maxLength": 400,
"description": "One or two sentences: what a person needs to know before opening it."
},
"importance": {
"type": "string",
"enum": [
"normal",
"high"
],
"description": "high: they should look now. Default normal."
}
},
"required": [
"title",
"body",
"summary"
]
}
}
+2 -2
View File
@@ -12,7 +12,7 @@
"subagent_run"
]
},
"description": "Hand a self-contained piece of work to a subagent, which works on its own and returns only its final report — keeping the searching and reading out of your context.\n\n- Use it for broad research (\"where is X handled, and what calls it?\") or a separable job. For one file you already know, just read it.\n- `prompt` must stand on its own: the subagent sees nothing of this conversation. Say what to find or do, and what to report back.\n- `background: true` returns at once with a job id and you carry on; the report comes to you as a message when it ends. Meanwhile job_output shows its progress, job_send gives it a message, job_stop stops it. Without it, the call waits for the report.\n- Independent tasks can run in the same turn. Subagents that change files at the same time should each have `worktree: true`, so they work on separate branches.\n- Agents: {{agents}}",
"description": "Hand a self-contained piece of work to a subagent, which works on its own and returns only its final report — keeping the searching and reading out of your context.\n\n- Use it for broad research (\"where is X handled, and what calls it?\") or a separable job. For one file you already know, just read it.\n- `prompt` must stand on its own: the subagent sees nothing of this conversation. Say what to find or do, and what to report back.\n- `background: true` returns at once with a job id and you carry on; the report comes to you as a message when it ends. Meanwhile job_output shows its progress, job_send gives it a message, job_stop stops it. Without it, the call waits for the report.\n- Independent tasks can run in the same turn. Subagents that change files at the same time should each have `worktree: true`, so they work on separate branches.\n- It runs on your model. Another model only when the person named it in this conversation; nothing else chooses one.\n- Agents: {{agents}}",
"parameters": {
"type": "object",
"properties": {
@@ -38,7 +38,7 @@
"type": "boolean"
},
"model": {
"description": "Run it on another configured model (connection/model, from the list in your instructions) — a second opinion, or a model better at this kind of work. Default: the agent's own model, else yours.",
"description": "Run it on another model — only one the person named in this conversation (its id or name, as in the list in your instructions). Default: your model.",
"type": "string"
}
},
+89
View File
@@ -0,0 +1,89 @@
{
"name": "team_add",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "task",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Add a subagent and start it at once, in the background, on its part of the work. Only you, the main agent, add subagents. You lead: subagents do the work while you plan, coordinate and review — once you have one, tools that change things are refused to you.\n\n- `name` is how everyone addresses it: lowercase letters, digits and hyphens, after what it owns (`parser`, `api-tests`). `role` is its position, one line: what it owns. `task` is its brief and must stand on its own — it sees nothing of this conversation: what to do, when it is done, and what to report.\n- `goal` is the team's goal in a line; your first subagent needs it, and every subagent is told it.\n- `lead: true` makes it a sub-manager: it directs the subagents you place under it (`parent`), reviews their reports and reports to you; it does not add or stop subagents itself.\n- `mode` is its permission mode: its parent's by default, never looser. With a stricter mode you may give `request` options — kinds of action (read, write, execute) it may ask you for with team_request; you decide with team_decide.\n- The person sets how many agents the team may have, you included; past that this is refused. When the model is already serving as many requests as it can at once, the subagent waits for a slot and starts when one frees.\n- It reports with team_finish (or its final reply). Meanwhile team_send messages it, team_read shows the tree and the room, team_assign gives it new work, team_replace replaces it, team_stop stops it.\n- Agents: {{agents}}",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{0,31}$",
"description": "Its name in the team, after what it owns"
},
"role": {
"type": "string",
"minLength": 1,
"description": "Its position, one line: what it owns"
},
"task": {
"type": "string",
"minLength": 1,
"description": "Its brief, self-contained"
},
"goal": {
"type": "string",
"description": "The team's goal in one line: needed with your first member; a new one is told to members added from now on"
},
"lead": {
"type": "boolean",
"description": "A sub-manager: directs the subagents placed under it (default: false)"
},
"agent": {
"type": "string",
"description": "Which agent it is (default: general)"
},
"model": {
"type": "string",
"description": "Run it on another model — only one the person named in this conversation (its id or name, as in the list in your instructions). Default: the session's model."
},
"parent": {
"type": "string",
"description": "The sub-manager to place it under (default: you, lead)"
},
"mode": {
"type": "string",
"enum": [
"auto",
"edit",
"manual",
"plan"
],
"description": "Its permission mode: its parent's or stricter (default: its parent's)"
},
"request": {
"type": "array",
"items": {
"type": "string",
"enum": [
"read",
"write",
"execute"
]
},
"description": "With a stricter mode only: kinds of action it may ask you for (team_request)"
}
},
"required": [
"name",
"role",
"task"
]
},
"variables": {
"agents": "the agents a member may be: `name — description`, separated by \"; \" (as task's)"
},
"offered": "main"
}
+51
View File
@@ -0,0 +1,51 @@
{
"name": "team_assign",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"offered": "main",
"description": "Give a subagent that has not ended a new task: it is told at its next step, or woken. Optionally a new position (`role`), another sub-manager to work under (`parent`, or lead), or a stricter `mode`.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"task": {
"type": "string",
"minLength": 1
},
"role": {
"type": "string"
},
"parent": {
"type": "string"
},
"mode": {
"type": "string",
"enum": [
"auto",
"edit",
"manual",
"plan"
]
}
},
"required": [
"name",
"task"
]
}
}
+38
View File
@@ -0,0 +1,38 @@
{
"name": "team_decide",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"offered": "main",
"description": "Decide a subagent's request (team_request): allow it or refuse it, with a note it is told. You may allow only what your own mode would allow you; anything beyond that goes to the person when the subagent tries.",
"parameters": {
"type": "object",
"properties": {
"id": {
"type": "string",
"minLength": 1
},
"allow": {
"type": "boolean"
},
"note": {
"type": "string"
}
},
"required": [
"id",
"allow"
]
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "team_findings",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Findings kept beyond your context: `write` adds one (a fact, a result, where something is) to yours; `read` shows yours, or with `of` those of a subagent under you (the main agent: anyone's), ended ones included. Write as you go: when your context fills you have one turn left, and your findings are what the next agent starts from.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"write",
"read"
]
},
"text": {
"type": "string",
"description": "write: the finding"
},
"of": {
"type": "string",
"description": "read: a name or an id (default: yours)"
}
},
"required": [
"action"
]
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"name": "team_finish",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"offered": "subagent",
"description": "Your task is done: send your report to your parent and end. Make the report complete on its own — the result, then the evidence (file:line), then anything you could not settle. Save anything worth keeping beyond the report with team_findings first. Nothing runs after this call.",
"parameters": {
"type": "object",
"properties": {
"report": {
"type": "string",
"minLength": 1
}
},
"required": [
"report"
]
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "team_read",
"scope": "shared",
"sessions": "both",
"risk": "read",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "The tree and its room: every agent (name, id, position, parent, state, model, mode, context use, last activity), open slots, subagents that have ended, and the room's messages after `since` that are yours to see — those you sent or received and those of the subagents under you; the main agent sees them all. Messages are numbered: pass the last number you saw as `since` to read only what is new.",
"parameters": {
"type": "object",
"properties": {
"since": {
"type": "integer",
"minimum": 0,
"description": "Show messages after this number (default: 0, from the start)"
}
}
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"name": "team_replace",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "task",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"offered": "main",
"description": "Replace a subagent — one that ran out of context, or one that is stuck: it ends (stopped, if it has not already), and a new one with the same name, position, parent, mode and model takes its place, briefed with `task` (default: the old task) and the old one's findings. The subagents under it move under the new one.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"task": {
"type": "string"
}
},
"required": [
"name"
]
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "team_request",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"offered": "subagent",
"description": "Ask the main agent to allow a call your mode does not, of a kind your request options name. Say the tool, the permission pattern you need (a command such as `git push *`, or a path) and why. Its decision comes to you as a message; once allowed, make the call again.",
"parameters": {
"type": "object",
"properties": {
"tool": {
"type": "string",
"minLength": 1
},
"pattern": {
"type": "string",
"minLength": 1
},
"why": {
"type": "string",
"minLength": 1
}
},
"required": [
"tool",
"pattern",
"why"
]
}
}
+39
View File
@@ -0,0 +1,39 @@
{
"name": "team_send",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Send a message through the team's room: to one or more agents by name, to `parent` (the agent you report to), or to `all`. It reaches each at its next step, or wakes one that has finished, its context intact. Message the agent who owns a thing; use `all` only for what everyone needs. The main agent is `lead`.",
"parameters": {
"type": "object",
"properties": {
"to": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"description": "Names, [\"parent\"], or [\"all\"]"
},
"message": {
"type": "string",
"minLength": 1
}
},
"required": [
"to",
"message"
]
}
}
+32
View File
@@ -0,0 +1,32 @@
{
"name": "team_stop",
"scope": "shared",
"sessions": "both",
"risk": "interact",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Stop a subagent, and the subagents under it, where they are: their work stops and they end, which makes room for others. Only you, the main agent, stop subagents; `all` stops every one. Nothing they had not reported comes back — ask for a report with team_send first, or read their findings with team_findings.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"description": "A subagent's name, or all"
}
},
"required": [
"name"
]
},
"offered": "main"
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "team_whoami",
"scope": "shared",
"sessions": "both",
"risk": "read",
"exclusive": false,
"block": "tool",
"purpose": false,
"requires": [
"team"
],
"unavailable": "The person allows one agent in this chat: there is no team. Do the work yourself.",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Who you are on the team: your id, name, position, parent, task, permission mode and request options, model, limits, and how full your context is.",
"parameters": {
"type": "object",
"properties": {}
}
}
+1 -1
View File
@@ -324,5 +324,5 @@ say ""
say "Done. Open a new shell (or: source your rc file), then run: lembas"
[ -n "$extra" ] && say "Aliases: $(printf '%s' "$extra" | sed -n "s/^alias \([a-z]*\)=.*/\1/p" | paste -sd' ')"
if [ "$starter" -eq 1 ] && [ -z "$(sed -n 's/^model: *//p' "$CONFIG/config.yaml")" ]; then
say "Next: add a connection to $CONFIG/connections.yaml and set model: in config.yaml."
say "Next: lembas login <your LLeMbas server address>"
fi
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "lembas-cli",
"version": "2.0.0-beta.1",
"version": "2.0.0-beta.11",
"description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.",
"license": "MIT",
"private": true,
+54 -5
View File
@@ -56,6 +56,22 @@
"description": "false: leave the mouse to the terminal — its own selection and Ctrl+Shift+C work without Shift, and the wheel no longer scrolls the transcript (pgup/pgdn do). Default true.",
"type": "boolean"
},
"notify": {
"description": "When a reply finishes, or the agent waits for you, while the terminal is not focused: ring the bell and ask the terminal for a desktop notification (OSC 9) naming the session — never what the reply says. Default true; false: neither.",
"type": "boolean"
},
"paste": {
"description": "A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path.",
"type": "string",
"enum": [
"placeholder",
"full"
]
},
"kitty_clipboard": {
"description": "true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in.",
"type": "boolean"
},
"icons": {
"description": "emoji (default), or plain: one-column symbols for a terminal font that has no emoji.",
"type": "string",
@@ -870,7 +886,7 @@
"type": "string"
},
"effort": {
"description": "The effort a session starts with, when the model takes it; otherwise the model's own default.",
"description": "The effort level a session starts with, when the model offers it: an effort, off (thinking switched off, on a model with the switch) or default; otherwise the model's own start level.",
"anyOf": [
{
"type": "string",
@@ -886,9 +902,42 @@
{
"type": "string",
"const": "off"
},
{
"type": "string",
"const": "default"
}
]
},
"agents": {
"description": "Subagents (harness team.md, subagents.md): how many agents a session may have at work, counting the session's own agent — Subagents: Min 1, Max 4 by default; 1 is this agent alone. Offered where subagents are on and a model could serve one: the session's, when it serves two requests at once, or another model off its one-model server. /team size and /effort (one range, Min and Max) change it for the session.",
"type": "object",
"properties": {
"min": {
"description": "Subagents, Min: the agents at work at least, this agent included (default 1 — 1 is this agent alone). 2 or more: it works through subagents from the start.",
"type": "integer",
"minimum": 1,
"maximum": 9007199254740991
},
"max": {
"description": "Subagents, Max: the agents at work at most, this agent included (default 4 — this agent and up to 3 subagents). 1: this agent alone, no subagents.",
"type": "integer",
"minimum": 1,
"maximum": 9007199254740991
},
"cap": {
"description": "Global config only. The highest max a session may set (default 32).",
"type": "integer",
"minimum": 1,
"maximum": 9007199254740991
}
},
"additionalProperties": false
},
"subagents": {
"description": "false: no subagents — no task tool and no team.",
"type": "boolean"
},
"settings_tool": {
"description": "Global config only. The agent's settings tool: ask (default) — each change is approved like any tool call; allow — changes go through without asking (a less strict mode still asks); off — no settings tool.",
"type": "string",
@@ -991,10 +1040,6 @@
},
"additionalProperties": false
},
"prototypes": {
"description": "Global config only. Offer the model prototypes: a complete HTML page in a `prototype-chat` or `prototype-page` fence, saved as a file under the state directory (prototypes/<session>/) and listed by /prototype; the LLeMbas web UI renders the same fences live. Default false.",
"type": "boolean"
},
"library": {
"description": "Global config only. Where memory lives. lembas (the default when the login may reach it): the account's memory records on the LLeMbas server, through its /mcp — the same records its chats have. local: this machine's memory files. Notes, knowledge bases and skills are this machine's either way.",
"type": "string",
@@ -1042,6 +1087,10 @@
"description": "Let the web UI open a terminal here (LLeMbas's terminal panel on a chat on this device): a login shell as this user, in a directory remote sessions may use. Default false.",
"type": "boolean"
},
"scheduled": {
"description": "Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas instance run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off.",
"type": "boolean"
},
"terminal_integration": {
"description": "Shell integration in those terminals (bash, zsh, fish): after your own startup files, the shell marks each prompt, command and exit status (OSC 133) and its directory (OSC 7), so the web UI shows the directory, a mark beside each finished command, and can jump between commands. false: the shell starts as it is. Default true.",
"type": "boolean"
+21 -3
View File
@@ -127,7 +127,7 @@
"maximum": 1
},
"efforts": {
"description": "The model's own effort vocabulary, in offering order.",
"description": "The model's own effort vocabulary, in offering order. [] — it takes none (its one level is `default`).",
"type": "array",
"items": {
"type": "string",
@@ -141,8 +141,12 @@
]
}
},
"thinking_switch": {
"description": "The server turns thinking off for a request with chat_template_kwargs.enable_thinking false: only then is the level `off` offered.",
"type": "boolean"
},
"effort": {
"description": "Default effort; `off` sends none.",
"description": "The level a conversation starts with, when the model offers it: an effort, `off` (thinking switched off, with thinking_switch) or `default` (nothing sent, for a model that takes no efforts).",
"anyOf": [
{
"type": "string",
@@ -158,6 +162,10 @@
{
"type": "string",
"const": "off"
},
{
"type": "string",
"const": "default"
}
]
},
@@ -174,6 +182,10 @@
"description": "The model reads images: @image files, pasted paths and view_image.",
"type": "boolean"
},
"html_pages": {
"description": "The server's word that this model can write HTML pages (harness pages.md). Read and kept, never used here: a terminal's model is not offered pages.",
"type": "boolean"
},
"tools": {
"description": "false: a model without tool calls — it can only talk.",
"type": "boolean"
@@ -202,9 +214,15 @@
"maxLength": 300
},
"single_session": {
"description": "The server serves one request at a time: a subagent on this same model would take its only slot and push the session's cached prompt out, so it is refused.",
"description": "The server serves one request at a time: a subagent on this same model would take its only slot and push the session's cached prompt out, so it is refused (name a model on another server instead). The same as parallel: 1.",
"type": "boolean"
},
"parallel": {
"description": "How many requests the model's server serves at once (capacity.parallel); wins over single_session. Absent with no single_session: no limit (a hosted API). The session's model is its own subagents' model only when it serves at least 2.",
"type": "integer",
"exclusiveMinimum": 0,
"maximum": 9007199254740991
},
"group": {
"description": "Models sharing one GPU server that holds one model at a time (llama-swap), as the LLeMbas server says (capacity.group): a subagent on another model of the same group would unload this one, so it is refused.",
"type": "string"
+4
View File
@@ -32,6 +32,10 @@ if ! command -v bun >/dev/null 2>&1; then
fi
bun --version
# The repository is public: nothing private in its tracked files (scripts/hygiene.sh).
step "hygiene"
scripts/hygiene.sh
step "dependencies"
bun install --frozen-lockfile
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env bash
# The repository is public: nothing in it may name the private estate it was written on.
# The rule "everything public is current-state and estate-free", as a check that runs in CI on
# every push rather than a sentence somebody has to remember.
#
# Patterns are the kinds of thing that leak: a private domain, an internal `.lan` name, a
# container number, a private address range, a machine's name. This file is the one place that
# may spell them, and is skipped.
set -euo pipefail
cd "$(dirname "$0")/.."
patterns=(
'houmeres'
'\b[a-z0-9-]+\.lan\b'
'\bCT ?2[0-9]{2}\b'
'\b10\.0\.0\.[0-9]+'
'\b192\.168\.[0-9]+\.[0-9]+'
'\bgamebox\b'
'\bthor\b'
)
# What is allowed to match, each for a reason — a line of `file:line:text` as grep prints it:
allowed=(
# The public forge the releases are made on: the workflow that republishes them must name it.
'^\.github/workflows/release\.yml:[0-9]+:.*git\.houmeres\.sk'
# A theme's former name, still read from a configuration written before it was renamed.
'^src/tui/palette\.ts:[0-9]+:export const RENAMED_THEMES'
# Made-up private names and addresses the web tool must refuse to fetch: the test needs them.
'^tests/web\.test\.ts:[0-9]+:.*(files\.lan|device\.lan|192\.168\.1\.10)'
)
allow="$(IFS='|'; echo "${allowed[*]}")"
found=0
for pattern in "${patterns[@]}"; do
hits="$(git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" | grep -vE -- "$allow" || true)"
if [ -n "$hits" ]; then
printf '%s\n' "$hits"
echo "hygiene: the lines above match /$pattern/" >&2
found=1
fi
done
[ "$found" -eq 0 ] && echo "hygiene: nothing private in the tracked files"
exit "$found"
+242 -45
View File
@@ -30,10 +30,12 @@ import { PLAN_META } from "../session/engine.ts"
import { ToolError } from "../tool/tool.ts"
import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts"
import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts"
import { shellLaunch } from "./shellrc.ts"
import { pickShell, shellLaunch } from "./shellrc.ts"
import { callTitle } from "../session/display.ts"
import { sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts"
import { expandHome } from "../config/paths.ts"
import { asMode, EFFORTS, MODES, type Effort, type Mode } from "../config/schema.ts"
import { asMode, MODES, type Mode } from "../config/schema.ts"
import { isLevel, readLevel, type Level } from "../provider/effort.ts"
import { HARNESS_VERSION } from "../harness.ts"
import { findProject, trustedRoots, trustedWithin, trustOf } from "../project/root.ts"
import { VERSION } from "../version.ts"
@@ -41,7 +43,9 @@ import { CWD_META, REMOTE_META, Store } from "../session/store.ts"
import type { Message } from "../provider/types.ts"
import type { Hub } from "./hub.ts"
import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs } from "./jobs.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import { isNote } from "../session/prefix.ts"
import { deniedText, finalReply, judgeMonitor, monitorTimeout, notifyOf, permissionFor, refusalText, runMonitor, runOutcome, scheduledMode, type Report, type ScheduledTurn } from "./scheduled.ts"
export const ACP_VERSION = 1
/** The link's version (LLeMbas `services/device_link.py:PROTOCOL`, harness/acp.md *Versions*). 3:
@@ -66,6 +70,8 @@ export interface Limits {
/** `remote.enabled`, where the limits are the device's (the link, the service's hub). False:
* nothing new is opened or shared, whatever the roots say. Absent: not judged here. */
enabled?: boolean
/** Accept scheduled work (`remote.scheduled`, spec 3.5.0), with remote work on. Absent: no. */
scheduled?: boolean
/** The link a terminal holds for /remote on a machine whose remote work is off: only
* the sessions shared from that terminal can be reached; the web UI opens none of its own. */
sharedOnly?: boolean
@@ -77,7 +83,7 @@ export function refusalFor(L: Limits | undefined, dir: string): string | undefin
if (L.sharedOnly) return "remote work is off on this machine (remote.enabled); only the sessions its terminal shares (/remote) can be reached"
if (L.enabled === false) return "remote work is off on this machine — lembas remote enable there (remote.enabled)"
if (!L.roots.length) return "this device allows no folders for remote work yet — lembas remote add <dir> there (remote.roots)"
if (!underRoots(dir, L.roots)) return `${dir} is outside the directories this device accepts remote work in (remote.roots)`
if (!underRoots(dir, L.roots)) return `${dir} is outside the directories this device accepts remote work in — to allow it, run lembas remote add <dir> there (remote.roots)`
if (L.requireTrust && trustOf(findProject(dir).root) !== "trusted" && !trustedWithin(realPath(dir)))
return `${dir} is not in a trusted project on this device — trust it there first (lembas trust)`
return undefined
@@ -130,10 +136,10 @@ interface Terminal {
/** Most terminals one link may hold at once. */
const MAX_TERMINALS = 4
/** An effort as the instance sends it: a level, or "off"; anything else is not one. */
export function effortOf(v: unknown): Effort | "off" | undefined {
if (v === "off" || v === "" || v === null) return "off"
return typeof v === "string" && (EFFORTS as readonly string[]).includes(v) ? (v as Effort) : undefined
/** An effort level as the instance sends it (an effort, "off" or "default"); anything else is not
* one. Whether the model offers it is the session's to decide (readLevel). */
export function effortOf(v: unknown): Level | undefined {
return isLevel(v) ? v : undefined
}
const MODE_RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
@@ -178,6 +184,13 @@ export interface Session {
turns: TurnLog<PromptResult>
/** The command set last sent to the client, to send it again only when it changed. */
commands?: string
/** Spec 3.8.0: the report the run under way has written (the last one), for its answer. */
report?: Report
/** How the session was opened, when a schedule opened it: what its list of tools follows. */
opened?: ScheduledTurn
/** The scheduled turn it runs now (spec 3.5.0): its mode is the ceiling, its approvals wait
* the schedule's wait and say so, and nobody answers a question or a plan. */
scheduled?: ScheduledTurn
}
/** What `session/prompt` answers. */
@@ -211,7 +224,6 @@ export function contextOf(meta: any): SessionContext | undefined {
out.personalization = { personality: str(m.personalization.personality), personality_custom: str(m.personalization.personality_custom), instructions: str(m.personalization.instructions) }
// `library` (an instance's knowledge bases, 1.1.0) is not read: the CLI's knowledge bases are its
// own (spec 3.0.0), and a 3.0.0 instance sends none.
if (m.prototypes && typeof m.prototypes === "object") out.prototypes = { offered: m.prototypes.offered === true, sources: str(m.prototypes.sources) }
return Object.keys(out).length ? out : undefined
}
@@ -257,11 +269,10 @@ export const CAPABILITIES = [
"model",
"turns",
// Harness spec 1.1.0: what only the client knows comes with the session (its instructions,
// personalization, library scope, prototypes), the plan travels as a structure, library calls
// personalization, library scope), the plan travels as a structure, library calls
// carry the chat's scope, and a client may rewind a session.
"context",
"library",
"prototypes",
"plan_state",
"rewind",
// Harness spec 2.0.0: the session's background jobs — the `job` and `job_note` events, the
@@ -271,6 +282,19 @@ export const CAPABILITIES = [
// Harness spec 3.0.0: the show tool, offered in a session the client opened when the client
// said it can show files; the device sends the file with `_lembas/show`.
"show",
// Harness spec 3.4.0: the progress phases (the `phase` event, `progress` in status); the subagent
// tree (the `team` event with the tree, `_lembas/team*`, `subagent` on an approval); the chat's
// Subagents setting read from `_meta.lembas.agents` (an agent chat's subagents are this device's).
"progress",
"tree",
"agents",
// Harness spec 3.5.0: scheduled turns (`scheduled` in session/new and session/prompt, the run's
// outcome in the answer, `scheduled` on an approval) and `_lembas/monitor`. Whether this device
// accepts them now is `limits.scheduled`.
"scheduled",
// Harness spec 3.8.0 (reports.md §6): `scheduled.notify` read; report_write offered to a run's
// model, and the report it writes carried in the turn's answer.
"reports",
] as const
export const STOP: Record<string, string> = { stop: "end_turn", steps: "max_turn_requests", budget: "max_tokens", cancelled: "cancelled", error: "end_turn" }
@@ -279,12 +303,14 @@ type AskRequest = Parameters<Asker["ask"]>[0]
/** `session/request_permission`'s params for an approval — the same card whichever process asks
* (the hub for a session a terminal runs). `patient`: a person may answer at the terminal
* too, so the instance waits rather than timing the card out. */
export function permissionParams(sessionId: string, req: AskRequest, o: { patient?: boolean; toolCallId?: string } = {}) {
export function permissionParams(sessionId: string, req: AskRequest, o: { patient?: boolean; toolCallId?: string; scheduled?: ScheduledTurn } = {}) {
const offerAlways = !req.request.alwaysAsk
return {
sessionId,
toolCall: {
toolCallId: o.toolCallId ?? crypto.randomUUID(),
// The card's title is the whole command, or the tool's name: a card is read before it is
// answered. The call's short title (display.md §1) belongs on tool_call, not here.
title: req.request.command ?? req.tool,
kind: toolKind(req.tool),
status: "pending",
@@ -298,12 +324,18 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien
],
_meta: {
lembas: {
tool: req.tool,
reason: req.decision.reason,
purpose: req.purpose,
always: req.decision.always ?? req.request.always,
...(o.patient ? { patient: true } : {}),
// Which subagent asks (capability jobs), so the card can say — it may ask while the session itself is idle.
...(req.source ? { job: { id: req.source.jobId, agent: req.source.agent, description: req.source.description } } : {}),
// Spec 3.4.0 (capability tree): a subagent of the tree whose call only the person can allow.
...(req.source?.subagent ? { subagent: req.source.subagent } : {}),
// Spec 3.5.0 (capability scheduled): a scheduled turn's call — the client puts it to the
// person where they are, and the device waits the schedule's wait.
...(o.scheduled ? { scheduled: { schedule_id: o.scheduled.scheduleId, run_id: o.scheduled.runId, wait_s: Math.round(o.scheduled.waitMs / 1000) } } : {}),
},
},
}
@@ -369,7 +401,9 @@ export function planReplyFrom(answer: any, maxMode?: Mode): PlanReply {
}
/** Text the expander added to a user message (an @file, an image, a listing, a `!` command's output). */
const ATTACHMENT = /^<(file|directory|shell|image) /
// What the model was given beside the words typed — attachments, and a session note
// (session/prefix.ts) — is not shown as typed.
const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test(t) || isNote(t) }
/** A stored session as turns the web UI can draw: each person's message, then what the
* model said, thought and ran in answer, up to the next one. A message's attachments are chips,
@@ -464,6 +498,11 @@ export class AcpAgent {
peer.handle("_lembas/job/stop", (p) => this.job("stop", p))
peer.handle("_lembas/job/send", (p) => this.job("send", p))
peer.handle("_lembas/job/transcript", (p) => this.job("transcript", p))
peer.handle("_lembas/team", (p) => this.tree("team", p))
peer.handle("_lembas/team/transcript", (p) => this.tree("team_transcript", p))
peer.handle("_lembas/team/findings", (p) => this.tree("team_findings", p))
peer.handle("_lembas/team/stop", (p) => this.tree("team_stop", p))
peer.handle("_lembas/monitor", (p) => this.monitor(p))
peer.on("_lembas/terminal/input", (p) => this.terminalInput(p))
peer.on("_lembas/terminal/resize", (p) => this.terminalResize(p))
peer.on("_lembas/terminal/close", (p) => this.terminalClose(String(p?.terminalId ?? "")))
@@ -512,7 +551,7 @@ export class AcpAgent {
lembas: {
protocol: this.protocol,
harness_spec: HARNESS_VERSION,
limits: this.limits ? { roots: this.limits.roots, max_mode: this.limits.maxMode } : null,
limits: this.limits ? { roots: this.limits.roots, max_mode: this.limits.maxMode, scheduled: this.limits.scheduled === true } : null,
// The login's connection: a `model` event's ref `<connection>/<name>` is the
// instance's own model `<name>`; any other ref is one only this device has.
connection: this.instanceConnection ?? null,
@@ -571,12 +610,15 @@ export class AcpAgent {
const cwd = typeof p?.cwd === "string" ? expandHome(p.cwd) : ""
if (!cwd || !isAbsolute(cwd)) throw new RpcError(INVALID_PARAMS, "cwd must be an absolute path")
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a directory on this machine`)
// Spec 3.5.0: a scheduled session is judged first — off is the same fixed refusal whatever else.
const scheduled = this.judgeScheduled(p?._meta?.lembas?.scheduled)
const refused = this.refusal(cwd)
if (refused) throw new RpcError(INVALID_PARAMS, refused)
if (refused) throw new RpcError(INVALID_PARAMS, refused, scheduled ? { reason: "folder" } : undefined)
const L = this.limits
const wanted = asMode(p?._meta?.mode) ?? undefined
const mode = L ? clampMode(wanted ?? L.maxMode, L.maxMode) : wanted
const session: Session = { id: "", cwd, prompting: false, app: undefined as unknown as App, turns: new TurnLog() }
// A scheduled session runs in the schedule's mode, never `_meta.mode`.
const mode = scheduled ? scheduled.mode : L ? clampMode(wanted ?? L.maxMode, L.maxMode) : wanted
const session: Session = { id: "", cwd, prompting: false, app: undefined as unknown as App, turns: new TurnLog(), ...(scheduled ? { scheduled, opened: scheduled } : {}) }
// No model-made title: the client names its own conversations (LLeMbas has its chat's), and a
// title request would be a second call the account pays for, for nothing.
// The chat's model and effort: `lembas_model` is the instance's own name for it, the
@@ -616,7 +658,7 @@ export class AcpAgent {
sessionId: id,
modes: { currentModeId: session.app.engine.mode, availableModes: this.modes().map((m) => ({ id: m, name: m })) },
// `instance` (spec 3.0.0): the model is one this link's instance serves, as the model event says.
_meta: { lembas: { model: session.app.engine.model.ref, mode: session.app.engine.mode, effort: session.app.engine.effort ?? "off", instance: this.isInstance(session.app.engine.model.connectionName) } },
_meta: { lembas: { model: session.app.engine.model.ref, mode: session.app.engine.mode, effort: session.app.engine.effort, instance: this.isInstance(session.app.engine.model.connectionName) } },
}
}
@@ -669,8 +711,11 @@ export class AcpAgent {
s.app.switchModel(ref)
}
const effort = effortOf(p?.effort)
if (effort !== undefined) s.app.engine.effort = effort === "off" ? null : effort
return { model: s.app.engine.model.ref, effort: s.app.engine.effort ?? "off" }
// A level the model does not offer is read as its start level; the answer says the one used.
if (effort !== undefined) s.app.engine.effort = readLevel(s.app.engine.model, effort)
// Spec 3.4.0: the chat's Subagents setting, changed between turns.
if (p?.agents) this.takeAgents(s, { agents: p.agents })
return { model: s.app.engine.model.ref, effort: s.app.engine.effort }
}
private modes(): Mode[] {
@@ -719,6 +764,19 @@ export class AcpAgent {
private takeContext(s: Session, p: any) {
const ctx = contextOf(p?._meta)
if (ctx) s.app.setContext(ctx, this.instanceConnection)
this.takeAgents(s, p?._meta?.lembas)
}
/** Spec 3.4.0 (capability agents): the chat's Subagents setting, sent with every turn by the
* instance — absent (an older one, an editor on serve --stdio): the device's own, as before.
* `said`: the person's earlier words in the chat. */
private takeAgents(s: Session, m: any) {
if (!this.lembas) return
const team = s.app.team.team
const a = m?.agents
if (Number.isInteger(a?.min) && Number.isInteger(a?.max) && a.min >= 1 && a.max >= 1) team.setSetting(Math.min(a.min, a.max), a.max)
if (m?.subagents === false) team.subagents = false
if (Array.isArray(m?.said) && !s.app.engine.saidBefore.length) s.app.engine.saidBefore = m.said.filter((x: unknown): x is string => typeof x === "string")
}
/** The session's plan, as a `plan` update — after session/new and after opening from the
@@ -746,7 +804,9 @@ export class AcpAgent {
* `_lembas/show`, where the client said it shows files; otherwise none, and show is not offered. */
private equipShow(s: Session) {
const ctx = s.app.engine.o.toolCtx
if (!this.shows) return void delete ctx.show
this.equipReport(s)
// Nobody is looking at a scheduled run (spec 3.5.0): show is not offered there.
if (!this.shows || s.scheduled) return void delete ctx.show
ctx.show = async (req, callId) => {
if (s.agent !== this || this.peer.isClosed) return { shown: false, reason: "the client is not connected" }
const r = (await this.peer.request("_lembas/show", { sessionId: s.id, toolCallId: callId ?? "", ...req }, 30_000)) as { shown?: unknown; reason?: unknown } | undefined
@@ -754,6 +814,26 @@ export class AcpAgent {
}
}
/** report_write for a session a schedule opened for its run (harness reports.md §2, §6): in the
* list when the server said the schedule notifies; the report is kept on the session — the
* last one written is the run's — and goes back with the turn's answer. A turn of the session
* that is not the schedule's (the person writing into it) finds the tool unavailable. */
private equipReport(s: Session) {
const ctx = s.app.engine.o.toolCtx
if (ctx.report || !s.opened?.notify || s.opened.notify === "never") return
let calls = 0
let run = ""
ctx.report = {
active: () => s.scheduled !== undefined && s.prompting,
file: (report) => {
const id = s.scheduled?.runId ?? ""
if (id !== run) (calls = 0), (run = id)
s.report = report
return ++calls
},
}
}
/** `available_commands_update`: the session's command set, when it changed (or always). */
private sendCommands(s: Session, always = false) {
if (!this.ready || this.peer.isClosed || s.agent !== this) return
@@ -962,12 +1042,18 @@ export class AcpAgent {
// A turn id this session has taken already: not run again — the original's answer,
// now or when it is done.
if (s.turns.has(turnId)) return s.turns.run(turnId, () => Promise.reject(new Error("unreachable")))
// Spec 3.5.0: a scheduled turn is judged again (the setting may have been turned off since the
// session was opened); a prompt without `scheduled` is the person's, in the run's agent chat.
const scheduled = this.judgeScheduled(p?._meta?.lembas?.scheduled)
this.takeContext(s, p)
const prepared = preparePrompt(s.app, s.id, p.prompt, { roots: this.limits?.roots })
// Working already: the prompt waits for the turn to end and runs next. It used to be
// refused, and a web UI that had misjudged the session as idle lost its message to an error.
const run = async (started: () => void): Promise<PromptResult> => {
s.prompting = true
// The turn that runs now says whether the session is a scheduled run's (it may wait behind another).
if (scheduled) s.scheduled = scheduled
else delete s.scheduled
started()
try {
return await this.runPrepared(s, prepared, turnId)
@@ -991,9 +1077,11 @@ export class AcpAgent {
* the expanded prompt with its attachments, under the command's model and mode for this turn. */
private async runPrepared(s: Session, prepared: ReturnType<typeof preparePrompt>, turnId: string): Promise<PromptResult> {
const app = s.app
const turn = s.scheduled
if (turn) return this.runScheduled(s, prepared, turnId, turn)
const done = (meta: Record<string, unknown>): PromptResult => ({ stopReason: "end_turn", _meta: { lembas: { turnId, ...meta } } })
if (prepared.kind === "message") {
app.bus.emit({ type: "notice", message: `/${prepared.name}: ${prepared.text}` })
app.bus.emit({ type: "notice", level: "info", message: `/${prepared.name}: ${prepared.text}` })
return done({ command: prepared.name, message: prepared.text })
}
if (prepared.kind === "action") {
@@ -1006,7 +1094,7 @@ export class AcpAgent {
}
if (prepared.name === "undo") {
const r = app.turns.undo()
app.bus.emit({ type: "notice", message: r ? (r.files.length ? `undone — restored ${r.files.join(", ")}` : "undone — no files had changed") : "nothing to undo in this session" })
app.bus.emit({ type: "notice", level: r ? "info" : "warn", message: r ? (r.files.length ? `undone — restored ${r.files.join(", ")}` : "undone — no files had changed") : "nothing to undo in this session" })
return done({ command: "undo", undone: r ?? null })
}
const mode = this.limits ? clampMode("plan", this.limits.maxMode) : "plan"
@@ -1036,6 +1124,71 @@ export class AcpAgent {
}
}
/** A scheduled request's settings as this device runs them (spec 3.5.0), or undefined when the
* request is not scheduled; a refusal is thrown as -32602 with `data.reason`. */
private judgeScheduled(meta: any): ScheduledTurn | undefined {
if (meta === undefined || meta === null) return undefined
const m = typeof meta === "object" ? meta : {}
const L = this.limits
const judged = scheduledMode({ accept: L?.scheduled === true && L.enabled !== false && !L.sharedOnly, mode: m.mode, max_mode: L?.maxMode ?? "edit", approval_wait_s: m.approval_wait_s })
if ("refused" in judged) throw new RpcError(INVALID_PARAMS, refusalText(judged.refused as "scheduled_off" | "plan"), { reason: judged.refused })
const str = (v: unknown) => (typeof v === "string" ? v.slice(0, 200) : "")
// Spec 3.8.0: `notify` from a server that has reports; none from an older one.
return { scheduleId: str(m.schedule_id), runId: str(m.run_id), title: str(m.title), mode: judged.mode, waitMs: judged.wait_s * 1000, ...(m.notify !== undefined ? { notify: notifyOf(m.notify) } : {}) }
}
/** One scheduled turn: the schedule's mode is the ceiling for the turn — a command in the prompt
* narrows it, never widens it — and the answer carries the run's outcome. */
private async runScheduled(s: Session, prepared: ReturnType<typeof preparePrompt>, turnId: string, turn: ScheduledTurn): Promise<PromptResult> {
const app = s.app
const meta = (extra: Record<string, unknown>, reason: string, text: string, error?: string) => ({
turnId,
...extra,
scheduled: runOutcome({ runId: turn.runId, reason, text, error, notify: turn.notify, report: s.report }),
})
if (prepared.kind !== "run") {
// A scheduled run's text is the server's; a command that is only an action has no reply.
return { stopReason: "end_turn", _meta: { lembas: meta({ command: prepared.name }, "stop", "") } }
}
app.engine.mode = prepared.mode ? clampMode(prepared.mode, turn.mode) : turn.mode
// A run files at most one report, and each run its own.
delete s.report
let error: string | undefined
const off = app.bus.on((e) => {
if (e.type === "error") error = e.message
})
const prev = { model: app.engine.model.ref, effort: app.engine.effort }
try {
if (prepared.model) app.switchModel(prepared.model)
const reason = await app.turns.prompt(prepared.prompt, prepared.extra, prepared.shown, { turnId, attachments: prepared.attachments })
const unsent = app.engine.takeInbox()
return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: meta(unsent.length ? { unsent } : {}, reason, finalReply(app.engine.messages), error) } }
} finally {
off()
if (prepared.model && app.engine.model.ref !== prev.model) {
app.switchModel(prev.model)
app.engine.effort = prev.effort
}
app.engine.mode = turn.mode
}
}
/** `_lembas/monitor` (spec 3.5.0): a schedule's watch command, run here only where the
* schedule's mode allows it without asking — a watch has nobody to ask. */
private async monitor(p: any) {
const turn = this.judgeScheduled({ mode: p?.mode, schedule_id: p?.schedule_id, run_id: p?.run_id })!
const cwd = typeof p?.cwd === "string" ? expandHome(p.cwd) : ""
if (!cwd || !isAbsolute(cwd)) throw new RpcError(INVALID_PARAMS, "cwd must be an absolute path", { reason: "folder" })
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a directory on this machine`, { reason: "folder" })
const refused = this.refusal(cwd)
if (refused) throw new RpcError(INVALID_PARAMS, refused, { reason: "folder" })
const command = typeof p?.command === "string" ? p.command.trim() : ""
if (!command) throw new RpcError(INVALID_PARAMS, "command must be a command line")
const judged = judgeMonitor(command, turn.mode, { ...permissionFor(cwd), cwd })
if ("refused" in judged) throw new RpcError(INVALID_PARAMS, judged.text, { reason: "permission" })
return runMonitor(command, cwd, monitorTimeout(p?.timeout_s))
}
/** `_lembas/session/status`: whether the session is working, and where it runs — asked
* after a restart or a dropped link, so the instance follows a turn still running instead of
* sending its prompt a second time. */
@@ -1062,6 +1215,8 @@ export class AcpAgent {
...(s.turns.last ? { lastTurnId: s.turns.last } : {}),
plan: s.app.engine.plan ?? null,
jobs: jobList(s.app),
progress: s.app.engine.progress.current,
tree: treeOf(s.app),
}
const row = (this.store ??= new Store()).session(id)
// Not open: the last turn it finished, as kept across a restart, its plan and its jobs as stored.
@@ -1086,6 +1241,24 @@ export class AcpAgent {
return { jobs: jobList(this.get(p).app) }
}
/** `_lembas/team`, `/transcript`, `/findings`, `/stop` (spec 3.4.0, capability tree): the
* session's subagent tree — the terminal's through the hub, as the jobs go. */
private async tree(op: "team" | "team_transcript" | "team_findings" | "team_stop", p: any) {
const t = this.terminalFor(p)
if (t) return t.client.request("hub/job", { sessionId: t.sessionId, op, id: p?.id, since: p?.since }, 15_000)
const app = this.get(p).app
switch (op) {
case "team":
return teamView(app, p?.since)
case "team_transcript":
return teamTranscript(app, p?.id)
case "team_findings":
return teamFindings(app, p?.id)
case "team_stop":
return teamStop(app, p?.id)
}
}
/** `_lembas/job/output`, `/stop`, `/send`, `/transcript` (acp/jobs.ts): one job of the session. */
private async job(op: "output" | "stop" | "send" | "transcript", p: any) {
const t = this.terminalFor(p)
@@ -1202,27 +1375,35 @@ export class AcpAgent {
* model's, so the hardline and the modes do not apply, exactly as in a terminal opened here. */
private terminalOpen(p: any) {
const L = this.limits
if (!L?.terminal) throw new RpcError(INVALID_PARAMS, "this device does not open terminals for the web UI (remote.terminal is off)")
if (!L?.terminal) throw new RpcError(INVALID_PARAMS, "Terminals are switched off on this computer. To allow them, run `lembas remote terminal on` there (remote.terminal).")
const cwd = typeof p?.cwd === "string" && p.cwd.trim() ? resolve(expandHome(p.cwd.trim())) : resolve(expandHome(L.roots[0] ?? "~"))
const refused = this.refusal(cwd)
if (refused) throw new RpcError(INVALID_PARAMS, refused)
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a directory on this machine`)
if (this.terminals.size >= MAX_TERMINALS) throw new RpcError(INVALID_PARAMS, `this device already has ${MAX_TERMINALS} terminals open for the web UI`)
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a folder on this computer — choose one that exists`)
if (this.terminals.size >= MAX_TERMINALS) throw new RpcError(INVALID_PARAMS, `This computer already has ${MAX_TERMINALS} terminals open — close one, then open another.`)
const id = crypto.randomUUID()
const cols = Math.max(20, Math.min(500, Number(p?.cols) || 80))
const rows = Math.max(5, Math.min(300, Number(p?.rows) || 24))
const shell = process.env.SHELL || "/bin/bash"
const picked = pickShell()
if (!picked) throw new RpcError(INVALID_PARAMS, "No shell was found on this computer to open a terminal with — set SHELL to one (on Windows: install PowerShell).")
// Marks for the web UI's terminal: the user's own startup files first, then OSC 133/7.
const launch = shellLaunch(shell, id, L.terminalIntegration !== false)
const proc = Bun.spawn(launch.argv, {
cwd,
env: { ...process.env, TERM: "xterm-256color", ...launch.env },
terminal: {
cols,
rows,
data: (_t: unknown, d: Uint8Array) => this.peer.notify("_lembas/terminal/output", { terminalId: id, data: Buffer.from(d).toString("base64") }),
},
} as Parameters<typeof Bun.spawn>[1])
const launch = shellLaunch(picked.shell, id, L.terminalIntegration !== false, process.env, picked.args)
let proc: ReturnType<typeof Bun.spawn>
try {
proc = Bun.spawn(launch.argv, {
cwd,
env: { ...process.env, TERM: "xterm-256color", ...launch.env },
terminal: {
cols,
rows,
data: (_t: unknown, d: Uint8Array) => this.peer.notify("_lembas/terminal/output", { terminalId: id, data: Buffer.from(d).toString("base64") }),
},
} as Parameters<typeof Bun.spawn>[1])
} catch (e) {
// The runtime's pseudo-terminal is POSIX's: where it has none (Windows), say so plainly.
launch.cleanup()
throw new RpcError(INVALID_PARAMS, `A terminal could not be opened on this computer (${basename(picked.shell)}): ${(e as Error).message.split("\n")[0]}`)
}
const pty = (proc as unknown as { terminal: Terminal["pty"] }).terminal
this.terminals.set(id, { proc, pty, cleanup: launch.cleanup })
void proc.exited.then((code) => {
@@ -1286,7 +1467,7 @@ export class AcpAgent {
private forward(s: Session, e: Event) {
// A model change says whether the model is this link's instance's: its ref is the
// provider's now (`deepseek/x`), so the ref alone no longer tells.
const event = e.type === "model" ? { ...e, instance: this.isInstance(e.connection) } : e
const event = e.type === "model" ? { ...e, instance: this.isInstance(e.connection) } : e.type === "team" ? { ...e, tree: treeOf(s.app) } : e
if (this.lembas) this.peer.notify("_lembas/event", { sessionId: s.id, event })
switch (e.type) {
case "text":
@@ -1294,17 +1475,30 @@ export class AcpAgent {
case "reasoning":
return this.update(s, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: e.text } })
case "tool_start":
return this.update(s, { sessionUpdate: "tool_call", toolCallId: e.id, title: e.name, kind: toolKind(e.name), status: "in_progress", rawInput: e.args })
// One title for a call (display.md §1): the same as the transcript's and the progress line's.
return this.update(s, { sessionUpdate: "tool_call", toolCallId: e.id, title: e.title ?? callTitle(e.args) ?? e.name, kind: toolKind(e.name), status: "in_progress", rawInput: e.args })
case "tool_end":
return this.update(s, {
sessionUpdate: "tool_call_update",
toolCallId: e.id,
status: e.result.isError ? "failed" : "completed",
...(e.result.title ? { title: e.result.title } : {}),
content: [{ type: "content", content: { type: "text", text: e.result.output.slice(0, 20_000) } }],
})
case "tool_denied":
return this.update(s, { sessionUpdate: "tool_call_update", toolCallId: e.id, status: "failed", content: [{ type: "content", content: { type: "text", text: e.reason } }] })
// Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas.
// A refused call never started, so no tool_call announced it (the approval card, if one
// was shown, has an id of its own): this is the call's first and only update, and an
// update of an id nobody knows would be dropped.
return this.update(s, {
sessionUpdate: "tool_call",
toolCallId: e.id,
title: e.title ?? e.name,
kind: toolKind(e.name),
status: "failed",
...(e.args !== undefined ? { rawInput: e.args } : {}),
content: [{ type: "content", content: { type: "text", text: e.reason } }],
_meta: { lembas: { denied: true } },
})
case "plan":
return this.update(s, planUpdate(e.plan))
case "mode":
@@ -1318,7 +1512,8 @@ export class AcpAgent {
* (its time ran out, the link dropped) is taken down with `_lembas/permission/settled`. */
private asker(s: Session): Asker {
const agentOf = () => s.agent ?? this
const canAsk = () => agentOf().cards && !agentOf().peer.isClosed
// Nobody is at a scheduled run to answer a question or a plan (spec 3.5.0).
const canAsk = () => agentOf().cards && !agentOf().peer.isClosed && !s.scheduled
/** The client does not know the method after all: as if it had never been offered (and never again). */
const unknown = (a: AcpAgent, e: unknown) => {
if (!(e instanceof RpcError) || e.code !== METHOD_NOT_FOUND) return false
@@ -1330,15 +1525,17 @@ export class AcpAgent {
ask: async (req): Promise<AskReply> => {
// Whichever link holds the session now; none (dropped, not back yet) is nobody to ask.
const agent = agentOf()
const timeout = agent.limits?.approvalTimeoutMs ?? 0
const params = permissionParams(s.id, req)
// A scheduled turn's approval waits the schedule's wait (spec 3.5.0), and says so.
const turn = s.scheduled
const timeout = turn ? turn.waitMs : (agent.limits?.approvalTimeoutMs ?? 0)
const params = permissionParams(s.id, req, turn ? { scheduled: turn } : {})
try {
if (agent.peer.isClosed) throw new Error("not linked")
const answer = await agent.peer.request("session/request_permission", params, timeout || undefined)
return replyFrom(answer, !req.request.alwaysAsk)
} catch {
settle(agent, params.toolCall.toolCallId)
return { kind: "deny", feedback: "Nobody answered the approval in time, so it was refused." }
return { kind: "deny", feedback: turn ? deniedText(turn.waitMs) : "Nobody answered the approval in time, so it was refused." }
}
},
// Getters: whether there is anybody to ask is decided when the tool runs, by the link
+46
View File
@@ -5,6 +5,7 @@
import type { App } from "../app.ts"
import { jobRegistry, type Job, type JobInfo } from "../jobs/registry.ts"
import type { Store } from "../session/store.ts"
import type { TreeInfo } from "../team/team.ts"
import { historyTurns } from "./agent.ts"
import { INVALID_PARAMS, RpcError } from "./rpc.ts"
@@ -79,3 +80,48 @@ export function storedJobs(store: Store, sessionId: string): JobInfo[] {
}
return [...list.filter((j) => j.state === "running"), ...list.filter((j) => j.state !== "running")]
}
// ── Spec 3.4.0 (acp.md capability `tree`): the subagent tree of a session ────────────────────
/** The tree (subagents.md §12), or null for a session with no subagents. */
export function treeOf(app: App): TreeInfo | null {
const t = app.team.team
if (!t.offered && !t.hasMembers() && !t.ended.length) return null
return t.info()
}
/** `_lembas/team`: the tree and the whole room above `since`. */
export function teamView(app: App, since: unknown) {
const n = typeof since === "number" && since >= 0 ? since : 0
const t = app.team.team
return { tree: treeOf(app), room: t.room.filter((m) => m.n > n).map((m) => ({ n: m.n, from: m.from, to: m.to, recipients: m.recipients, text: m.text, time: m.time, report: m.report, kind: m.kind })) }
}
function subagentOf(app: App, id: unknown) {
const key = String(id ?? "")
const a = app.team.team.find(key)
if (!a || a.id !== key || a.id === "lead") throw new RpcError(INVALID_PARAMS, `this session has no subagent ${key}`)
return a
}
/** `_lembas/team/transcript`: a subagent's session, read-only. */
export function teamTranscript(app: App, id: unknown) {
const a = subagentOf(app, id)
const job = a.jobId ? app.registry.get(app.jobsSessionId(), a.jobId) : undefined
const messages = job?.subagent?.engine.messages ?? (job?.childSessionId && app.store ? app.store.messages(job.childSessionId) : [])
return { id: a.id, state: a.state, turns: historyTurns(messages, app.engine.o.toolCtx.cwd) }
}
/** `_lembas/team/findings`. */
export function teamFindings(app: App, id: unknown) {
const a = subagentOf(app, id)
return { id: a.id, findings: a.findings.map((f) => ({ ...f })) }
}
/** `_lembas/team/stop`: the person stops a live subagent and its subtree. */
export function teamStop(app: App, id: unknown) {
const a = subagentOf(app, id)
if (a.endState) throw new RpcError(INVALID_PARAMS, `${a.id} has already ended`)
const gone = app.team.personStop(a.name)
return { stopped: app.team.team.ended.slice(-gone.length).map((x) => x.id) }
}
+5 -2
View File
@@ -56,6 +56,9 @@ export function limitsFromConfig(o: { sharedOnly?: boolean } = {}): Limits & { e
get terminal() {
return r().terminal === true
},
get scheduled() {
return r().enabled === true && r().scheduled === true
},
get terminalIntegration() {
return r().terminal_integration !== false
},
@@ -65,7 +68,7 @@ export function limitsFromConfig(o: { sharedOnly?: boolean } = {}): Limits & { e
/** What the instance is told when the link opens (the hello, initialize's limits and
* capabilities): when it changes, the link is dialled again so the instance hears the new one. */
function announced(L: Limits & { enabled: boolean }): string {
return JSON.stringify([L.enabled, L.sharedOnly, L.roots, L.maxMode, L.requireTrust, L.terminal])
return JSON.stringify([L.enabled, L.sharedOnly, L.roots, L.maxMode, L.requireTrust, L.terminal, L.scheduled === true])
}
export function pickInstance(name?: string): Instance {
@@ -199,7 +202,7 @@ export async function runLink(o: LinkOptions = {}): Promise<LinkStatus> {
version: VERSION,
harness_spec: HARNESS_VERSION,
device: { host: hostname(), platform: `${process.platform}-${process.arch}` },
limits: { roots: limits.roots, max_mode: limits.maxMode, require_trust: limits.requireTrust },
limits: { roots: limits.roots, max_mode: limits.maxMode, require_trust: limits.requireTrust, scheduled: limits.scheduled === true },
})
status("linked")
// The limits apply at once, each time they are looked at. What the instance was told at
+307
View File
@@ -0,0 +1,307 @@
// Scheduled work on a linked computer (harness acp.md, spec 3.5.0): what this device makes of a
// scheduled turn and of a monitor's watch command. The server decides when a schedule runs; the
// device decides whether (Accept scheduled work, `remote.scheduled`) and how far (the schedule's
// mode, never wider than Edit unless it says Auto, lowered to remote.max_mode). The pure rules are
// here, run by the conformance areas `scheduled`, `silent` and `monitor`; agent.ts wires them in.
import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import { join } from "node:path"
import { loadConfig } from "../config/load.ts"
import type { Mode, PermissionConfig } from "../config/schema.ts"
import { LOOP } from "../harness.ts"
import { DEFAULT_RULES, evaluate, toRules, type Rule } from "../permission/evaluate.ts"
import { BUILTIN_HARDLINE, hardlineRules, type HardlineRule } from "../permission/hardline.ts"
import { fillPrompt } from "../prompt/fill.ts"
import { findProject, trustOf } from "../project/root.ts"
import type { Message } from "../provider/types.ts"
export const SCHEDULED = LOOP.scheduled
const RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
/** A mode lowered to `max` (agent.ts clampMode, kept here so neither imports the other). */
const clampMode = (wanted: Mode, max: Mode): Mode => (RANK[wanted] < RANK[max] ? max : wanted)
/** Why a scheduled request is refused: `data.reason` of the -32602. */
export type Refusal = "scheduled_off" | "plan" | "folder" | "permission"
/** What a scheduled request says (`_meta.lembas.scheduled`, or `_lembas/monitor`'s params). */
export interface ScheduledMeta {
schedule_id?: string
run_id?: string
title?: string
mode?: unknown
approval_wait_s?: unknown
/** Spec 3.8.0 (reports.md §6): the schedule's notify-when. Absent: a server before 3.8.0. */
notify?: unknown
}
/** A scheduled turn's settings, once the device has judged it. */
export interface ScheduledTurn {
scheduleId: string
runId: string
title: string
mode: Mode
waitMs: number
/** Spec 3.8.0: the schedule's notify-when, when the server said one — the run may then file a
* report (unless `never`) and the retired sentinel means nothing. Absent: a 3.5–3.7 server,
* whose runs are judged as before. */
notify?: Notify
}
/** The schedule's mode and approval wait as this device runs them, or why it refuses
* (conformance/scheduled.json). `accept`: remote.scheduled with remote work on. */
export function scheduledMode(o: { accept: boolean; mode?: unknown; max_mode: Mode; approval_wait_s?: unknown }): { mode: Mode; wait_s: number } | { refused: Refusal } {
if (!o.accept) return { refused: "scheduled_off" }
if (o.mode === "plan") return { refused: "plan" }
// An unknown word is the default, never anything wider (`unrestricted` is not read as auto here).
const chosen: Mode = (SCHEDULED.modes as string[]).includes(o.mode as string) ? (o.mode as Mode) : (SCHEDULED.default_mode as Mode)
return { mode: clampMode(chosen, o.max_mode), wait_s: approvalWait(o.approval_wait_s) }
}
/** The approval wait in whole seconds, clamped (loop.json scheduled.approval_wait_seconds). */
export function approvalWait(v: unknown): number {
const W = SCHEDULED.approval_wait_seconds
const n = typeof v === "number" && Number.isFinite(v) ? Math.floor(v) : W.default
return Math.max(W.min, Math.min(W.max, n))
}
/** The fixed text of a refusal. */
export function refusalText(reason: "scheduled_off" | "plan"): string {
return reason === "plan" ? SCHEDULED.texts.plan : SCHEDULED.texts.off
}
/** The feedback a scheduled approval nobody answered gives the model. */
export function deniedText(waitMs: number): string {
return fillPrompt(SCHEDULED.texts.denied, { minutes: String(Math.max(1, Math.round(waitMs / 60_000))) })
}
// --- The sentinel --------------------------------------------------------------------------
const marks = (line: string) => line.trim().replace(/\.+$/, "").trim().toUpperCase() === SCHEDULED.sentinel
/** Whether a reply is silent: the sentinel on its first or last non-empty line, any case, every
* trailing full stop forgiven (conformance/silent.json; the server's `notify.is_silent`). */
export function isSilent(text: string): boolean {
const lines = (text ?? "")
.trim()
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean)
return lines.length > 0 && (marks(lines[0]!) || marks(lines[lines.length - 1]!))
}
/** The reply without any sentinel line, trimmed: what a preview shows. */
export function stripSentinel(text: string): string {
return (text ?? "")
.trim()
.split(/\r?\n/)
.filter((l) => !marks(l))
.join("\n")
.trim()
}
/** The text of the last assistant message: a turn's final reply. */
export function finalReply(messages: Message[]): string {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i]!
if (m.role === "user") return ""
if (m.role !== "assistant") continue
const text = m.parts.map((p) => (p.type === "text" ? p.text : "")).join("")
if (text.trim()) return text
}
return ""
}
/** The run's outcome, for `session/prompt`'s `_meta.lembas.scheduled`. */
export function runOutcome(o: { runId: string; reason: string; text: string; error?: string; notify?: Notify; report?: Report }) {
let status: "ok" | "silent" | "failed" | "cancelled"
let error: string | null = null
if (o.reason === "cancelled") status = "cancelled"
else if (o.reason === "error") {
status = "failed"
error = o.error || "the turn failed"
} else if (!o.text.trim()) {
status = "failed"
error = SCHEDULED.texts.no_reply
} else status = o.notify === undefined && isSilent(o.text) ? "silent" : "ok"
// Spec 3.8.0: the report written in the turn travels with its answer — also from a turn that
// then failed: what was found is not thrown away with the error. `silent` is a status of 3.5.0.
return { run_id: o.runId, status, text: o.text, error, ...(o.report ? { report: o.report } : {}) }
}
// --- The watch command ---------------------------------------------------------------------
/** `sha256:` and the hex SHA-256 of the output's bytes as read, a newline, and the exit status:
* the status after the bytes, so a stream is hashed as it comes (conformance/monitor.json). */
export function monitorHash(exit: number, output: Uint8Array | string): string {
const h = createHash("sha256")
h.update(typeof output === "string" ? Buffer.from(output, "utf8") : output)
h.update(`\n${exit}`)
return `sha256:${h.digest("hex")}`
}
/** The permission context a `bash` call in `cwd` would be judged in: the hardline, the default
* rules, the global rules and — in a trusted project — the project's (as app.ts builds them). */
export function permissionFor(cwd: string): { rules: Rule[]; hardline: HardlineRule[]; root: string; planDir: string; projectDir: string } {
const project = findProject(cwd)
const trusted = trustOf(project.root) === "trusted"
const loaded = loadConfig({ projectConfigDir: project.dir, trusted })
return {
rules: [...toRules(DEFAULT_RULES, "default"), ...loaded.permissions.flatMap((p, i) => toRules(p, loaded.permissionSources[i] ?? "global"))],
hardline: hardlineRules({ extra: loaded.config.hardline_extra, disable: loaded.config.hardline_disable }),
root: project.root,
planDir: join(project.dir, "plans"),
projectDir: project.dir,
}
}
/** Whether a watch command may run in `mode`: only where the mode allows it without asking
* (conformance/monitor.json `judge`). */
export function judgeMonitor(line: string, mode: Mode, ctx: { rules: Rule[]; hardline: HardlineRule[]; root: string; cwd?: string; planDir?: string; projectDir?: string }): { run: true } | { refused: "asks" | "denied"; text: string } {
const d = evaluate({ permission: "bash", class: "execute", patterns: [line], command: line, paths: [ctx.cwd ?? ctx.root] }, { mode, rules: ctx.rules, hardline: ctx.hardline, root: ctx.root, planDir: ctx.planDir, projectDir: ctx.projectDir })
if (d.action === "allow") return { run: true }
const reason = d.reason || (d.action === "ask" ? "it is not allowed without asking" : "refused")
if (d.action === "ask") return { refused: "asks", text: fillPrompt(SCHEDULED.texts.monitor_asks, { mode, reason }) }
return { refused: "denied", text: fillPrompt(SCHEDULED.texts.monitor_denied, { reason }) }
}
/** The conformance runner's judge: the default rules and the case's own as global rules. */
export function judgeCase(line: string, mode: Mode, extra?: PermissionConfig) {
const rules = [...toRules(DEFAULT_RULES, "default"), ...toRules(extra ?? {}, "global")]
return judgeMonitor(line, mode, { rules, hardline: BUILTIN_HARDLINE, root: "/project", planDir: "/project/.agent/plans", projectDir: "/project/.agent" })
}
export interface MonitorResult {
hash: string | null
exit: number | null
timed_out: boolean
excerpt: string
truncated: boolean
bytes: number
duration_ms: number
}
/** The watch command's timeout in seconds, defaulted and clamped. */
export function monitorTimeout(v: unknown): number {
const T = SCHEDULED.monitor.timeout_seconds
const n = typeof v === "number" && Number.isFinite(v) ? Math.floor(v) : T.default
return Math.max(T.min, Math.min(T.max, n))
}
/** Run a watch command as `bash -c` in `cwd`, in its own process group, with no input; stop the
* group at the timeout. Everything streamed is hashed; the first output_max_bytes are kept. */
export function runMonitor(command: string, cwd: string, timeoutS: number, env: Record<string, string | undefined> = process.env): Promise<MonitorResult> {
const M = SCHEDULED.monitor
const started = Date.now()
return new Promise((resolve) => {
const child = spawn("bash", ["-c", `exec 2>&1\n${command}`], { cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], env })
const hash = createHash("sha256")
const kept: Buffer[] = []
let keptBytes = 0
let bytes = 0
let timedOut = false
const onData = (d: Buffer) => {
bytes += d.length
hash.update(d)
if (keptBytes < M.output_max_bytes) {
const piece = d.subarray(0, M.output_max_bytes - keptBytes)
kept.push(piece)
keptBytes += piece.length
}
}
child.stdout!.on("data", onData)
child.stderr!.on("data", onData)
const killGroup = (sig: NodeJS.Signals) => {
try {
process.kill(-child.pid!, sig)
} catch {}
}
const timer = setTimeout(() => {
timedOut = true
killGroup("SIGTERM")
setTimeout(() => killGroup("SIGKILL"), 2000).unref()
}, timeoutS * 1000)
let done = false
const finish = (code: number | null) => {
if (done) return
done = true
clearTimeout(timer)
const text = Buffer.concat(kept).toString("utf8")
const excerpt = text.slice(0, M.excerpt_chars)
const exit = timedOut || child.signalCode ? null : code
if (exit !== null) hash.update(`\n${exit}`)
resolve({
hash: exit === null ? null : `sha256:${hash.digest("hex")}`,
exit,
timed_out: timedOut,
excerpt,
truncated: bytes > Buffer.byteLength(excerpt, "utf8"),
bytes,
duration_ms: Date.now() - started,
})
}
child.on("close", (code) => finish(code))
child.on("error", () => finish(127))
})
}
// ---- Reports (harness reports.md, spec 3.8.0) ----
const NOTIFY = SCHEDULED.notify
export type Notify = "always" | "when" | "never"
/** A report as report_write files it. */
export interface Report {
title: string
body: string
summary: string
importance: "normal" | "high"
}
/** A schedule's notify-when as a value: a word nobody knows, or none, is the default. */
export function notifyOf(v: unknown): Notify {
return (NOTIFY.values as string[]).includes(v as string) ? (v as Notify) : (NOTIFY.default as Notify)
}
/** The instruction placed in the run's prompt (reports.md §3): the text for the value, the
* condition the person's words — one line, trimmed, without a closing full stop — or the default
* one; "" for never. */
export function notifyInstruction(notify: unknown, condition?: unknown): string {
const n = notifyOf(notify)
if (n === "never") return ""
if (n === "always") return NOTIFY.texts.always
const own = typeof condition === "string" ? condition.split(/\s+/).filter(Boolean).join(" ").replace(/\.+$/, "").trim() : ""
return fillPrompt(NOTIFY.texts.when, { condition: own || NOTIFY.default_condition })
}
/** Whether report_write is in a session's list, and what a call meets (reports.md §2): only a
* session a schedule opened for its run, when it notifies at all, and never a subagent's; in
* such a session a turn that is not the schedule's answers the tool's unavailable text. */
export function reportTool(o: { session: string; notify?: unknown; turn: string; subagent?: boolean }): "offered" | "absent" | "unavailable" {
if (o.session !== "scheduled" || o.subagent || notifyOf(o.notify) === "never") return "absent"
return o.turn === "run" ? "offered" : "unavailable"
}
/** What report_write answers: the first report of a run is filed, a later one replaces it. */
export const reportResult = (calls: number) => (calls > 1 ? NOTIFY.result.replaced : NOTIFY.result.filed)
/** A report_write call's arguments as a report. */
export function asReport(args: { title?: unknown; body?: unknown; summary?: unknown; importance?: unknown }): Report {
return { title: String(args.title ?? "").trim(), body: String(args.body ?? ""), summary: String(args.summary ?? "").trim(), importance: args.importance === "high" ? "high" : "normal" }
}
const cutTo = (s: string, max: number) => ([...s].length > max ? `${[...s].slice(0, max - 1).join("")}…` : s)
/** What a run leaves (reports.md §4): its report — the last one written; under `always`, with
* none written, the answer filed as one — and the history line. The retired sentinel is read as
* nothing to tell (§5). */
export function runLeaves(o: { notify?: unknown; title: string; calls: Parameters<typeof asReport>[0][]; answer: string }): { report: Report | null; note: string } {
const notify = notifyOf(o.notify)
const answer = (isSilent(o.answer ?? "") ? stripSentinel(o.answer) : (o.answer ?? "")).trim()
const first = answer.split(/\r?\n/).map((l) => l.trim()).find(Boolean)
const note = first ? cutTo(first, NOTIFY.note_max) : SCHEDULED.texts.no_reply
if (o.calls.length) return { report: asReport(o.calls[o.calls.length - 1]!), note }
if (notify !== "always" || !answer) return { report: null, note }
const paragraph = answer.split(/\r?\n\s*\r?\n/)[0]!.split(/\s+/).filter(Boolean).join(" ")
return { report: { title: o.title, body: answer, summary: cutTo(paragraph, NOTIFY.summary_max), importance: "normal" }, note }
}
+17 -7
View File
@@ -14,8 +14,9 @@ import type { ImagePart } from "../provider/types.ts"
import { commandSet, sourcesOf } from "../session/commands.ts"
import type { PlanReply, PlanRequest } from "../tool/plan_submit.ts"
import type { QuestionReply, QuestionRequest } from "../tool/ask_user.ts"
import { readLevel } from "../provider/effort.ts"
import { clampMode, effortOf, markRemote, permissionParams, planParams, planReplyFrom, questionParams, questionReplyFrom, replyFrom, STOP, type PromptResult } from "./agent.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript } from "./jobs.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import type { SessionContext } from "../app.ts"
import { sessionTurnFile, sessionTurns, type TurnLog } from "./turns.ts"
import { dropAttachments, preparePrompt } from "./prompt.ts"
@@ -390,7 +391,7 @@ export class Share {
// is the instance's.
modelConnection: this.app.engine.model.connectionName,
mode: this.app.engine.mode,
effort: this.app.engine.effort ?? "off",
effort: this.app.engine.effort,
busy: Boolean(this.app.turns.current),
explicit,
},
@@ -453,7 +454,7 @@ export class Share {
return
}
if (this.sharedId && this.hub && this.app.engine.sessionId === this.sharedId) {
this.hub.notify("hub/event", { sessionId: this.sharedId, event: e })
this.hub.notify("hub/event", { sessionId: this.sharedId, event: e.type === "team" ? { ...e, tree: treeOf(this.app) } : e })
if (e.type === "task" && e.state === "end") this.sendCommands()
}
}
@@ -469,8 +470,8 @@ export class Share {
const turnId = typeof p?.turnId === "string" && p.turnId ? p.turnId : crypto.randomUUID()
// A turn id taken already: the original's answer.
if (this.turns.has(turnId)) return this.turns.run(turnId, () => Promise.reject(new Error("unreachable")))
// What the client holds for the session (its instructions, personalization, library scope,
// prototypes), passed on by the hub: read into the prompt here as the service would.
// What the client holds for the session (its instructions, personalization, library scope),
// passed on by the hub: read into the prompt here as the service would.
if (p?.context && typeof p.context === "object") this.app.setContext(p.context as SessionContext, typeof p?.instance === "string" ? p.instance : undefined)
// The blocks, expanded here as this terminal's keyboard would; `text` from a hub of
// an earlier build.
@@ -519,6 +520,15 @@ export class Share {
return jobSend(this.app, p?.id, p?.text)
case "transcript":
return jobTranscript(this.app, p?.id)
// Spec 3.4.0 (capability tree): the subagent tree, through the hub as the jobs go.
case "team":
return teamView(this.app, p?.since)
case "team_transcript":
return teamTranscript(this.app, p?.id)
case "team_findings":
return teamFindings(this.app, p?.id)
case "team_stop":
return teamStop(this.app, p?.id)
default:
throw new RpcError(INVALID_PARAMS, `no such job operation: ${String(p?.op ?? "")}`)
}
@@ -596,9 +606,9 @@ export class Share {
// same model as `deepseek/x`, and switching to it again would reset the effort.
if (typeof p?.model === "string" && p.model && this.app.canonicalRef(p.model) !== this.app.engine.model.ref) this.app.switchModel(p.model)
const effort = effortOf(p?.effort)
if (effort !== undefined) this.app.engine.effort = effort === "off" ? null : effort
if (effort !== undefined) this.app.engine.effort = readLevel(this.app.engine.model, effort)
this.hooks.changed()
return { model: this.app.engine.model.ref, effort: this.app.engine.effort ?? "off" }
return { model: this.app.engine.model.ref, effort: this.app.engine.effort }
})
}
}
+27 -4
View File
@@ -9,7 +9,7 @@
// files (which it sources), zsh a ZDOTDIR whose files source the user's own and hand ZDOTDIR back,
// fish a command run after its config. Any other shell starts as it did before, without marks.
// `remote.terminal_integration: false` turns it off.
import { mkdirSync, rmSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"
import { basename, join } from "node:path"
import { paths } from "../config/paths.ts"
@@ -167,11 +167,34 @@ export interface ShellLaunch {
cleanup(): void
}
/** The shell a terminal opened from the web UI runs, and how it is started without the marks.
* POSIX: `$SHELL` when it is there, else the first of bash, zsh and sh that is — as a login
* shell (`-l`). Windows: PowerShell 7 (`pwsh`), then Windows PowerShell, then `%ComSpec%` /
* `cmd.exe` — none of which takes `-l`. Undefined when the machine has none of them. */
export function pickShell(
os: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
has: (path: string) => boolean = existsSync,
which: (cmd: string) => string | null = Bun.which,
): { shell: string; args: string[] } | undefined {
if (os === "win32") {
for (const name of ["pwsh.exe", "powershell.exe"]) {
const found = which(name)
if (found) return { shell: found, args: ["-NoLogo"] }
}
const cmd = (env.ComSpec && has(env.ComSpec) ? env.ComSpec : undefined) ?? which("cmd.exe")
return cmd ? { shell: cmd, args: [] } : undefined
}
const shell = [env.SHELL, "/bin/bash", "/bin/zsh", "/bin/sh"].find((s): s is string => !!s && has(s))
return shell ? { shell, args: ["-l"] } : undefined
}
/** How to start `shell` for terminal `id`: with the marks when it is bash, zsh or fish and
* `integration` is on; as `$SHELL -l` otherwise. */
export function shellLaunch(shell: string, id: string, integration: boolean, env: NodeJS.ProcessEnv = process.env): ShellLaunch {
* `integration` is on; as `$SHELL -l` (or with `plainArgs`, for a shell that takes no `-l`)
* otherwise. */
export function shellLaunch(shell: string, id: string, integration: boolean, env: NodeJS.ProcessEnv = process.env, plainArgs: string[] = ["-l"]): ShellLaunch {
const kind = shellKind(shell)
const plain: ShellLaunch = { kind, integration: false, argv: [shell, "-l"], env: {}, cleanup: () => {} }
const plain: ShellLaunch = { kind, integration: false, argv: [shell, ...plainArgs], env: {}, cleanup: () => {} }
if (!integration || kind === "other") return plain
const dir = join(paths.state, "terminal", id.replace(/[^\w-]/g, "_"))
const cleanup = () => rmSync(dir, { recursive: true, force: true })
+292 -61
View File
@@ -12,14 +12,15 @@ import { boardSummary } from "./project/board.ts"
import { unsafeProjectFile } from "./project/safe.ts"
import { Bus, type Asker } from "./bus/index.ts"
import { loadConfig, type Loaded } from "./config/load.ts"
import type { Effort, Mode } from "./config/schema.ts"
import type { Mode } from "./config/schema.ts"
import { DEFAULT_RULES, toRules } from "./permission/evaluate.ts"
import { hardlineRules } from "./permission/hardline.ts"
import { defaultEffort } from "./provider/effort.ts"
import { clientFor, familyOf, resolveModel } from "./provider/index.ts"
import { assembleSystem, instructionFiles, knowledgeScope } from "./prompt/assemble.ts"
import { subagentModel, type ModelInfo } from "./team/subagents.ts"
import { assembleSystem, instructionFiles, knowledgeScope, modeText } from "./prompt/assemble.ts"
import type { Changing } from "./session/prefix.ts"
import { describeRepo, repoState } from "./git/repo.ts"
import { findProject, persistProjectRule, trustOf, type Project } from "./project/root.ts"
import { findProject, forgetProjectRule, persistProjectRule, trustOf, type Project } from "./project/root.ts"
import type { Message } from "./provider/types.ts"
import { Engine } from "./session/engine.ts"
import { agents, NOT_FOR_SUBAGENTS } from "./project/agents.ts"
@@ -41,17 +42,24 @@ import { Library, type Embedder } from "./library/store.ts"
import { instances as lembasInstances, keyFile as lembasKeyFile } from "./lembas/login.ts"
import { PERSONAL_KEYS, personalConfig, pushPersonalization } from "./lembas/personal.ts"
import type { Plan } from "./plan/plan.ts"
import { LIBRARY_SERVER } from "./mcp/index.ts"
import { LIBRARY_SERVER, mcpInstructions } from "./mcp/index.ts"
import { clean as cleanText, errorLine } from "./mcp/clean.ts"
import { customCommands } from "./project/commands.ts"
import { TUI_COMMAND_NAMES } from "./session/commands.ts"
import type { McpServer } from "./config/schema.ts"
import { embedderFor } from "./library/embed.ts"
import { effortsFor } from "./provider/effort.ts"
import { isLevel, levelsFor, readLevel, type Level } from "./provider/effort.ts"
import { memberTools as memberToolsOf, readingBashByDefault, Team, TEAM, TEAM_TOOLS, type Capacity, type TeamAgent } from "./team/team.ts"
import { whoDecides } from "./team/delegation.ts"
import { TeamRuntime, type MemberHandle } from "./team/runtime.ts"
export interface AppOptions {
cwd: string
model?: string
mode?: Mode
/** undefined = the model's default; "off" = none */
effort?: Effort | "off"
/** The effort level asked for (an effort, "off" or "default"); undefined, or one the model does
* not offer: its start level. */
effort?: string
asker: Asker
store?: Store | false
/** Nobody can answer an approval (headless, no --yes). Said in the system prompt up front. */
@@ -83,8 +91,6 @@ export interface SessionContext {
instructions?: string
/** The account's personalization, in place of this device's; null: the device's own. */
personalization?: { personality: string; personality_custom: string; instructions: string } | null
/** Whether the model may write a prototype, and what a page may load. */
prototypes?: { offered: boolean; sources: string }
}
export interface App {
@@ -148,6 +154,8 @@ export interface App {
context: SessionContext
/** Replace it (`{}`: none), naming the instance it came from for the prompt's heading. */
setContext(ctx: SessionContext, from?: string): void
/** The session's team (spec 3.2.0, team.md): its rules and its members at work. */
team: TeamRuntime
/** The chat a session the client opened belongs to (its id): sent with every call to the server's
* memory, which answers in that chat's data group (harness/acp.md *Memory*); undefined for a
* session of this device's own. The memory for the prompt is read again in it. */
@@ -197,8 +205,15 @@ function openInBrowser(url: string): boolean {
}
}
/** A model as the subagent rules see it (subagents.md): its names and what its server can do at once. */
function modelInfo(m: ResolvedModel): ModelInfo {
return { ref: m.ref, id: m.id, name: m.spec.name, capacity: { parallel: m.spec.parallel, single_session: m.spec.single_session, group: m.spec.group } }
}
/** Tools the spec offers to subagents only (`offered: subagent`): never a session's own model's. */
export const SUBAGENT_ONLY = new Set(Object.values(TOOL_SPECS).filter((t) => t.offered === "subagent").map((t) => t.name))
/** Spec 3.4.0: tools the spec offers to the main agent only (`offered: main`): never a subagent's. */
export const MAIN_ONLY_TOOLS = new Set(Object.values(TOOL_SPECS).filter((t) => t.offered === "main").map((t) => t.name))
const MODE_RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
export function stricterMode(a: Mode | undefined, b: Mode): Mode {
@@ -214,13 +229,10 @@ export function createApp(o: AppOptions): App {
// An untrusted project is read-only: plan mode, and its own config is ignored.
let mode: Mode = o.mode ?? loaded.config.mode ?? "manual"
if (trust === "readonly") mode = "plan"
// `effort:` in config when this model takes it, else the model's own default.
const startEffort = (m: ResolvedModel) => {
const e = loaded.config.effort
if (e === "off") return null
return e && effortsFor(m).includes(e) ? e : defaultEffort(m)
}
const effort = o.effort === "off" ? null : (o.effort ?? startEffort(model))
// `effort:` in config when this model offers that level, else the model's own start level
// (harness models/schema.json `levels`).
const startEffort = (m: ResolvedModel): Level => readLevel(m, loaded.config.effort)
const effort: Level = o.effort !== undefined && isLevel(o.effort) && (levelsFor(model).levels as string[]).includes(o.effort) ? o.effort : startEffort(model)
// One object for the session's lifetime, so a setting changed later reaches the tools.
loaded.config.search ??= {}
const bus = o.bus ?? new Bus()
@@ -253,8 +265,9 @@ export function createApp(o: AppOptions): App {
return s ? describeRepo(s) : undefined
}
// Memory and skills go into the system prompt as they stood when the session started: a write
// during the session reaches the file, not the prompt (Hermes' frozen snapshot).
// Memory and skills go into the system prompt as they stood when it was made: a write during the
// session reaches the file, not the prompt (Hermes' frozen snapshot) — the person's own edit
// reaches the model as a note (session/prefix.ts).
const memoryOn = loaded.config.memory?.enabled !== false
const memory = new MemoryStore({ memory: loaded.config.memory?.memory_chars ?? DEFAULT_LIMITS.memory, user: loaded.config.memory?.user_chars ?? DEFAULT_LIMITS.user })
const projectDir = () => (trusted && existsSync(project.dir) ? project.dir : undefined)
@@ -263,17 +276,18 @@ export function createApp(o: AppOptions): App {
? new MemoryStore({ memory: loaded.config.memory?.memory_chars ?? DEFAULT_LIMITS.memory, user: 0 }, join(project.dir, "local"), { memory: "PROJECT MEMORY (this project only)" })
: undefined
const skillList = () => loadSkills({ projectDir: projectDir(), external: loaded.config.skills?.external_dirs, disabled: loaded.config.skills?.disabled })
// Everything in the system prompt that could change during a session is taken once, here, for
// the same reason as the git block: the prompt must stay byte for byte the same, or the server
// reads the whole conversation again.
// What the system prompt holds that nothing during the session updates: taken as the session
// starts, for the same reason as the git block. The engine makes the prompt once and resends it
// byte for byte (harness context.md §10); what may change and is said in a note when it does —
// memory, instruction files, personality, MCP instructions — is read by `changing` below.
const freeze = () => ({
// The server's memory, when it is the server's: as last read for this session (readServerMemory).
memory: !memoryOn ? undefined : serverMemory !== undefined ? serverMemory.text : [memory.snapshot(), projectMemory?.block("memory") ?? ""].filter(Boolean).join("\n\n"),
skills: skillLines(skillList()),
git: gitSummary(),
tasks: projectDir() && !unsafeProjectFile(join(project.dir, "tasks.md"), project.root) ? boardSummary(project.dir) : undefined,
files: instructionFiles(o.cwd, project.root, loaded.instructions),
})
/** The memory block as it is now: the server's when it is the server's (as last read for this
* session, readServerMemory), else this machine's files; undefined when memory is off. */
const memoryNow = () => (!memoryOn ? undefined : serverMemory !== undefined ? serverMemory.text : [memory.snapshot(), projectMemory?.block("memory") ?? ""].filter(Boolean).join("\n\n"))
// `library: lembas`: the server keeps the memory (acp.md *Memory*); its entries for the prompt are
// read from it as a session starts. Until the read answers, none.
const memoryOnServer = loaded.config.library === "lembas" && memoryOn
@@ -299,7 +313,7 @@ export function createApp(o: AppOptions): App {
const lembasLibrary = memoryOnServer ? lembasLibraryServer(loaded.warnings) : undefined
if (lembasLibrary) loaded.mcp[LIBRARY_SERVER] = lembasLibrary
// Without a way to the server's memory, this machine's is used for now.
if (memoryOnServer && !lembasLibrary) serverMemory = undefined, frozen = freeze()
if (memoryOnServer && !lembasLibrary) serverMemory = undefined
const mcp = new McpManager(loaded.mcp, {
root: project.root,
version: VERSION,
@@ -336,12 +350,31 @@ export function createApp(o: AppOptions): App {
const knowledgeOffered = () => library.bases().some((b) => b.documents > 0 && (!libraryCtx.bases || libraryCtx.bases.includes(b.name)))
/** The library block's scope: this machine's `knowledge:`. */
const libraryBlock = () => (knowledgeOffered() ? { scope: knowledgeScope(libraryCtx.bases) } : undefined)
/** Prototypes: offered by the client for this session, or by `prototypes: true` for a terminal's. */
const prototypesBlock = () => (context.prototypes?.offered || (!context.prototypes && loaded.config.prototypes === true) ? { sources: context.prototypes?.sources ?? "" } : undefined)
/** The three personal keys this session uses: the client's for it, else the config's. */
const personal = () => (context.personalization ? personalConfig({ enabled: true, available: true, ...context.personalization }) : loaded.config)
const system = (m: Mode, current: ResolvedModel, subagent?: { name: string; instructions: string; report: boolean; skills: boolean; recall: boolean }, at?: { cwd: string; root: string }, plan?: Plan) =>
assembleSystem({
/** What may change during the session, as it is now (session/prefix.ts `Changing`): what the
* prompt is made from, and what a note compares. A subagent's prompt holds no memory and no
* personality; a worktree subagent reads its own checkout's instruction files. */
type Source = { files: { path: string; text: string; chain?: true }[]; memory?: string; personality?: string; userInstructions?: string; instance?: { name: string; instructions: string }; mcp: Record<string, string> }
const changing = (subagent?: boolean, at?: { cwd: string; root: string }): Changing => {
const files = instructionFiles(at?.cwd ?? o.cwd, at?.root ?? project.root, loaded.instructions)
const p = subagent ? {} : personalityOf(personal())
const src: Source = {
files,
memory: subagent ? undefined : memoryNow(),
...p,
...(!subagent && context.instructions ? { instance: { name: contextFrom, instructions: context.instructions } } : {}),
mcp: mcp.serverInstructions(),
}
const named: Record<string, string> = Object.fromEntries(files.map((f) => [f.path, f.text]))
// What a note names the person's own instructions by (loop.json context.note.personal).
if (src.userInstructions) named[LOOP.context.note.personal] = src.userInstructions
if (src.instance) named[`Instructions from ${src.instance.name}`] = src.instance.instructions
return { memory: src.memory ?? "", personality: src.personality ?? "", files: named, mcp: src.mcp, source: src }
}
const system = (m: Mode, current: ResolvedModel, ch: Changing, subagent?: { name: string; instructions: string; report: boolean; skills: boolean; recall: boolean }, at?: { cwd: string; root: string }, plan?: Plan, member?: { id: string; name: string; manager: string; role: string; goal: string; lead: boolean }) => {
const src = ch.source as Source
return assembleSystem({
modelRef: current.ref,
family: familyOf(current),
cwd: at?.cwd ?? o.cwd,
@@ -355,22 +388,28 @@ export function createApp(o: AppOptions): App {
// A worktree subagent works elsewhere: its own snapshot, taken as it starts.
git: at ? gitSummary() : frozen.git,
tasks: frozen.tasks,
files: at ? undefined : frozen.files,
files: src.files,
subagent,
memory: frozen.memory,
memory: src.memory,
// The skills block tells of skill_view; a subagent without the tool gets no block.
skills: subagent && !subagent.skills ? undefined : frozen.skills,
manageSkills: true,
// Read on every prompt: /personality and /settings change it without a restart.
...personalityOf(personal()),
mcp: mcp.instructions(),
// As the prompt is made; /personality and /settings later change it by a note.
personality: src.personality,
userInstructions: src.userInstructions,
mcp: mcpInstructions(src.mcp),
roster: roster(current.ref),
plan,
...(context.instructions ? { instance: { name: contextFrom, instructions: context.instructions } } : {}),
...(src.instance ? { instance: src.instance } : {}),
library: libraryBlock(),
prototypes: prototypesBlock(),
context: subagent ? subagent.recall : true,
...(member ? { member } : {}),
// The lead's prompt says how to lead whenever the team tools are offered (team.md §10).
teamLead: !subagent && teamRt.team.offered,
})
}
/** A mode's text for a note, as the prompt would have it. */
const modeNote = (m: Mode) => modeText(m, planDir, o.unattended ? UNATTENDED[m] : undefined)
// The other configured models, for the task tool's `model`, or a switch.
const roster = (current: string) =>
loaded.refs
@@ -392,6 +431,7 @@ export function createApp(o: AppOptions): App {
const inWords = (sec: number) => (sec % 60 === 0 ? `${sec / 60} minute${sec === 60 ? "" : "s"}` : `${sec} seconds`)
const vars: Record<string, Record<string, string>> = {
task: { agents: agentList.map((a) => `${a.name} — ${a.description}`).join("; ") },
team_add: { agents: agentList.map((a) => `${a.name} — ${a.description}`).join("; ") },
bash: {
timeout: inWords(loaded.config.limits?.bash_timeout ?? 120),
timeout_max: inWords(600),
@@ -439,9 +479,24 @@ export function createApp(o: AppOptions): App {
// The model asked for (task's `model`), else the agent's own, else the session's — and whether
// its server can take it beside the session's and beside every subagent already running
// (src/session/capacity.ts), before anything is made.
const m = opts.model ? resolveModel(loaded, opts.model) : spec.model ? resolveModel(loaded, spec.model) : engine.model
const refused = capacityRefusal(engine.model, m) || registry.running(jobsSessionId()).filter((j) => j.kind === "subagent" && j.subagent).map((j) => capacityBeside(j.subagent!.engine.model, m)).find(Boolean)
if (refused) throw new ToolError(`${refused} Do this part yourself, or hand it to a model on another connection.`)
const member = opts.member
// Spec 3.3.0 (subagents.md): the session's model, unless the person named another; an agent
// file's own `model` is not used. A member's model was judged by team_add.
let m: ResolvedModel
if (member) m = opts.model ? resolveModel(loaded, opts.model) : engine.model
else {
const wanted = opts.model ? resolveModel(loaded, opts.model) : undefined
const r = subagentModel(modelInfo(engine.model), wanted && modelInfo(wanted), engine.personSaid())
if ("refused" in r) throw new ToolError(r.refused)
m = wanted && wanted.ref === r.model ? wanted : engine.model
}
// A team's member is not refused for capacity: the team gave it its slot (team.md §8).
if (!member) {
const running = registry.running(jobsSessionId()).filter((j) => j.kind === "subagent" && j.subagent && !j.team)
const onIt = running.filter((j) => j.subagent!.engine.model.ref === m.ref).length
const refused = capacityRefusal(engine.model, m, onIt) || running.map((j) => capacityBeside(j.subagent!.engine.model, m, onIt)).find(Boolean)
if (refused) throw new ToolError(`${refused} Wait for one to finish, or do this part yourself.`)
}
// A checkout and branch of its own, when asked for (the task's worktree, the agent's isolation).
let wt: Worktree | undefined
if (opts.worktree || spec.isolation === "worktree") {
@@ -469,8 +524,18 @@ export function createApp(o: AppOptions): App {
}
: perm
// `report` is every subagent's: its way of speaking to the main agent before its final reply.
const childTools = [...tools.filter((t) => !NOT_FOR_SUBAGENTS.has(t.name) && (!spec.tools || spec.tools.includes(t.name))), ...BUILTIN_TOOLS.filter((t) => SUBAGENT_ONLY.has(t.name))]
const description = opts.description ?? prompt.split("\n")[0]!.slice(0, 60)
// A subagent of the tree also has its team tools (spec 3.4.0 §8: whoami, read, send, findings,
// finish, and request with request options) — never the main agent's (`offered: main`); a task
// subagent has none of them.
const memberTools = member ? memberToolsOf(member) : []
const isTeamTool = (n: string) => (TEAM_TOOLS as readonly string[]).includes(n)
const childTools = [
...tools.filter((t) => !NOT_FOR_SUBAGENTS.has(t.name) && !MAIN_ONLY_TOOLS.has(t.name) && (!isTeamTool(t.name) || memberTools.includes(t.name)) && (!spec.tools || spec.tools.includes(t.name) || memberTools.includes(t.name))),
...BUILTIN_TOOLS.filter((t) => SUBAGENT_ONLY.has(t.name) && (!isTeamTool(t.name) || memberTools.includes(t.name))),
]
// Its mode: the one the main agent gave it, made stricter by its agent's own (explore reads).
if (member) member.mode = stricterMode(spec.mode, member.mode)
const description = member ? `${member.name}: ${member.role}` : (opts.description ?? prompt.split("\n")[0]!.slice(0, 60))
const ownerSession = jobsSessionId()
const childRow = store?.createSession(at?.root ?? project.root, m.ref, engine.sessionId)
if (childRow) store!.setTitle(childRow.id, `${spec.name}: ${description}`)
@@ -479,7 +544,7 @@ export function createApp(o: AppOptions): App {
let job: Job
// The asker is the session's; a child's ask says which subagent it comes from.
const askerFor = (): Asker => ({
ask: (req) => o.asker.ask({ ...req, source: { jobId: job.id, agent: spec.name, description } }),
ask: (req) => o.asker.ask({ ...req, source: { jobId: job.id, agent: spec.name, description, ...(member ? { subagent: { id: member.id, name: member.name, position: member.role } } : {}) } }),
get question() {
return o.asker.question
},
@@ -495,8 +560,9 @@ export function createApp(o: AppOptions): App {
tools: childTools,
store,
sessionId: childRow?.id,
// An agent's own mode can make it stricter than its parent, never looser.
mode: stricterMode(spec.mode, engine.mode),
// An agent's own mode can make it stricter than its parent, never looser. A subagent of the
// tree runs in the mode the main agent gave it (spec 3.4.0 §7), set above.
mode: member ? member.mode : stricterMode(spec.mode, engine.mode),
effort: m.ref === engine.model.ref ? engine.effort : startEffort(m),
maxSteps: loaded.config.limits?.subagent_steps ?? LOOP.jobs.subagent_steps.default,
compaction,
@@ -505,16 +571,36 @@ export function createApp(o: AppOptions): App {
...baseToolCtx(),
...(at ? { root: at.root, cwd: at.cwd, projectDir: undefined } : {}),
jobs: { registry, owner: () => ({ sessionId: childSessionId, job }) },
...(member ? { team: { runtime: teamRt, as: member.name } } : {}),
},
...(member
? {
team: {
fix: () => teamRt.team.offered,
offered: () => teamRt.team.offered,
refuse: (tool: Tool, args: unknown) => teamRt.refuse(member.name, tool, args),
// Spec 3.4.0 §7: itself, the main agent through a request, or the person.
permit: (request, ctx) => {
const a = teamRt.team.get(member.name)
return whoDecides(request, { ctx, mode: a?.mode ?? member.mode, main: engine.mode, request: a?.request ?? [], grants: a?.grants ?? [], unattended: o.unattended })
},
contextFull: (used: number, window: number) => (window ? teamRt.contextFull(member.name) : "go"),
ended: () => teamRt.hasEnded(member.name),
},
}
: {}),
steerMark: MARKS.to_subagent,
system: (mode, current, plan) =>
changing: () => changing(true, at),
modeText: modeNote,
system: (mode, current, plan, ch) =>
system(
mode,
current,
ch,
{
name: spec.name,
instructions: wt
? `${spec.instructions}\n\nYou are working in a separate checkout of the repository, at ${at!.root}, on the branch ${wt.branch} (made from the last commit — uncommitted work of the main agent is not here). Work only inside it. When you finish, your changes are committed on that branch for the main agent to merge: do not commit, merge or push yourself.`
? `${spec.instructions}\n\nYou are working in a separate checkout of the repository — its root is your project root, so relative paths reach it — on the branch ${wt.branch} (made from the last commit — uncommitted work of the main agent is not here). Work only inside it. When you finish, your changes are committed on that branch for the main agent to merge: do not commit, merge or push yourself.`
: spec.instructions,
report: childTools.some((t) => t.name === "report"),
skills: childTools.some((t) => t.name === "skill_view"),
@@ -522,6 +608,7 @@ export function createApp(o: AppOptions): App {
},
at,
plan,
member ? { id: member.id, name: member.name, manager: member.manager ?? TEAM.names.lead, role: member.role, goal: member.goal, lead: member.leads } : undefined,
),
})
// Its own background commands wake it at its next step while it runs; once it has ended they
@@ -537,7 +624,14 @@ export function createApp(o: AppOptions): App {
const end = registry.finishSubagent(job, { reason, report: text, ...(error ? { error } : {}), ...(worktree ? { worktree } : {}) })
return { text: worktree ? `${text}\n\n[worktree] ${worktree}` : text, steps: job.steps ?? 0, tools: job.tools ?? 0, reason, ...(error ? { error } : {}), ...(end.stopped ? { stopped: end.stopped } : {}) }
}
const run = (text: string) => child.prompt(text).then(finish, (e) => (job.lastError = (e as Error).message, finish("error")))
// A task subagent started inside a team counts toward its size and holds a slot while it runs
// (team.md §3, §8).
const counted = (p: Promise<SubagentResult>) => {
if (member || !teamRt.team.offered) return p
const id = teamRt.team.taskStart(TEAM.names.lead, m.ref)
return p.finally(() => teamRt.team.taskDone(id))
}
const run = (text: string, machine = false, steps?: number) => counted(child.prompt(text, [], text, { ...(machine ? { machine: true as const } : {}), ...(steps ? { maxSteps: steps } : {}) }).then(finish, (e) => (job.lastError = (e as Error).message, finish("error"))))
const handle: SubagentHandle = {
bus: childBus,
engine: child,
@@ -545,7 +639,34 @@ export function createApp(o: AppOptions): App {
restart: (text) => run(text).then(() => undefined),
cancel: () => child.cancel(),
}
job = registry.startSubagent({ sessionId: ownerSession, ownerCallId: opts.callId, ownerJobId: baseOwner().job?.id, agent: spec.name, model: m.ref, description, handle, childSessionId, silent: !opts.background })
job = registry.startSubagent({ sessionId: ownerSession, ownerCallId: opts.callId, ownerJobId: baseOwner().job?.id, agent: spec.name, model: m.ref, description, handle, childSessionId, silent: !opts.background || member !== undefined })
if (member) {
// A member's turn that ends is its report (team.md §5): the team, not a job note, carries it.
job.team = member.name
member.jobId = job.id
// Its progress and context use, for the tree (spec 3.4.0 §12).
childBus.on((e) => {
if (e.type === "phase") {
teamRt.team.setProgress(member.name, e.progress)
teamRt.notify()
} else if (e.type === "usage" && !e.child && e.context) {
teamRt.team.setContext(member.name, e.used ?? e.usage.input + e.usage.output, e.context)
teamRt.notify()
}
})
const memberRun = (text: string, machine: boolean, steps?: number) => {
if (job.state !== "running") registry.restartSubagent(job)
void run(text, machine, steps).then((r) => {
const leftover = [...child.takeNotes(), ...child.takeInbox()]
const reason = r.reason === "error" ? `error — ${r.error ?? "unknown"}` : r.reason
if (r.reason !== "cancelled") teamRt.memberDone(member.name, r.text, reason, leftover)
})
}
const mh: MemberHandle = { engine: child, run: (text) => memberRun(text, true), cancel: () => child.cancel(), final: (text) => memberRun(text, true, TEAM.context.final_steps) }
teamRt.attach(member.name, mh)
memberRun(prompt, false)
return { id: job.id, done: Promise.resolve({ text: "", steps: 0, tools: 0, reason: "stop" }), member: mh }
}
// A synchronous subagent goes with its parent's turn (Esc stops both); a background one does not.
const onAbort = () => child.cancel()
opts.signal?.addEventListener("abort", onAbort, { once: true })
@@ -571,10 +692,92 @@ export function createApp(o: AppOptions): App {
budget: { wall_seconds: loaded.config.limits?.wall_seconds, output_bytes: loaded.config.limits?.output_bytes, completion_tokens: loaded.config.limits?.completion_tokens },
compaction,
perm,
toolCtx: { ...baseToolCtx(), jobs: { registry, owner: baseOwner } },
system: (m, current, plan) => system(m, current, undefined, undefined, plan),
toolCtx: { ...baseToolCtx(), jobs: { registry, owner: baseOwner }, team: { get runtime() { return teamRt }, as: TEAM.names.lead } },
system: (m, current, plan, ch) => system(m, current, ch, undefined, undefined, plan),
team: {
fix: (ref, offered) => teamRt.team.fix(ref, offered),
offered: () => teamRt.team.offered,
refuse: (tool, args) => teamRt.refuse(TEAM.names.lead, tool, args),
note: () => teamRt.team.noteLines(),
forget: () => teamRt.team.forgetTold(),
beforeTurn: (signal) => teamRt.beforeLeadTurn(signal),
},
changing: () => changing(),
modeText: modeNote,
// The configured MCP servers, up to loop.json's wait: their tools in the first list.
beforeFirst: () => Promise.race([mcpReady.catch(() => {}), Bun.sleep(LOOP.context.mcp_wait_ms)]),
persistRule: trusted ? (rule) => persistProjectRule(project, rule) : undefined,
spawn,
forgetRule: trusted ? (rule) => forgetProjectRule(project, rule) : undefined,
// subagents: false — no task tool, and no team (team.md §2).
spawn: loaded.config.subagents === false ? undefined : spawn,
})
// The session's team (spec 3.2.0, team.md): its size from the configuration (the cap the global
// one's), the capacity of each model as the server says it.
const capacityOf = (ref: string): Capacity => {
try {
const s = ref === engine.model.ref ? engine.model.spec : resolveModel(loaded, ref).spec
return { parallel: s.parallel, single_session: s.single_session, group: s.group }
} catch {
return {}
}
}
// Every model the person may use: the server's, as the login read them (subagents.md §4).
const usableModels = () => loaded.refs.map((r) => r.ref)
// The size as set while the process runs (any scope): a new or resumed session keeps it.
const teamSize: { min?: number; max?: number } = {}
const newTeam = () =>
new Team({
min: teamSize.min ?? loaded.config.agents?.min,
max: teamSize.max ?? loaded.config.agents?.max,
cap: loaded.config.agents?.cap,
subagents: loaded.config.subagents !== false,
model: engine.model.ref,
capacity: capacityOf,
models: usableModels,
leadState: "idle",
readingBash: (command) => readingBashByDefault(command, project.root),
mode: engine.mode,
steps: { main: loaded.config.limits?.steps ?? LOOP.steps.default, sub: loaded.config.limits?.subagent_steps ?? LOOP.jobs.subagent_steps.default },
})
const teamRt: TeamRuntime = new TeamRuntime({
team: newTeam(),
bus,
// spawn makes the member's engine and attaches it before its first await, so a message to it
// finds it at once.
spawnMember: (member: TeamAgent, text: string) => {
spawn(member.agent, text, { member, model: member.model, background: true, description: `${member.name}: ${member.role}` }).catch((e) => {
bus.emit({ type: "notice", level: "warn", message: `team: ${member.name} could not start: ${(e as Error).message}` })
teamRt.memberDone(member.name, "", `error — ${(e as Error).message}`, [])
})
},
lead: {
note: (text) => engine.note(text),
wake: (text) => wake(text, shownLine(text)),
waiting: (model) => engine.progress.set({ phase: "waiting_for_model", model: engine.model.spec.name ?? model, reason: "slots" }),
},
tools: () => tools,
resolve: (agent, model) => {
if (!agentList.some((a) => a.name === agent)) return { error: `There is no agent "${agent}". The agents are: ${agentList.map((a) => a.name).join(", ")}.` }
try {
// Spec 3.3.0 (subagents.md): the session's model, unless the person named another.
const wanted = model ? resolveModel(loaded, model) : undefined
const r = subagentModel(modelInfo(engine.model), wanted && modelInfo(wanted), engine.personSaid())
return "refused" in r ? { error: r.refused } : { model: r.model }
} catch (e) {
return { error: (e as Error).message }
}
},
})
// The lead's turn ended: it is idle, and its slot frees (team.md §8).
bus.on((e) => e.type === "done" && teamRt.leadDone())
// Spec 3.4.0: the main agent's mode reaches down the tree; its progress and context are in it.
bus.on((e) => {
if (e.type === "mode") teamRt.mainMode(e.mode)
else if (e.type === "phase") {
teamRt.team.setProgress(TEAM.names.lead, e.progress)
if (teamRt.team.hasMembers()) teamRt.notify()
} else if (e.type === "usage" && !e.child && e.context) teamRt.team.setContext(TEAM.names.lead, e.used ?? e.usage.input + e.usage.output, e.context)
})
// MCP tools join the engine's list as servers connect (the engine reads it at each prompt).
@@ -591,20 +794,23 @@ export function createApp(o: AppOptions): App {
for (const s of mcp.servers.values()) {
if (seen.get(s.name) === s.status) continue
seen.set(s.name, s.status)
if (s.status === "connected") bus.emit({ type: "notice", message: `MCP ${s.name}: connected — ${s.tools.length} tool${s.tools.length === 1 ? "" : "s"}${s.prompts.length ? `, ${s.prompts.length} prompt${s.prompts.length === 1 ? "" : "s"}` : ""}` })
else if (s.status === "failed" || s.status === "needs_auth") bus.emit({ type: "notice", message: `MCP ${s.name}: ${s.error ?? s.status}` })
// A server that connected says nothing: that is what was meant to happen, and the status
// bar counts it. One that did not gets one line that says which, why, and where to go.
// One line, cleaned and with nothing secret in it (it goes to every front end, the link's
// included), and promising only what every front end has: /mcp <name> shows the server.
if (s.status === "failed") bus.emit({ type: "notice", level: "warn", message: `MCP ${cleanText(s.name)} did not connect: ${errorLine(s.error) || "no reason given"} — /mcp ${cleanText(s.name)} shows more` })
else if (s.status === "needs_auth") bus.emit({ type: "notice", level: "warn", message: `MCP ${cleanText(s.name)} needs you to sign in — /mcp ${cleanText(s.name)}` })
}
})
const mcpReady = mcp.start()
/** The server's memory entries for the prompt (`lembas://memory`), read as a session starts, in
* the session's scope: put into the prompt while nothing has been sent yet, kept for the next
* session otherwise — the prompt does not change under a session. */
* 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
try {
const text = await mcp.readResource(LIBRARY_SERVER, MEMORY_RESOURCE, engine.o.toolCtx.libraryScope)
serverMemory = { text }
if (!engine.messages.length && memoryOn) frozen = { ...frozen, memory: 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` })
}
@@ -687,19 +893,28 @@ export function createApp(o: AppOptions): App {
},
live(key) {
if (key === "model") return engine.model.ref
if (key === "effort") return engine.effort ?? "off"
if (key === "effort") return engine.effort
if (key === "mode") return engine.mode
// The team's size as the session holds it (the cap applied).
if (key === "agents.min") return teamRt.team.min
if (key === "agents.max") return teamRt.team.max
return key.split(".").reduce<unknown>((x, k) => (x && typeof x === "object" ? (x as Record<string, unknown>)[k] : undefined), loaded.config)
},
check(key, v) {
if (key === "model" || key === "small_model") resolveModel(loaded, String(v))
if (key === "effort" && v !== "off" && !effortsFor(engine.model).includes(v as Effort))
throw new Error(`${engine.model.ref} takes ${effortsFor(engine.model).join(", ")} or off`)
if (key === "effort" && !(levelsFor(engine.model).levels as string[]).includes(String(v)))
throw new Error(`${engine.model.ref} offers the levels ${levelsFor(engine.model).levels.join(", ")}`)
if (key === "knowledge") for (const b of v as string[]) if (!library.base(b)) throw new Error(`there is no knowledge base "${b}" — lembas kb lists them`)
// The team's size (team.md §2): refused outside 1 ≤ min ≤ max ≤ cap, with the bounds.
if (key === "agents.min" || key === "agents.max") {
const t = teamRt.team
const no = Team.check(key === "agents.min" ? Number(v) : t.min, key === "agents.max" ? Number(v) : t.max, t.cap)
if (no) throw new Error(no)
}
},
apply(key, v) {
if (key === "model") switchModel(String(v))
else if (key === "effort") engine.effort = v === "off" ? null : (v as Effort)
else if (key === "effort") engine.effort = v as Level
else if (key === "mode") engine.mode = v as Mode
else if (key === "limits.steps") engine.o.maxSteps = Number(v)
else if (key === "busy_input") engine.busyInput = v as "steer" | "queue"
@@ -707,6 +922,14 @@ export function createApp(o: AppOptions): App {
else if (key === "limits.wall_seconds" || key === "limits.output_bytes" || key === "limits.completion_tokens") engine.o.budget = { ...engine.o.budget, [key.slice("limits.".length)]: Number(v) }
else if (key === "compaction.auto_at") compaction.autoAt = Number(v)
else if (key === "knowledge") libraryCtx.bases = (v as string[]).length ? (v as string[]) : undefined
else if (key === "agents.min" || key === "agents.max") {
// Said to the lead as a note on its next message (team.md §2), never in the prompt.
const t = teamRt.team
t.setSetting(key === "agents.min" ? Number(v) : t.min, key === "agents.max" ? Number(v) : t.max)
teamSize.min = t.min
teamSize.max = t.max
bus.emit({ type: "team" })
}
if (key !== "model" && key !== "effort" && key !== "mode") setIn(key, v)
bus.emit({ type: "setting", key, value: v })
},
@@ -731,6 +954,10 @@ export function createApp(o: AppOptions): App {
}
if (session) bus.emit({ type: "session", id: session.id, model: model.ref, mode })
// A custom command named like a command of the program is hidden by it: said once at start,
// with the way to it.
for (const cc of customCommands(trusted ? project.dir : undefined))
if ((TUI_COMMAND_NAMES as readonly string[]).includes(cc.name)) loaded.warnings.push(`the custom command /${cc.name} (${cc.file}) has the name of a built-in command, which wins — run it as /command ${cc.name}, or rename the file`)
for (const w of loaded.warnings) bus.emit({ type: "notice", message: w })
return {
bus,
@@ -758,6 +985,7 @@ export function createApp(o: AppOptions): App {
mcpReady,
small,
close: () => {
teamRt.stopAll()
detach()
for (const d of childDetach.splice(0)) d()
return mcp.close()
@@ -772,6 +1000,7 @@ export function createApp(o: AppOptions): App {
jobsSessionId,
jobs: () => registry.list(jobsSessionId()),
wake,
team: teamRt,
get context() {
return context
},
@@ -797,6 +1026,7 @@ export function createApp(o: AppOptions): App {
const s = store?.createSession(project.root, engine.model.ref)
keepCwd(s?.id)
standIn = `local_${crypto.randomUUID().slice(0, 8)}`
teamRt.reset(newTeam())
engine.newSession(s?.id)
turns.reset()
if (s) bus.emit({ type: "session", id: s.id, model: engine.model.ref, mode: engine.mode })
@@ -810,6 +1040,7 @@ export function createApp(o: AppOptions): App {
const before = engine.sessionId
frozen = freeze()
void readServerMemory()
teamRt.reset(newTeam())
engine.resume(id, store.context(id))
// A session from before titles gets its first prompt's line now, and the model's after the next reply.
firstShown = ""
+13 -4
View File
@@ -26,9 +26,10 @@ export type Event =
| { type: "tool_call_delta"; index: number; name?: string; argsDelta: string }
/** The server reading the prompt, before the reply (llama.cpp): tokens in all, from its cache, read so far. */
| { type: "progress"; total: number; cache: number; processed: number; ms: number }
| { type: "tool_start"; id: string; name: string; args: unknown }
/** `title`: the call's one short title (harness display.md §1), made from `args` when it starts. */
| { type: "tool_start"; id: string; name: string; args: unknown; title?: string }
| { type: "tool_end"; id: string; name: string; result: ToolResult; ms: number }
| { type: "tool_denied"; id: string; name: string; reason: string }
| { type: "tool_denied"; id: string; name: string; reason: string; args?: unknown; title?: string }
| {
type: "usage"
usage: Usage
@@ -47,7 +48,9 @@ export type Event =
| { type: "steered"; texts: string[]; ids?: string[] }
/** A task — one prompt, with every step and tool it takes — starts or ends; `turnId` as on `prompt`. */
| { type: "task"; state: "start" | "end"; turnId?: string }
| { type: "notice"; message: string; level?: "info" | "warn" }
/** `level` (tui/notices.ts): info — something happened; success; warn — needs attention (what a
* notice with no level is taken for); error. */
| { type: "notice"; message: string; level?: "info" | "success" | "warn" | "error"; /** Spec 3.4.0: a request that will be sent again. */ retry?: { reason: string; in: number; attempt?: number } }
/** Discard the reply streamed so far in this step: it is being retried. */
| { type: "retract" }
/** The session's plan was written, changed or cleared (plan_write, plan_update, /new). */
@@ -62,6 +65,12 @@ export type Event =
/** The note about that job was given to the model: inside a turn at its next step, or as the
* `machine` turn whose `prompt` follows. */
| { type: "job_note"; jobId: string; text: string }
/** The session's team changed (spec 3.2.0): a member added, started, finished or stopped, a
* message in the room. Read the team itself for what. */
| { type: "team" }
/** Spec 3.4.0 (harness/progress.md): what the session's agent is doing now, or null. A
* subagent's progress is in the tree (`team`). */
| { type: "phase"; progress: import("../session/progress.ts").Progress | null }
/** The permission mode changed from inside a turn (plan approved). */
| { type: "mode"; mode: Mode }
/** The session's model or effort changed, for whatever reason — /model, /effort, the settings
@@ -124,7 +133,7 @@ export interface Asker {
purpose?: string
/** Set when a subagent running as a background job asks, so the card can say which — it may
* ask while the session itself is idle. */
source?: { jobId: string; agent: string; description: string }
source?: { jobId: string; agent: string; description: string; /** Spec 3.4.0: a subagent of the tree. */ subagent?: { id: string; name: string; position: string } }
}): Promise<AskReply>
/** The ask_user tool. Absent: the tool reports that nobody can be asked. `callId`: the tool call's
* id, which keys the card on another screen. */
+79 -16
View File
@@ -3,15 +3,16 @@ import { existsSync } from "node:fs"
import { join } from "node:path"
import { parseArgs } from "node:util"
import { createApp } from "./app.ts"
import { expandSlash } from "./session/commands.ts"
import { attachmentsFor } from "./project/attach.ts"
import { ConfigError, loadConfig } from "./config/load.ts"
import { asMode, EFFORTS, MODES, type Effort, type Mode } from "./config/schema.ts"
import { asMode, EFFORTS, MODES, type Mode } from "./config/schema.ts"
import { isLocal, localRoot } from "./config/paths.ts"
import { SettingError } from "./config/settings.ts"
import { renderJson, renderPlain, settleJobs, terminalAsker } from "./headless.ts"
import { enterLocal, localFor, LocalError, localRefusal, localTmp, LOCAL_FLAGS } from "./project/local.ts"
import { findProject, setTrust, trustOf } from "./project/root.ts"
import { effortsFor } from "./provider/effort.ts"
import { isLevel, levelsFor } from "./provider/effort.ts"
import { clientFor, ModelError, NOT_LOGGED_IN, resolveModel } from "./provider/index.ts"
import { Store } from "./session/store.ts"
import { promptTitle } from "./session/title.ts"
@@ -45,12 +46,16 @@ Usage:
lembas serve --stdio an ACP agent on stdin/stdout, for an editor that speaks ACP
lembas service install | uninstall | status | logs [-f] | run
work from a LLeMbas instance as a background service (remote:)
lembas service scheduled [on|off]
Accept scheduled work: your schedules may run here as agent
turns (remote.scheduled, off by default)
lembas remote list | add <dir>… | remove <dir>… | enable | disable
| mode <manual|edit|auto|plan> | terminal <on|off> [--json]
| mode <manual|edit|auto|plan> | terminal <on|off> | scheduled <on|off> [--json]
what the instance may do here (remote:): the directories it may
work in (add turns remote work on), the most permissive mode,
terminals; a running service applies a change within seconds
(--json: one object, {enabled, roots, max_mode, terminal})
(--json: one object, {enabled, roots, max_mode, terminal,
scheduled})
lembas mcp [list] connect the MCP servers and list their tools and prompts
lembas mcp auth <server> sign in to a remote MCP server (OAuth)
lembas mcp logout <server> forget a server's stored sign-in
@@ -84,7 +89,7 @@ Local mode:
Options for run:
-m, --model conn/model model to use (default: config.yaml \`model\`)
--mode MODE manual | edit | auto | plan
-e, --effort LEVEL ${EFFORTS.join(" | ")} | off
-e, --effort LEVEL ${EFFORTS.join(" | ")} | off | default (one the model offers)
-y, --yes approve every ask (still never the hardline)
--json events as JSON lines
--reasoning show the model's reasoning
@@ -98,7 +103,7 @@ function fail(msg: string, code = 1): never {
}
async function loginCommand(cmd: "login" | "logout", args: string[]) {
const { codeEvent, codeInstructions, doneEvent, instances, isWebuiEntry, login, loginSummary, loginWithToken, logout, sync, LembasError } = await import("./lembas/login.ts")
const { codeEvent, codeInstructions, doneEvent, instances, isWebuiEntry, login, loginSummary, loginWithToken, logout, sync, LembasError, SignInRejected } = await import("./lembas/login.ts")
const { values, positionals } = parseArgs({
args,
allowPositionals: true,
@@ -144,10 +149,19 @@ async function loginCommand(cmd: "login" | "logout", args: string[]) {
// `login` again with no address refreshes the one instance there is.
const again = address ? Object.values(known).find((i) => sameBase(i.base_url, address)) : Object.keys(known).length === 1 ? Object.values(known)[0] : undefined
if (again && !values.ca && isWebuiEntry(again.connection)) {
const r = await sync(again.connection, { setDefault: values.default })
if (json) emit(doneEvent(r, false))
else console.log(loginSummary(r, false).join("\n"))
return
try {
const r = await sync(again.connection, { setDefault: values.default })
if (json) emit(doneEvent(r, false))
else console.log(loginSummary(r, false).join("\n"))
return
} catch (e) {
// The token here was revoked or is unknown to the instance: refreshing it can never work,
// and "run login again" would send the person straight back here. Sign in afresh instead;
// the new login replaces the old one.
if (!(e instanceof SignInRejected)) throw e
if (!json) console.error("The instance no longer accepts the sign-in kept here: signing in again.")
address = again.base_url
}
}
// An older kind of login (the models copied into connections.yaml) is replaced by signing in
// again, at the address it had.
@@ -240,7 +254,7 @@ async function main() {
cwd: process.cwd(),
model: values.model,
mode: asMode(values.mode),
effort: values.effort as Effort | "off" | undefined,
effort: values.effort,
resume: values.session ?? (values.continue ? "last" : undefined),
})
if (done.reload) await (await import("./reload.ts")).restart(done.reload)
@@ -277,7 +291,20 @@ async function main() {
if (sub === "status") return void console.log(service.status().join("\n"))
if (sub === "logs") process.exit(service.logs(argv.includes("-f") || argv.includes("--follow")))
if (sub === "run") process.exit(await service.run(argv[2]))
fail("usage: lembas service install | uninstall | status | logs [-f] | run [connection]", 2)
// Accept scheduled work (spec 3.5.0): the same switch as `lembas remote scheduled`.
if (sub === "scheduled") {
const { remoteCommand } = await import("./remote.ts")
const v = argv[2]
if (v === undefined || v === "--json") {
const { remoteState } = await import("./config/remote.ts")
const s = remoteState()
if (v === "--json") console.log(JSON.stringify({ scheduled: s.scheduled, enabled: s.enabled }))
else console.log(`accept scheduled work: ${s.scheduled ? "on" : "off"}${s.scheduled && !s.enabled ? " (but remote work is off, so nothing runs: lembas remote enable)" : ""}`)
process.exit(0)
}
process.exit(remoteCommand(["scheduled", ...argv.slice(2)]))
}
fail("usage: lembas service install | uninstall | status | logs [-f] | run [connection] | scheduled [on|off]", 2)
}
if (cmd === "run") {
@@ -299,14 +326,13 @@ async function main() {
if (!prompt && !process.stdin.isTTY) prompt = (await new Response(Bun.stdin.stream()).text()).trim()
if (!prompt) fail('nothing to do: lembas run "your prompt"', 2)
if (values.mode && !asMode(values.mode)) fail(`--mode must be one of ${MODES.join(", ")}`, 2)
if (values.effort && values.effort !== "off" && !(EFFORTS as readonly string[]).includes(values.effort))
fail(`--effort must be one of ${EFFORTS.join(", ")}, off`, 2)
if (values.effort && !isLevel(values.effort)) fail(`--effort must be one of ${EFFORTS.join(", ")}, off, default`, 2)
const app = createApp({
cwd: process.cwd(),
model: values.model,
mode: asMode(values.mode),
effort: values.effort as Effort | "off" | undefined,
effort: values.effort,
asker: terminalAsker({ yes: values.yes ?? false, unattended: loadConfig().config.question?.unattended, theme: loadConfig().config.theme }),
unattended: !values.yes && !process.stdin.isTTY,
store: values["no-store"] ? false : undefined,
@@ -319,6 +345,42 @@ async function main() {
// One prompt, so the MCP servers' tools must be there before it (each server has its own
// connect timeout; a failure is a notice, not a stop).
await app.mcpReady
// A command that only says something (/mcp, /agents, /team — what the TUI shows as a menu):
// its text, and no model is asked.
// /reports reads the server, so it is answered here rather than among the commands that only
// read this process: the list, or one report by its id or title, as text.
const reportsArg = /^\/reports(?:\s+(\S[\s\S]*))?$/.exec(prompt.trim())
if (reportsArg) {
const R = await import("./lembas/reports.ts")
let text: string
let failed = false
try {
const all = await R.listReports()
const found = reportsArg[1] ? R.findReport(all, reportsArg[1]) : undefined
if (typeof found === "string") (text = found), (failed = true)
else text = found ? R.reportText(await R.getReport(found.id)) : R.listLines(all).join("\n")
} catch (e) {
text = `/reports: ${(e as Error).message}`
failed = true
}
if (values.json) {
app.bus.emit({ type: "notice", level: failed ? "error" : "info", message: text })
app.bus.emit({ type: "done", reason: failed ? "error" : "stop" })
} else (failed ? console.error : console.log)(text)
app.discardIfEmpty()
process.exit(failed ? 1 : 0)
}
const said = expandSlash(app, prompt, { plain: true })
if (said?.kind === "message") {
// With --json the text is an event of the stream like any other, then the end; plainly, it
// is the output. A command that could not do what was asked exits 1.
if (values.json) {
app.bus.emit({ type: "notice", level: said.error ? "error" : "info", message: said.text })
app.bus.emit({ type: "done", reason: said.error ? "error" : "stop" })
} else (said.error ? console.error : console.log)(said.text)
app.discardIfEmpty()
process.exit(said.error ? 1 : 0)
}
const atts = attachmentsFor(prompt, app.engine.o.toolCtx, app.engine.model.spec.vision === true)
// Through the turns, like every front end: a job's note wakes the session the same way.
const reason = await app.turns.prompt(prompt, atts.flatMap((a) => (a.image ? [a.text, a.image] : [a.text])))
@@ -342,7 +404,8 @@ async function main() {
spec.max_output ? `out ${spec.max_output}` : "",
spec.vision ? "vision" : "",
spec.tools === false ? "no-tools" : "",
spec.effort || spec.efforts ? `effort ${spec.effort ?? "off"} of ${effortsFor(m).join("/")}` : "",
((l) => (l.control === "none" ? "" : `effort ${l.start} of ${l.levels.join("/")}`))(levelsFor(m)),
spec.parallel ? `parallel ${spec.parallel}` : spec.single_session ? "parallel 1" : "",
].filter(Boolean)
console.log(` ${m.ref}${bits.length ? " — " + bits.join(", ") : ""}`)
}
+13 -1
View File
@@ -129,6 +129,12 @@ function legacyKeys(all: Record<string, unknown>, file: string, notes: string[])
all.compaction = rest
notes.push(`${file}: compaction.prune was removed — old tool outputs are no longer cut afterwards; delete it`)
}
// prototypes: true offered the 1.x prototype fences to a terminal's model. Harness spec 3.8.0 has
// HTML pages in their place, which only the server offers (pages.md §4): the key is gone.
if ("prototypes" in all) {
delete all.prototypes
notes.push(`${file}: prototypes was removed — a terminal's model is not offered HTML pages (the web UI and Desktop show them); delete it`)
}
// One file written as a plain string, not a list: read as the list of that one, not dropped
// without a word by the schema.
if (typeof all.instruction_files === "string") {
@@ -154,6 +160,12 @@ function readConfig(file: string, label: string, notes: string[], dropped?: stri
delete all[k]
dropped.push(k)
}
// The team's cap is the global configuration's: a project never raises it (harness team.md §2).
if (dropped && all.agents && typeof all.agents === "object" && !Array.isArray(all.agents) && "cap" in all.agents) {
const { cap: _cap, ...agents } = all.agents as Record<string, unknown>
all.agents = agents
dropped.push("agents.cap")
}
// mcp, voice and search are filled in later, one server / half / service at a time: a key that
// cannot be read turns off that one thing instead of the whole file.
// update: filled in when an update is looked for — a token file missing must not stop a start.
@@ -192,7 +204,7 @@ function merge<T extends Record<string, unknown>>(a: T, b: Partial<T>): T {
// instructions and a custom personality's text are the person's own words, put last in the system
// prompt as theirs: a repository writing them would speak in the user's voice.
// A personality preset's name is only a choice among the shipped texts, and stays a project's to make.
const GLOBAL_ONLY = ["hardline_extra", "hardline_disable", "voice", "update", "settings_tool", "embedding", "remote", "library", "prototypes", "instructions", "personality_custom"] as const
const GLOBAL_ONLY = ["hardline_extra", "hardline_disable", "voice", "update", "settings_tool", "embedding", "remote", "library", "instructions", "personality_custom"] as const
export function loadConfig(opts: { projectConfigDir?: string; trusted?: boolean } = {}): Loaded {
const warnings: string[] = []
+3
View File
@@ -62,6 +62,8 @@ export interface RemoteState {
roots: string[]
max_mode: Mode
terminal: boolean
/** Accept scheduled work (spec 3.5.0). */
scheduled: boolean
}
export function remoteState(b: RemoteBlock = remoteBlock()): RemoteState {
@@ -70,6 +72,7 @@ export function remoteState(b: RemoteBlock = remoteBlock()): RemoteState {
roots: (b.roots ?? []).map((r) => resolve(expandHome(r))),
max_mode: b.max_mode ?? "edit",
terminal: b.terminal === true,
scheduled: b.scheduled === true,
}
}
+20 -5
View File
@@ -51,15 +51,18 @@ export const ModelSpec = z.strictObject({
max_output: z.number().int().positive().optional().describe("Max tokens per reply."),
temperature: z.number().min(0).max(2).optional().describe("Sampling temperature; absent = the server's default."),
top_p: z.number().min(0).max(1).optional().describe("Nucleus sampling; absent = the server's default."),
efforts: z.array(z.enum(EFFORTS)).optional().describe("The model's own effort vocabulary, in offering order."),
effort: z.union([z.enum(EFFORTS), z.literal("off")]).optional().describe("Default effort; `off` sends none."),
efforts: z.array(z.enum(EFFORTS)).optional().describe("The model's own effort vocabulary, in offering order. [] — it takes none (its one level is `default`)."),
thinking_switch: z.boolean().optional().describe("The server turns thinking off for a request with chat_template_kwargs.enable_thinking false: only then is the level `off` offered."),
effort: z.union([z.enum(EFFORTS), z.literal("off"), z.literal("default")]).optional().describe("The level a conversation starts with, when the model offers it: an effort, `off` (thinking switched off, with thinking_switch) or `default` (nothing sent, for a model that takes no efforts)."),
effort_style: z.enum(["top", "kwargs", "both"]).optional().describe("Where the effort goes in a request: top-level, in chat_template_kwargs, or both (the default: llama.cpp drops top-level)."),
vision: z.boolean().optional().describe("The model reads images: @image files, pasted paths and view_image."),
html_pages: z.boolean().optional().describe("The server's word that this model can write HTML pages (harness pages.md). Read and kept, never used here: a terminal's model is not offered pages."),
tools: z.boolean().optional().describe("false: a model without tool calls — it can only talk."),
headers: z.record(z.string(), z.string()).optional().describe("Extra HTTP headers for this model's requests."),
body: z.record(z.string(), z.unknown()).optional().describe("Merged into every request body for this model."),
notes: z.string().max(300).optional().describe("What this model is good at, in a line: the model in use is told which others there are, for handing work over (task) or switching."),
single_session: z.boolean().optional().describe("The server serves one request at a time: a subagent on this same model would take its only slot and push the session's cached prompt out, so it is refused."),
single_session: z.boolean().optional().describe("The server serves one request at a time: a subagent on this same model would take its only slot and push the session's cached prompt out, so it is refused (name a model on another server instead). The same as parallel: 1."),
parallel: z.number().int().positive().optional().describe("How many requests the model's server serves at once (capacity.parallel); wins over single_session. Absent with no single_session: no limit (a hosted API). The session's model is its own subagents' model only when it serves at least 2."),
group: z.string().optional().describe("Models sharing one GPU server that holds one model at a time (llama-swap), as the LLeMbas server says (capacity.group): a subagent on another model of the same group would unload this one, so it is refused."),
})
export type ModelSpec = z.infer<typeof ModelSpec>
@@ -239,6 +242,9 @@ export const Config = z.strictObject({
skin: z.string().optional().describe("The old name of `theme`; still read when `theme` is not set."),
busy_input: z.enum(["steer", "queue"]).optional().describe("A message sent while the agent works: steer (default) — it goes in at the next step, after the running tools finish, and the agent carries on with it; queue — it is sent as the next prompt once the task is done."),
mouse: z.boolean().optional().describe("false: leave the mouse to the terminal — its own selection and Ctrl+Shift+C work without Shift, and the wheel no longer scrolls the transcript (pgup/pgdn do). Default true."),
notify: z.boolean().optional().describe("When a reply finishes, or the agent waits for you, while the terminal is not focused: ring the bell and ask the terminal for a desktop notification (OSC 9) naming the session — never what the reply says. Default true; false: neither."),
paste: z.enum(["placeholder", "full"]).optional().describe("A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path."),
kitty_clipboard: z.boolean().optional().describe("true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in."),
icons: z.enum(["emoji", "plain"]).optional().describe("emoji (default), or plain: one-column symbols for a terminal font that has no emoji."),
personality: z
.enum(PERSONALITIES)
@@ -293,10 +299,18 @@ export const Config = z.strictObject({
mcp: z.record(z.string(), McpServer).optional().describe("MCP servers by name. `{env:}`/`{file:}` are filled in per server (a missing one disables that server only). A project's servers count only once the project is trusted."),
knowledge: z.array(z.string()).optional().describe("The knowledge bases searched (lembas kb); absent: all of them. A project's own config narrows it to what that project needs."),
embedding: z.string().optional().describe("Global config only. An embedding model the LLeMbas server serves, by its id there: knowledge bases are then searched by meaning as well as by words. lembas kb reindex after changing it."),
effort: z.union([z.enum(EFFORTS), z.literal("off")]).optional().describe("The effort a session starts with, when the model takes it; otherwise the model's own default."),
effort: z.union([z.enum(EFFORTS), z.literal("off"), z.literal("default")]).optional().describe("The effort level a session starts with, when the model offers it: an effort, off (thinking switched off, on a model with the switch) or default; otherwise the model's own start level."),
agents: z
.strictObject({
min: z.number().int().min(1).optional().describe("Subagents, Min: the agents at work at least, this agent included (default 1 — 1 is this agent alone). 2 or more: it works through subagents from the start."),
max: z.number().int().min(1).optional().describe("Subagents, Max: the agents at work at most, this agent included (default 4 — this agent and up to 3 subagents). 1: this agent alone, no subagents."),
cap: z.number().int().min(1).optional().describe("Global config only. The highest max a session may set (default 32)."),
})
.optional()
.describe("Subagents (harness team.md, subagents.md): how many agents a session may have at work, counting the session's own agent — Subagents: Min 1, Max 4 by default; 1 is this agent alone. Offered where subagents are on and a model could serve one: the session's, when it serves two requests at once, or another model off its one-model server. /team size and /effort (one range, Min and Max) change it for the session."),
subagents: z.boolean().optional().describe("false: no subagents — no task tool and no team."),
settings_tool: z.enum(["ask", "allow", "off"]).optional().describe("Global config only. The agent's settings tool: ask (default) — each change is approved like any tool call; allow — changes go through without asking (a less strict mode still asks); off — no settings tool."),
update: Update.optional().describe("Global config only. Updating LLeMbas CLI itself."),
prototypes: z.boolean().optional().describe("Global config only. Offer the model prototypes: a complete HTML page in a `prototype-chat` or `prototype-page` fence, saved as a file under the state directory (prototypes/<session>/) and listed by /prototype; the LLeMbas web UI renders the same fences live. Default false."),
library: z.enum(["local", "lembas"]).optional().describe("Global config only. Where memory lives. lembas (the default when the login may reach it): the account's memory records on the LLeMbas server, through its /mcp — the same records its chats have. local: this machine's memory files. Notes, knowledge bases and skills are this machine's either way."),
remote: z
.strictObject({
@@ -306,6 +320,7 @@ export const Config = z.strictObject({
approval_timeout: z.number().int().positive().optional().describe("Seconds an approval waits for an answer from the web before it counts as a denial (default 600)."),
require_trust: z.boolean().optional().describe("Only projects trusted on this machine (default true)."),
terminal: z.boolean().optional().describe("Let the web UI open a terminal here (LLeMbas's terminal panel on a chat on this device): a login shell as this user, in a directory remote sessions may use. Default false."),
scheduled: z.boolean().optional().describe("Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas instance run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off."),
terminal_integration: z.boolean().optional().describe("Shell integration in those terminals (bash, zsh, fish): after your own startup files, the shell marks each prompt, command and exit status (OSC 133) and its directory (OSC 7), so the web UI shows the directory, a mark beside each finished command, and can jump between commands. false: the shell starts as it is. Default true."),
})
.optional()
+15 -3
View File
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from "node:fs"
import { join } from "node:path"
import { parse, parseDocument } from "yaml"
import { z } from "zod"
import LOOP_JSON from "../../harness/loop.json"
import { paths } from "./paths.ts"
import { asMode, Config, EFFORTS, MODES, PERSONALITIES, UPDATE_CHANNELS } from "./schema.ts"
@@ -19,7 +20,7 @@ export type Source = "default" | "global" | "project" | "session"
export interface SettingDef {
key: string
/** model: a model the server serves, by its id; effort: one the model takes, or off; list: comma-separated. */
/** model: a model the server serves, by its id; effort: one of the model's levels; list: comma-separated. */
kind: "enum" | "model" | "effort" | "number" | "boolean" | "list" | "string"
values?: readonly string[]
/** The agent may change it (through the settings tool, with approval). */
@@ -29,14 +30,22 @@ export interface SettingDef {
reload?: boolean
/** What it is when nothing sets it. */
fallback?: string
/** What a person reads beside the key in /settings. */
hint?: string
}
// The Subagents setting's names and what its numbers count (harness loop.json subagents.setting).
const SUB = LOOP_JSON.subagents.setting
const ALL: Scope[] = ["session", "global", "project"]
const USER: Scope[] = ["session", "global"]
export const SETTINGS: SettingDef[] = [
{ key: "model", kind: "model", agent: true, scopes: ALL },
{ key: "effort", kind: "effort", agent: true, scopes: ALL, fallback: "the model's default" },
{ key: "effort", kind: "effort", agent: true, scopes: ALL, fallback: "the model's start level" },
// The team's size is the person's: the agent never sets how many agents it may have.
{ key: "agents.min", kind: "number", agent: false, scopes: ALL, fallback: "1", hint: `${SUB.label}: ${SUB.min} — ${SUB.short}` },
{ key: "agents.max", kind: "number", agent: false, scopes: ALL, fallback: "4", hint: `${SUB.label}: ${SUB.max} — this agent included; 4 is this agent and up to 3 subagents` },
{ key: "mode", kind: "enum", values: MODES, agent: true, scopes: ALL, fallback: "manual" },
{ key: "small_model", kind: "model", agent: true, scopes: ALL, fallback: "the session's model" },
{ key: "knowledge", kind: "list", agent: true, scopes: ALL, fallback: "every base" },
@@ -50,7 +59,10 @@ export const SETTINGS: SettingDef[] = [
{ key: "theme", kind: "string", agent: true, scopes: USER, fallback: "moria" },
{ key: "theme_background", kind: "enum", values: ["theme", "terminal"], agent: true, scopes: USER, fallback: "theme" },
{ key: "busy_input", kind: "enum", values: ["steer", "queue"], agent: true, scopes: USER, fallback: "steer" },
{ key: "paste", kind: "enum", values: ["placeholder", "full"], agent: true, scopes: USER, fallback: "placeholder", hint: "a long paste or a pasted image in the prompt box: a placeholder, or shown in full" },
{ key: "kitty_clipboard", kind: "boolean", agent: false, scopes: USER, fallback: "false", hint: "over SSH in kitty, ctrl+v asks the terminal for the image on its clipboard" },
{ key: "icons", kind: "enum", values: ["emoji", "plain"], agent: true, scopes: USER, fallback: "emoji" },
{ key: "notify", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "bell and desktop notification when a reply finishes or the agent waits for you while the terminal is not focused" },
{ key: "mouse", kind: "boolean", agent: true, scopes: ["global"], reload: true, fallback: "true" },
{ key: "compaction.auto_at", kind: "number", agent: true, scopes: ALL, fallback: "0.85" },
{ key: "search.order", kind: "list", values: ["searxng", "firecrawl", "ddg"], agent: true, scopes: ALL, fallback: "those configured, then ddg" },
@@ -104,7 +116,7 @@ export function parseValue(def: SettingDef, raw: unknown): unknown {
if (def.key === "mode") v = asMode(v) ?? v
// "none" is how a dialog or a person says it; the file keeps the web UI's empty string.
if (def.key === "personality" && typeof v === "string" && ["none", "off", "default"].includes(v.toLowerCase())) v = ""
if (def.kind === "effort" && v !== "off" && !(EFFORTS as readonly string[]).includes(String(v))) throw new SettingError(`effort: one of ${EFFORTS.join(", ")} or off`)
if (def.kind === "effort" && !["off", "default", ...EFFORTS].includes(String(v))) throw new SettingError(`effort: one of ${EFFORTS.join(", ")}, off or default`)
const schema = schemaAt(def.key.split("."))
const r = schema?.safeParse(v)
if (!r || !r.success) throw new SettingError(`${def.key}: ${def.values ? `one of ${def.values.join(", ")}` : (r?.error.issues.map((i) => i.message).join("; ") ?? "not settable")}`)
+3 -1
View File
@@ -1,7 +1,9 @@
/** Time as the eye reads it: 8.4s, 1m 05s, 2h 03m. `whole`: no tenths under a minute (8s) — for a
* clock that ticks while you watch. */
export function duration(ms: number, whole = false): string {
const s = Math.max(0, ms) / 1000
let s = Math.max(0, ms) / 1000
// 59.96 s is a minute, not "60.0s": tenths are only written where they stay under one.
if (!whole && s >= 59.95 && s < 60) s = 60
if (s < 60) return whole ? `${Math.floor(s)}s` : `${s.toFixed(1)}s`
const m = Math.floor(s / 60)
if (m < 60) return `${m}m ${String(Math.floor(s % 60)).padStart(2, "0")}s`
+163 -5
View File
@@ -28,6 +28,7 @@ import t_mv from "../harness/tools/mv.json"
import t_note_manage from "../harness/tools/note_manage.json"
import t_note_view from "../harness/tools/note_view.json"
import t_notes_search from "../harness/tools/notes_search.json"
import t_phone_action from "../harness/tools/phone_action.json"
import t_plan_submit from "../harness/tools/plan_submit.json"
import t_plan_update from "../harness/tools/plan_update.json"
import t_plan_write from "../harness/tools/plan_write.json"
@@ -37,6 +38,7 @@ import t_read from "../harness/tools/read.json"
import t_recall from "../harness/tools/recall.json"
import t_release from "../harness/tools/release.json"
import t_report from "../harness/tools/report.json"
import t_report_write from "../harness/tools/report_write.json"
import t_rm from "../harness/tools/rm.json"
import t_search from "../harness/tools/search.json"
import t_session_search from "../harness/tools/session_search.json"
@@ -48,6 +50,17 @@ import t_skills_list from "../harness/tools/skills_list.json"
import t_tag from "../harness/tools/tag.json"
import t_task from "../harness/tools/task.json"
import t_tasks from "../harness/tools/tasks.json"
import t_team_add from "../harness/tools/team_add.json"
import t_team_read from "../harness/tools/team_read.json"
import t_team_send from "../harness/tools/team_send.json"
import t_team_stop from "../harness/tools/team_stop.json"
import t_team_assign from "../harness/tools/team_assign.json"
import t_team_decide from "../harness/tools/team_decide.json"
import t_team_findings from "../harness/tools/team_findings.json"
import t_team_finish from "../harness/tools/team_finish.json"
import t_team_replace from "../harness/tools/team_replace.json"
import t_team_request from "../harness/tools/team_request.json"
import t_team_whoami from "../harness/tools/team_whoami.json"
import t_view_image from "../harness/tools/view_image.json"
import t_web_fetch from "../harness/tools/web_fetch.json"
import t_web_search from "../harness/tools/web_search.json"
@@ -72,14 +85,22 @@ export interface ToolSpecDef {
purpose: string | false
/** Names each project used before spec v1; a call under one is read as this tool. */
aliases: { cli: string[]; llembas: string[] }
/** `subagent`: offered only to a subagent (report), never to a session's own model. */
offered?: "subagent"
/** `subagent`: offered only to a subagent (report, team_finish, team_request), never to a
* session's own model; `main` (spec 3.4.0): only to the main agent, never to a subagent. */
offered?: "subagent" | "main"
argument_aliases?: Record<string, string>
/** Spec 3.0.0: what must hold for it to be offered — `display` (the session is shown where a file
* can be opened: over the link, to a client that offers `show`), `page`, `forge` (the chat's). */
requires?: ("display" | "page" | "forge")[]
* can be opened: over the link, to a client that offers `show`), `page`, `forge` (the chat's);
* `plan` (3.1.0): plan mode. From 3.1.0 one that can come and go during a session does not
* leave the tool out: it is offered and answers `unavailable` while unmet (context.md §10).
* `team` (3.2.0): the team setting allows more than one agent (harness/team.md §2). `phone`
* (3.6.0): a message came from the LLeMbas app on the person's phone (harness/phone.md) — the
* server's alone. */
requires?: ("display" | "page" | "forge" | "plan" | "team" | "phone" | "scheduled")[]
/** What a call answers, word for word, when a requirement went away after the offer. */
unavailable?: string
/** Spec 3.7.0: a tool's other fixed answers, by key (python: no_answer, timeout). */
texts?: Record<string, string>
/** `always`: put to the person in every mode, auto included; never remembered. */
confirm?: "always"
/** `{{name}}` in the description: a fact the projects differ in, filled in by each (fillDescription). */
@@ -111,6 +132,122 @@ export const LOOP: {
running_max: { default: number }
subagent_steps: { default: number }
}
/** Subagents (spec 3.3.0, harness/subagents.md): the model refusals, what names a model, and how
* the size setting is shown. */
subagents: {
texts: { not_named: string; same_group: string; one_request: string }
named: { before: string; after: string }
setting: { label: string; min: string; max: string; hint: string; short: string; own: string }
}
/** Teams (spec 3.2.0, harness/team.md): the size setting, names, marks, texts. */
team: {
agents: { min: number; max: number; cap: number }
names: { pattern: string; lead: string; reserved: string[]; parent: string; id_prefix: string }
marks: { message: string; report: string; assignment: string; request: string; decision: string; context_full: string }
unavailable: { one_agent: string; one_request: string }
work: { write: string[]; execute: string[]; kept: string[] }
read_max: number
texts: Record<
| "added" | "added_waiting" | "added_under" | "added_waiting_under" | "sent" | "stopped" | "manager" | "full" | "bad_name" | "all_name" | "taken" | "no_goal" | "unknown" | "self" | "nobody" | "not_yours" | "nobody_to_stop" | "no_report" | "ended"
// Spec 3.4.0 (subagents.md §5–§13).
| "only_main" | "not_manager" | "wider" | "request_not_narrower" | "request_kind" | "requestable" | "not_delegated" | "not_requestable" | "requested" | "no_request" | "decided" | "allowed" | "refused" | "decision_allowed" | "decision_refused" | "no_parent" | "finished" | "has_ended" | "cycle" | "assigned" | "replaced" | "replace_brief" | "no_findings" | "noted" | "not_yours_findings" | "context_full" | "gone" | "request_body",
string
>
read: {
tree: string
agent: string
lead_role: string
states: Record<"working" | "waiting" | "finished" | "idle" | "paused" | "done" | "out_of_context" | "stopped", string>
active: string
room: string
message: string
report: string
none: string
more: string
slots: string
ended: string
ended_agent: string
context: string
request: string
}
/** Spec 3.4.0. */
main_only: { tools: string[] }
context: { pause_at: number; final_steps: number }
request: { kinds: string[]; id_prefix: string }
whoami: { lines: Record<"who" | "parent" | "task" | "mode" | "request" | "model" | "limits" | "spawn_yes" | "spawn_no" | "context", string> }
findings: { header: string; item: string }
}
/** Scheduled work on a linked computer (spec 3.5.0, acp.md): the setting, the modes, the
* approval wait, the sentinel, the watch command's limits, the refusals. */
scheduled: {
setting: { key: string; label: string; hint: string }
modes: string[]
default_mode: string
approval_wait_seconds: { default: number; min: number; max: number }
sentinel: string
statuses: string[]
monitor: { timeout_seconds: { default: number; min: number; max: number }; excerpt_chars: number; output_max_bytes: number }
texts: Record<"off" | "plan" | "denied" | "monitor_asks" | "monitor_denied" | "no_reply", string>
/** Spec 3.8.0 (reports.md): a schedule's notify-when — its values, the instruction texts,
* what report_write answers, the limits of the history line and of a made-up summary. */
notify: {
values: string[]
default: string
one_shot_default: string
default_condition: string
labels: Record<"always" | "when" | "never", string>
texts: Record<"always" | "when", string>
result: Record<"filed" | "replaced", string>
note_max: number
summary_max: number
}
}
/** HTML pages in answers (spec 3.8.0, harness/pages.md). */
pages: {
fence: string
title_max: number
untitled: string
variables: string[]
note: string
where: string
projection: string
never: string[]
/** pages.md §6: what a static page may hold. */
static: { elements: string[]; attributes: string[]; attribute_prefixes: string[]; address_attributes: string[]; addresses: string[]; image_types: string[] }
}
/** Display (spec 3.7.0, harness/display.md): a tool call's title, states and facts, the blocks,
* the phases that end a reply, what each card offers. */
display: {
title: { questions_join: string; patch_files: string[]; patch_join: string; keys: string[] }
states: string[]
no_duration: string[]
duration: { tenths_under_seconds: number }
change: string
exit: string
hits: string
hit: string
blocks: string[]
not_drawn: string[]
end: string[]
actions: {
approval: Record<"once" | "always" | "deny" | "deny_reason", string>
question: Record<"something_else", string>
plan: Record<"approve_edit" | "approve_manual" | "revise", string>
}
plain: { group: string; decimal: string }
}
/** Progress (spec 3.4.0, harness/progress.md): the phases, their texts, the line. */
progress: {
phases: string[]
texts: Record<string, string>
reason: Record<string, string>
what: Record<string, string>
stopped_reason: Record<string, string>
line: string
no_elapsed: string[]
what_max: number
pace_per_second: number
}
/** Context hygiene (spec 3.0.0, harness/context.md): the result ids, the texts of a read's
* header, a stub, the elided line, recall; the output cap; what is deduplicated; the table
* compaction adds. */
@@ -131,6 +268,27 @@ export const LOOP: {
dedupe: { by_hash: string[]; by_result: string[] }
compaction: { heading: string; line: string; rows: number }
reasoning: string
/** The environment block's lines about where an agent session works (spec 3.2.0, §11). */
env: { project: string; started: string }
/** A note on the next user message (spec 3.1.0, context.md §10): its tags and its lines, in
* the order they are said. */
note: { open: string; close: string; date: string; mode: string; plan: string; memory: string; instructions: string; personality: string; pages_on: string; pages_off: string; mcp: string; empty: string
/** What a note names the person's own instructions by (the instructions block's `{{path}}`). */
personal: string
/** For a chat, whose modes have no text of their own; the CLI says modes/<mode>.md. */
plan_ended: string
/** For a chat, which does not resend earlier tool results; the CLI's model has them. */
plan_own: string
/** Spec 3.2.0 (team.md §10): the size setting, said to the lead. */
team: string
team_lead: string
team_one: string
team_stopped: string
/** Spec 3.3.0 (subagents.md §4): the session's model cannot serve subagents itself. */
team_own: string
}
/** How long a session waits for its configured MCP servers before its first request. */
mcp_wait_ms: number
}
} = LOOP_JSON
@@ -208,7 +366,7 @@ export function narrowParameters(parameters: Record<string, unknown>, narrow: Na
}
export const TOOL_SPECS: Record<string, ToolSpecDef> = Object.fromEntries(
([t_apply_patch, t_ask_user, t_bash, t_branch, t_commit, t_decisions, t_edit, t_glob, t_grep, t_job_list, t_job_output, t_job_send, t_job_stop, t_knowledge_get, t_knowledge_search, t_list, t_memory, t_merge, t_mkdir, t_multiedit, t_mv, t_note_manage, t_note_view, t_notes_search, t_plan_submit, t_plan_update, t_plan_write, t_pr, t_python, t_read, t_recall, t_release, t_report, t_rm, t_search, t_session_search, t_settings, t_show, t_skill_manage, t_skill_view, t_skills_list, t_tag, t_task, t_tasks, t_view_image, t_web_fetch, t_web_search, t_write] as ToolSpecDef[]).map((t) => [t.name, t]),
([t_apply_patch, t_ask_user, t_bash, t_branch, t_commit, t_decisions, t_edit, t_glob, t_grep, t_job_list, t_job_output, t_job_send, t_job_stop, t_knowledge_get, t_knowledge_search, t_list, t_memory, t_merge, t_mkdir, t_multiedit, t_mv, t_note_manage, t_note_view, t_notes_search, t_phone_action, t_plan_submit, t_plan_update, t_plan_write, t_pr, t_python, t_read, t_recall, t_release, t_report, t_report_write, t_rm, t_search, t_session_search, t_settings, t_show, t_skill_manage, t_skill_view, t_skills_list, t_tag, t_task, t_tasks, t_team_add, t_team_assign, t_team_decide, t_team_findings, t_team_finish, t_team_read, t_team_replace, t_team_request, t_team_send, t_team_stop, t_team_whoami, t_view_image, t_web_fetch, t_web_search, t_write] as ToolSpecDef[]).map((t) => [t.name, t]),
)
/** Whether the spec gives a tool to this CLI: not the server's alone (`scope: llembas`), and
+34 -8
View File
@@ -7,6 +7,10 @@ import type { PlanReply, PlanRequest } from "./tool/plan_submit.ts"
import type { IconSet } from "./tui/icons.ts"
import { loadTheme, type Theme } from "./tui/palette.ts"
import { duration } from "./duration.ts"
import { blockOf, callTitle, resultFacts } from "./session/display.ts"
import { endLine, endOf, type Progress } from "./session/progress.ts"
import { num } from "./tui/locale.ts"
import { NOTICES } from "./tui/notices.ts"
/** The theme's colours as 24-bit escapes — the same theme the TUI uses (`theme` in config.yaml). */
function escapes(theme: Theme) {
@@ -26,6 +30,8 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
let inReasoning = false
let atLineStart = true
let started = false
const titles = new Map<string, string | undefined>()
let failure: string | undefined
const out = (s: string) => {
if (!s) return
process.stdout.write(s)
@@ -53,11 +59,20 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
inReasoning = true
out(c(C.think, e.text))
break
case "tool_start":
titles.set(e.id, e.title ?? callTitle(e.args))
break
case "tool_end": {
// A call as every client shows it (harness display.md): its one title, what the result
// adds, how long it took.
const verb = e.name.padEnd(6)
const mark = e.result.isError ? c(C.err, "✗") : ""
const title = e.result.title ?? (e.result.isError ? e.result.output.split("\n")[0]!.slice(0, 120) : "")
line(`${c(C.dim, "┊")} ${icon(e.name)} ${c(C.label, verb)} ${title} ${c(C.dim, duration(e.ms))} ${mark}`)
const title = titles.get(e.id)
titles.delete(e.id)
const facts = resultFacts(blockOf(e.name), title, e.result, num)
if (e.result.isError && !facts.length) facts.push(e.result.output.trim().split("\n")[0]!.slice(0, 120))
const after = [...facts, duration(e.ms)].join(" · ")
line(`${c(C.dim, "┊")} ${icon(e.name)} ${c(C.label, verb)} ${title ? `${title} ${c(C.dim, `· ${after}`)}` : c(C.dim, after)} ${mark}`)
break
}
case "sub_tool":
@@ -72,22 +87,33 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
else if (e.state === "end") line(`${c(C.dim, "┊")} ${c(C.label, e.job.id)} ${e.job.state}${e.job.exit !== undefined ? ` (${e.job.exit === null ? "stopped" : `exit ${e.job.exit}`})` : ""} · ${e.job.description}`)
break
case "tool_denied":
line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.reason.split("\n")[0]!.slice(0, 140)}`)
line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.title ? `${e.title} ${c(C.dim, "·")} ` : ""}${e.reason.split("\n")[0]!.slice(0, 140)}`)
break
case "retract":
if (!atLineStart) out("\n")
started = false
break
case "notice":
line(c(C.warn, `⚠ ${e.message}`))
case "notice": {
// The same table as the TUI's transcript (tui/notices.ts): a warning sign means attention.
const kind = NOTICES[e.level ?? "warn"]
line(c({ info: C.dim, success: C.ok, warn: C.warn, error: C.err }[e.level ?? "warn"], `${kind.glyph} ${e.message}`))
break
}
case "error":
line(c(C.err, `✗ ${e.message}`))
// Said once, as the line that ends the reply.
failure = e.message
break
case "done":
case "done": {
if (!atLineStart) out("\n")
if (e.reason === "steps") line(c(C.warn, "⚠ stopped at the step limit"))
// How a reply that did not finish ended: the spec's line (display.md §4).
const end = endOf(e.reason, failure)
const text = end && endLine({ ...end, since: 0 } as Progress, 0, num)
if (text) line(end!.phase === "failed" ? c(C.err, `✗ ${text}`) : c(C.warn, `■ ${text}`))
const more = end?.phase === "failed" ? failure?.trim().split("\n").slice(1).join("\n").trim() : ""
if (more) line(c(C.err, more))
failure = undefined
break
}
}
})
}
+4 -1
View File
@@ -88,6 +88,9 @@ export interface Job {
/** Set when the note's wake should not happen: a synchronous subagent whose result goes back
* as the task call's output. */
silent?: boolean
/** A team member's name (spec 3.2.0): not a job to the model — the job tools do not take it —
* but a subagent job to a client over the link (team.md §4, §11). */
team?: string
}
/** A front end holding a session: where its jobs' events go, and how a note wakes it. The
@@ -463,7 +466,7 @@ export class JobRegistry {
case "tool_end":
case "tool_denied": {
job.tools = (job.tools ?? 0) + 1
const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `denied — ${e.reason.split("\n")[0]!.slice(0, 80)}`
const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `${e.title ? `${e.title} · ` : ""}denied — ${e.reason.split("\n")[0]!.slice(0, 80)}`
const isError = e.type === "tool_denied" || e.result.isError === true
this.append(job, `\n[${e.name}] ${title}${isError && e.type === "tool_end" ? " (error)" : ""}\n`)
if (job.ownerCallId) owner?.bus.emit({ type: "sub_tool", callId: job.ownerCallId, jobId: job.id, name: e.name, title, ...(isError ? { isError } : {}) })
+22 -6
View File
@@ -27,6 +27,8 @@ export function protocolMismatch(base: string, d: Pick<Discovery, "protocol" | "
}
export class LembasError extends Error {}
/** The instance answered 401: the token this machine holds is revoked or unknown there. `login` signs in afresh. */
export class SignInRejected extends LembasError {}
/** The server and this CLI speak no link protocol in common: no login, and no dial gets further. */
export class ProtocolError extends LembasError {}
@@ -58,10 +60,14 @@ export interface ServedModel {
top_p?: number
efforts?: string[]
effort?: string
/** Spec 3.2.0: the server turns thinking off for enable_thinking false. */
thinking_switch?: boolean
vision?: boolean
/** Spec 3.8.0 (harness pages.md): the model can write HTML pages. */
html_pages?: boolean
tools?: boolean
notes?: string
capacity?: { group?: string; single_session?: boolean }
capacity?: { group?: string; single_session?: boolean; parallel?: number }
default?: boolean
/** The provider's slug — the part of `id` before its `/` — and what kind of model it is. */
provider?: string
@@ -103,6 +109,16 @@ async function call(url: string, init: RequestInit, tls: Tls | undefined, timeou
}
}
/** One request to the instance with the device's token, its JSON answer and status (spec 3.5.0:
* the schedule routes of /api/v2). A body that is not JSON is null. */
export async function apiCall(base: string, token: string, tls: Tls | undefined, method: string, path: string, body?: unknown, timeoutMs = 30_000): Promise<{ status: number; json: any }> {
const headers: Record<string, string> = { authorization: `Bearer ${token}`, accept: "application/json" }
if (body !== undefined) headers["content-type"] = "application/json"
const res = await call(`${base}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }, tls, timeoutMs)
const json = res.status === 204 ? null : await res.json().catch(() => null)
return { status: res.status, json }
}
/** What a person typed, as a base address: a scheme added (https unless they said http), the path
* and a trailing slash dropped. */
export function normalise(address: string): string {
@@ -266,7 +282,7 @@ export async function checkToken(d: Discovery, token: string, tls: Tls | undefin
export async function models(d: { api: { openai: string } }, token: string, tls: Tls | undefined, timeoutMs?: number): Promise<ServedModel[]> {
const res = await call(`${d.api.openai}/models`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs)
if (res.status === 401) throw new LembasError("the instance no longer accepts this sign-in — run login again")
if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again")
if (res.status === 403) throw new LembasError("this account may not use the instance's models through the API (the “Use the API” permission)")
if (!res.ok) throw new LembasError(`listing the models: ${res.status} ${res.statusText}`)
const body = (await res.json()) as { data?: ServedModel[] }
@@ -291,7 +307,7 @@ export interface InstanceInfo {
export async function instanceInfo(base: string, token: string, tls: Tls | undefined, timeoutMs?: number): Promise<InstanceInfo | undefined> {
const res = await call(`${base}/api/v1/instance`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs)
if (res.status === 404) return undefined
if (res.status === 401) throw new LembasError("the instance no longer accepts this sign-in — run login again")
if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again")
if (!res.ok) throw new LembasError(`reading the instance: ${res.status} ${res.statusText}`)
const body = (await res.json().catch(() => undefined)) as InstanceInfo | undefined
return body && typeof body === "object" ? body : undefined
@@ -339,7 +355,7 @@ export interface Usage {
export async function usage(base: string, token: string, tls: Tls | undefined, timeoutMs = 5000): Promise<Usage | undefined> {
const res = await call(`${base}/v1/usage`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs)
if (res.status === 404) return undefined
if (res.status === 401) throw new LembasError("the instance no longer accepts this sign-in — run login again")
if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again")
if (!res.ok) throw new LembasError(`reading the usage: ${res.status} ${res.statusText}`)
const body = (await res.json().catch(() => undefined)) as Usage | undefined
return body && typeof body === "object" ? body : undefined
@@ -367,7 +383,7 @@ function asPersonalization(b: unknown): Personalization | undefined {
export async function personalization(base: string, token: string, tls: Tls | undefined, timeoutMs = 5000): Promise<Personalization | undefined> {
const res = await call(`${base}/v1/me/personalization`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs)
if (res.status === 404) return undefined
if (res.status === 401) throw new LembasError("the instance no longer accepts this sign-in — run login again")
if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again")
if (!res.ok) throw new LembasError(`reading the personalization: ${res.status} ${res.statusText}`)
return asPersonalization(await res.json().catch(() => undefined))
}
@@ -391,7 +407,7 @@ export async function savePersonalization(base: string, token: string, tls: Tls
if (res.status === 422) throw new LembasError(`the instance would not take that personalization${detail ? `: ${detail}` : ""}`)
throw new LembasError(detail ? `the instance did not allow it: ${detail}` : "not allowed: the instance refused to save the personalization")
}
if (res.status === 401) throw new LembasError("the instance no longer accepts this sign-in — run login again")
if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again")
if (!res.ok) throw new LembasError(`saving the personalization: ${res.status} ${res.statusText}`)
return asPersonalization(await res.json().catch(() => undefined))
}
+2 -2
View File
@@ -13,7 +13,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync }
import { join, resolve } from "node:path"
import { parseDocument } from "yaml"
import { expandHome, globalPaths, isLocal, paths } from "../config/paths.ts"
import { awaitToken, checkToken, discover, LembasError, signOut, spoken, startDevice, type DeviceStart, type Discovery, type Granted, type InstanceInfo, type ServedModel, type Tls } from "./client.ts"
import { awaitToken, checkToken, discover, LembasError, SignInRejected, signOut, spoken, startDevice, type DeviceStart, type Discovery, type Granted, type InstanceInfo, type ServedModel, type Tls } from "./client.ts"
import { dropCache, fetchWebui, isChatModel, readCache, specFor } from "./webui.ts"
export interface Instance {
@@ -557,4 +557,4 @@ export async function logout(connection: string): Promise<LogoutResult> {
return { connection, revoked, modelLeft: model && (ours || model.startsWith(`${connection}/`)) ? model : undefined }
}
export { LembasError, readCache, specFor }
export { LembasError, readCache, SignInRejected, specFor }
+85
View File
@@ -0,0 +1,85 @@
// `/reports`: the reports the account's schedules filed (harness reports.md, spec 3.8.0), read
// from the LLeMbas server with this device's token. Reports are the server's — it stores them,
// counts the unread, notifies; this is a window onto them from the terminal.
//
// PROVISIONAL CONTRACT — written before the server's routes existed, to be checked against its
// contract fixtures when they do:
// GET /api/v2/reports?unread=1 → { reports: [Report] }
// GET /api/v2/reports/{id} → Report with `body`, and `chat` (the chat a reply continues in, or null)
// POST /api/v2/reports/{id}/read → marks it read
// DELETE /api/v2/reports/{id}
// POST /api/v2/reports/{id}/reply → { chat: "<id>" } (not used here: see replyPrompt)
import { textProjection } from "../pages/fence.ts"
import { clean } from "../mcp/clean.ts"
import { api, when } from "./schedules.ts"
export interface Report {
id: string
title: string
summary: string
importance: "normal" | "high" | string
schedule?: { id: string; title: string } | null
created: string
unread: boolean
body?: string
chat?: string | null
}
const call = (method: string, path: string, body?: unknown) => api(method, path, body, "reports")
const id = (v: string) => encodeURIComponent(v)
export const listReports = async (o: { unread?: boolean } = {}): Promise<Report[]> => ((await call("GET", `/reports${o.unread ? "?unread=1" : ""}`))?.reports ?? []) as Report[]
export const getReport = async (report: string): Promise<Report> => {
const r = await call("GET", `/reports/${id(report)}`)
return (r?.report ?? r) as Report
}
export const markRead = async (report: string): Promise<void> => void (await call("POST", `/reports/${id(report)}/read`))
export const deleteReport = async (report: string): Promise<void> => void (await call("DELETE", `/reports/${id(report)}`))
/** Unread first, then the newest first. */
export function sorted(all: Report[]): Report[] {
return [...all].sort((a, b) => Number(b.unread) - Number(a.unread) || String(b.created).localeCompare(String(a.created)))
}
/** A report by its id, or by a title that starts with `query` (no case) when only one does. */
export function findReport(all: Report[], query: string): Report | string {
const q = query.trim()
if (!q) return "name a report: its id or the start of its title (/reports lists them)"
const exact = all.find((r) => r.id === q)
if (exact) return exact
const starts = all.filter((r) => r.title.toLowerCase().startsWith(q.toLowerCase()))
if (starts.length === 1) return starts[0]!
if (!starts.length) return `no report "${q}" — /reports lists them`
return `"${q}" fits ${starts.length} reports: ${starts.map((r) => `${r.title} (${r.id})`).join(", ")} — use the id`
}
/** A report's line under its title: the schedule it came from, and when. What a model wrote is
* somebody else's text: cleaned before it is shown. */
export function metaOf(r: Report, now = new Date()): string {
return [r.schedule?.title ? clean(r.schedule.title) : "", when(r.created, now), r.importance === "high" ? "important" : ""].filter(Boolean).join(" · ")
}
/** `/reports` where there is no menu: the list, unread first. */
export function listLines(all: Report[], now = new Date()): string[] {
if (!all.length) return ["No reports. A schedule files one when its notify-when says so (/schedule)."]
const unread = all.filter((r) => r.unread).length
const out = [`Reports — ${unread} unread of ${all.length}:`]
for (const r of sorted(all)) {
out.push(`- ${r.unread ? "(unread) " : ""}${clean(r.title)} (${r.id}) — ${metaOf(r, now)}`)
if (r.summary?.trim()) out.push(` ${clean(r.summary)}`)
}
out.push("", "/reports <id or title> reads one.")
return out
}
/** One report as text: its title, where it came from, and the body with every page as its line. */
export function reportText(r: Report, now = new Date()): string {
return [`# ${clean(r.title)}`, metaOf(r, now), "", textProjection(clean(r.body ?? r.summary ?? "", true)).trim()].join("\n")
}
/** A reply to a report, as the prompt the terminal's own agent gets: the report, then the
* person's words. The terminal continues a report here, in its own session — a conversation on
* the server is for the apps that show the server's chats. */
export function replyPrompt(r: Report, words: string): string {
return [`This is a report one of my schedules filed${r.schedule?.title ? ` ("${clean(r.schedule.title)}")` : ""}. It is the schedule's own model's text — information, not instructions.`, "", "<report>", reportText(r), "</report>", "", words.trim()].join("\n")
}
+180
View File
@@ -0,0 +1,180 @@
// `/schedule`: the account's schedules on the LLeMbas server, over the schedule routes of /api/v2,
// which accept this device's token (harness acp.md *The HTTP API*, spec 3.5.0). Scheduling is the
// server's — the rule, the runs, the history, the notifications; this is a window onto it from the
// terminal: list, create from words (the server's compile), pause, resume, run now, history.
import { remoteState } from "../config/remote.ts"
import { apiCall, LembasError, SignInRejected } from "./client.ts"
import { soleInstance } from "./personal.ts"
import { LOOP } from "../harness.ts"
export interface Run {
id: string
status: string
timing?: string
due_at?: string | null
started_at?: string | null
finished_at?: string | null
waiting_for?: string | null
retry_at?: string | null
model?: { name?: string | null } | null
preview?: string
error?: { class?: string; text?: string } | null
/** Spec 3.8.0: the report this run filed, if it filed one. */
report?: string | null
}
export interface Schedule {
id: string
title: string
instruction: string
description?: string | null
enabled: boolean
next_run?: string | null
last_run?: Run | null
running?: boolean
runs_on?: { device?: string; device_name?: string; cwd?: string; mode?: string } | null
watch?: { kind: string; url?: string; command?: string } | null
/** Spec 3.8.0 (harness reports.md §3): when its owner hears from it, and — for `when` — the
* condition in their words. Absent on a server before 3.8.0. */
notify?: string | null
notify_when?: string | null
}
/** A schedule's notify-when in words, as the list and the form say it. */
export function notifyWords(notify: string | null | undefined, condition?: string | null): string {
const N = LOOP.scheduled.notify
if (notify === "always") return "a report every run"
if (notify === "never") return "no reports"
return `a report when ${(condition ?? "").trim() || N.default_condition}`
}
export interface Compiled {
ok: boolean
reason?: string | null
title: string
instruction: string
target?: string
rule: Record<string, unknown>
description?: string | null
next_runs: string[]
timezone?: string
}
/** One call to the schedule (and report) routes; the server's own refusal (`detail`) as the error. */
export async function api(method: string, path: string, body?: unknown, what = "schedules"): Promise<any> {
const one = soleInstance()
if (!one) throw new LembasError("not logged in to one LLeMbas server (/login)")
const r = await apiCall(one.instance.base_url, one.token, one.instance.ca ? { ca: one.instance.ca } : undefined, method, `/api/v2${path}`, body)
const detail = typeof r.json?.detail === "string" ? r.json.detail : undefined
if (r.status === 401 && !detail) throw new SignInRejected("the server no longer accepts this sign-in — /login again")
// A server from before spec 3.5.0 lets only an app's token reach /api/v2.
if (r.status === 401 || (r.status === 403 && /scope|token/i.test(detail ?? "")))
throw new LembasError(`${one.instance.connection} does not let a linked computer manage ${what} yet (it needs a newer LLeMbas server)`)
if (r.status === 404 && !detail) throw new LembasError(`${one.instance.connection} has no ${what} here (an older LLeMbas server)`)
if (r.status >= 400) throw new LembasError(detail ?? `${method} ${path}: ${r.status}`)
return r.json
}
export const listSchedules = async (): Promise<Schedule[]> => ((await api("GET", "/schedules"))?.schedules ?? []) as Schedule[]
export const compileWords = async (text: string): Promise<Compiled> => (await api("POST", "/schedules/compile", { text })) as Compiled
export const pauseSchedule = async (id: string): Promise<Schedule> => (await api("POST", `/schedules/${encodeURIComponent(id)}/pause`)).schedule
export const resumeSchedule = async (id: string): Promise<Schedule> => (await api("POST", `/schedules/${encodeURIComponent(id)}/resume`)).schedule
export const runSchedule = async (id: string): Promise<Run> => (await api("POST", `/schedules/${encodeURIComponent(id)}/run`)).run
export const scheduleRuns = async (id: string, limit = 10): Promise<{ runs: Run[]; more: boolean }> => {
const r = await api("GET", `/schedules/${encodeURIComponent(id)}/runs?limit=${limit}`)
return { runs: (r?.runs ?? []) as Run[], more: r?.more === true }
}
export const runResult = async (id: string, run: string): Promise<{ run: Run; text: string | null }> => api("GET", `/schedules/${encodeURIComponent(id)}/runs/${encodeURIComponent(run)}`)
/** Create one from what compile said. `here`: it runs on this computer, in `cwd`, in Edit
* (`runs_on.device: "this"` is the calling device). */
export async function createSchedule(c: Compiled, request: string, here?: { cwd: string }, notify?: { notify: string; condition?: string }): Promise<Schedule> {
const body: Record<string, unknown> = { title: c.title, instruction: c.instruction, request, rule: c.rule, ...(c.target ? { target: c.target } : {}) }
// Spec 3.8.0: notify when — the three values, and the person's own words for `when`.
if (notify) Object.assign(body, { notify: notify.notify, ...(notify.notify === "when" && notify.condition?.trim() ? { notify_when: notify.condition.trim() } : {}) })
if (here) body.runs_on = { device: "this", cwd: here.cwd, mode: "edit" }
return (await api("POST", "/schedules", body)).schedule
}
/** A schedule by its id, or by a title that starts with `query` (no case) when only one does. */
export function findSchedule(all: Schedule[], query: string): Schedule | string {
const q = query.trim()
if (!q) return "name a schedule: its id or the start of its title (/schedule lists them)"
const exact = all.find((s) => s.id === q)
if (exact) return exact
const low = q.toLowerCase()
const titled = all.filter((s) => s.title.toLowerCase() === low)
if (titled.length === 1) return titled[0]!
const starts = all.filter((s) => s.title.toLowerCase().startsWith(low))
if (starts.length === 1) return starts[0]!
if (!starts.length) return `no schedule "${q}" — /schedule lists them`
return `"${q}" fits ${starts.length} schedules: ${starts.map((s) => `${s.title} (${s.id})`).join(", ")} — use the id`
}
/** A time as the person reads it: the local date and time, minutes only. */
export function when(iso: string | null | undefined, now = new Date()): string {
if (!iso) return "—"
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
const pad = (n: number) => String(n).padStart(2, "0")
const time = `${pad(d.getHours())}:${pad(d.getMinutes())}`
const sameDay = d.toDateString() === now.toDateString()
return sameDay ? `today ${time}` : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${time}`
}
/** A run's status in a word or two: what history and the list show. */
export function runStatus(r: Run): string {
if (r.status === "waiting") return r.waiting_for === "device" ? "waiting for the computer" : r.waiting_for === "model" ? "waiting for a free model" : "waiting to try again"
if (r.status === "missed") return "missed"
if (r.status === "unchanged") return "unchanged (nothing new)"
if (r.status === "silent") return "nothing to report"
if (r.status === "ok" && r.report) return "ok — a report"
return r.status
}
/** `/schedule` and `/schedule list`. */
export function listLines(all: Schedule[], now = new Date()): string[] {
if (!all.length) return ["no schedules yet — /schedule new <what, and when> (\"every weekday at 8 summarise the open issues\")"]
const out: string[] = []
for (const s of all) {
const state = s.running ? "running" : s.enabled ? `next ${when(s.next_run, now)}` : "paused"
const last = s.last_run ? ` · last ${runStatus(s.last_run)}${s.last_run.finished_at ? ` ${when(s.last_run.finished_at, now)}` : ""}` : ""
const where = s.runs_on ? ` · on ${s.runs_on.device_name || "a computer"}${s.runs_on.cwd ? ` in ${s.runs_on.cwd}` : ""}` : ""
const watch = s.watch ? ` · watches ${s.watch.kind === "url" ? s.watch.url : s.watch.command}` : ""
const reports = s.notify ? ` · ${notifyWords(s.notify, s.notify_when)}` : ""
out.push(`${s.title} (${s.id}) — ${s.description || "no rule"}`)
out.push(` ${state}${last}${where}${watch}${reports}`)
}
out.push("", "/schedule new <words> · pause|resume|run|history <id or title>")
return out
}
/** `/schedule history`: the newest runs first. Previews are model output: shown as plain text. */
export function historyLines(s: Schedule, runs: Run[], more: boolean, now = new Date()): string[] {
const out = [`${s.title} (${s.id}) — ${s.description || "no rule"}`]
if (!runs.length) out.push(" no runs yet")
for (const r of runs) {
const at = when(r.finished_at ?? r.started_at ?? r.due_at, now)
const model = r.model?.name ? ` · ${r.model.name}` : ""
out.push(` ${at} ${runStatus(r)}${r.timing === "late" ? " (late)" : r.timing === "catch_up" ? " (caught up)" : ""}${model} [${r.id}]`)
const said = r.error?.text || (r.preview ?? "").replace(/\s+/g, " ").trim()
if (said) out.push(` ${said.length > 160 ? said.slice(0, 159) + "…" : said}`)
}
if (more) out.push(" … older runs on the server")
return out
}
/** What compile made of the words, before anything is created. */
export function previewLines(c: Compiled, now = new Date()): string[] {
const out = [`${c.title || "(no title)"} — ${c.description || "no rule worked out"}`]
if (c.instruction) out.push(` does: ${c.instruction}`)
if (c.next_runs.length) out.push(` next: ${c.next_runs.map((t) => when(t, now)).join(", ")}${c.timezone ? ` (${c.timezone})` : ""}`)
if (!c.ok && c.reason) out.push(` ${c.reason}`)
return out
}
/** Whether a schedule could run here, in `cwd`: Accept scheduled work is on and remote work may use it. */
export function canRunHere(): boolean {
const s = remoteState()
return s.enabled && s.scheduled && s.roots.length > 0
}
+7 -2
View File
@@ -18,7 +18,7 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { join } from "node:path"
import { parse } from "yaml"
import { connectionFiles, isLocal, paths } from "../config/paths.ts"
import type { Connection, ModelSpec, WebuiConnection } from "../config/schema.ts"
import { EFFORTS, type Connection, type ModelSpec, type WebuiConnection } from "../config/schema.ts"
import { substituteDeep } from "../config/substitute.ts"
import { instanceInfo, LembasError, models as listModels, normalise, personalization, type InstanceInfo, type Personalization, type ServedModel, type Tls } from "./client.ts"
@@ -94,12 +94,17 @@ export function specFor(m: ServedModel, connection: string): ModelSpec {
if (m.max_output) out.max_output = m.max_output
if (typeof m.temperature === "number" && m.temperature >= 0 && m.temperature <= 2) out.temperature = m.temperature
if (typeof m.top_p === "number" && m.top_p >= 0 && m.top_p <= 1) out.top_p = m.top_p
if (m.efforts?.length) out.efforts = m.efforts
// [] is said: the model takes no efforts (its one level is `default`), unlike an absent list.
if (Array.isArray(m.efforts)) out.efforts = m.efforts.filter((e) => (EFFORTS as readonly string[]).includes(e))
if (m.effort) out.effort = m.effort
if (m.thinking_switch === true) out.thinking_switch = true
if (m.vision !== undefined) out.vision = m.vision
// Spec 3.8.0 (pages.md): kept as the server says it; nothing here offers pages.
if (m.html_pages !== undefined) out.html_pages = m.html_pages === true
if (m.tools !== undefined) out.tools = m.tools
if (m.notes) out.notes = m.notes.slice(0, 300)
if (m.capacity?.single_session) out.single_session = true
if (Number.isInteger(m.capacity?.parallel) && m.capacity!.parallel! >= 1) out.parallel = m.capacity!.parallel
if (m.capacity?.group) out.group = `${connection}:${m.capacity.group}`
return out as ModelSpec
}
+65
View File
@@ -0,0 +1,65 @@
// What a server says is somebody else's text. Before any of it is drawn on a terminal or printed —
// a tool's or a prompt's name and description, an error, what a local server wrote to stderr —
// it goes through here: control characters out (an escape sequence in a description must not
// move the cursor, set the title or the clipboard), and, where it leaves this machine or is
// printed into a reply, what looks like a secret out too.
/** Text with every control character gone: escape sequences (CSI, OSC, the rest), the other C0
* and C1 characters, DEL. `lines`: newlines are kept (a description, an error in full); else the
* text becomes one line. A tab is a space. */
export function clean(text: unknown, lines = false): string {
const s = typeof text === "string" ? text : text === undefined || text === null ? "" : String(text)
const out = s
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, "") // OSC … BEL | ST
.replace(/\x1b[P^_X][^\x1b]*(?:\x1b\\)?/g, "") // DCS, PM, APC, SOS … ST
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "") // CSI
.replace(/\x1b[\s\S]?/g, "") // any other escape
.replace(/\u009b[0-?]*[ -/]*[@-~]/g, "") // 8-bit CSI
.replace(/\r\n?/g, "\n")
.replace(/\t/g, " ")
// eslint-disable-next-line no-control-regex
.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "")
return lines ? out : out.replace(/\s*\n\s*/g, " ").trim()
}
/** An address without what may be secret in it: no user or password, no query, no fragment. Not
* an address: the text, cleaned. */
export function redactUrl(url: string): string {
try {
const u = new URL(url)
return `${u.protocol}//${u.host}${u.pathname}${u.search ? "?…" : ""}`
} catch {
return clean(url)
}
}
/** Text with what looks like a secret taken out: credentials and queries in addresses, a value
* after `token`, `key`, `secret`, `password`, `authorization` or `bearer`, and long runs of
* letters and digits that have both (keys, hashes). */
export function redactSecrets(text: string): string {
return text
.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, "$1")
.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s?#"')]+)\?[^\s"')]*/gi, "$1?…")
.replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]")
.replace(/\b((?:api[_-]?)?(?:token|key|secret|password|passwd|authorization|auth|cookie)\b["']?\s*[=:]\s*["']?)[^\s"',;&]+/gi, "$1[redacted]")
.replace(/\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{32,}\b/g, "[redacted]")
}
/** Text with the credentials and queries of the addresses in it taken out — what is shown of an
* error on this machine, where the rest of it is the person's own to read. */
export function redactUrls(text: string): string {
return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, "$1").replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s?#"')]+)\?[^\s"')]*/gi, "$1?…")
}
/** An error as it may leave this machine or be printed into a reply: its first line, cleaned,
* secrets out, not longer than a line should be. */
export function errorLine(error: string | undefined, max = 200): string {
const line = redactSecrets(clean((error ?? "").split("\n")[0]))
return line.length > max ? `${line.slice(0, max - 1)}…` : line
}
/** Text for a markdown reply, so that nothing in it is markup: a server's description cannot put
* a link or an image into the chat. */
export function mdEscape(text: string): string {
return text.replace(/[\\`*_{}[\]()<>#+!|~]/g, "\\$&").replace(/^(\s*)([-+]|\d+[.)])(\s)/gm, "$1\\$2$3")
}
+72 -13
View File
@@ -17,6 +17,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"
import { ToolListChangedNotificationSchema, PromptListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"
import { clean } from "./clean.ts"
import type { McpServer } from "../config/schema.ts"
import { expandHome } from "../config/paths.ts"
import { scanThreats } from "../memory/threats.ts"
@@ -25,6 +26,7 @@ import type { ImagePart } from "../provider/types.ts"
import { ToolError, truncate, type Tool, type ToolResult } from "../tool/tool.ts"
import { match } from "../permission/wildcard.ts"
import { codeFrom, forget, OAuthProvider, waitForCallback, CALLBACK_PORT } from "./oauth.ts"
import { mcpBlock } from "../session/prefix.ts"
export type ServerConfig = McpServer & { source: "global" | "project" }
export type Status = "disabled" | "connecting" | "connected" | "failed" | "needs_auth"
@@ -78,6 +80,12 @@ const sanitize = (s: string) => s.replace(/[^A-Za-z0-9_-]/g, "_")
* `memory` tool keeps its name and stands in for this machine's; notes, knowledge and skills stay
* this machine's (spec 3.0.0). */
export const LIBRARY_SERVER = "lembas-library"
/** A server's prompt as the command it is registered as: `<server>:<prompt>`, both spelled with
* letters, digits, `_` and `-` only. */
export function promptCommand(server: string, prompt: string): string {
return `${sanitize(server)}:${sanitize(prompt)}`
}
/** mcp__<server>__<tool>, at most 64 characters (the providers' limit); longer ones keep a hash. */
export function toolName(server: string, tool: string): string {
const full = `mcp__${sanitize(server)}__${sanitize(tool)}`
@@ -143,11 +151,19 @@ let exitHook = false
export class McpManager {
readonly servers = new Map<string, ServerState>()
/** What each server's tool is called here, as `tools()` last named it. */
private names = new Map<string, string>()
/** The name a server's tool goes by among this program's tools — its permission key too. */
nameOf(server: string, tool: string): string {
return this.names.get(`${server}\u0000${tool}`) ?? toolName(server, tool)
}
private listeners: (() => void)[] = []
/** Called whenever a server's status, tools or prompts change. */
onChange(f: () => void) {
onChange(f: () => void): () => void {
this.listeners.push(f)
return () => void (this.listeners = this.listeners.filter((x) => x !== f))
}
private changed() {
@@ -194,7 +210,8 @@ export class McpManager {
await close()
}
t.stderr?.on("data", (chunk: Buffer) => {
s.stderr.push(...chunk.toString().split("\n").filter(Boolean))
// Somebody else's text from here on (mcp/clean.ts): no control characters are kept.
s.stderr.push(...chunk.toString().split("\n").map((l) => clean(l)).filter(Boolean))
if (s.stderr.length > 20) s.stderr.splice(0, s.stderr.length - 20)
})
return t
@@ -286,7 +303,7 @@ export class McpManager {
private fail(s: ServerState, why: string): ServerState {
s.status = "failed"
s.error = why
s.error = clean(why, true)
this.changed()
return s
}
@@ -334,10 +351,15 @@ export class McpManager {
const r = await c.listPrompts(cursor ? { cursor } : undefined)
return { items: r.prompts as RemotePrompt[], next: r.nextCursor }
}) : []
s.tools = tools.filter((t) => toolAllowed(t.name, s.cfg.tools))
s.prompts = prompts
// Where a server's words enter: descriptions are text to be shown, so control characters go
// (clean.ts). Names stay as the server spells them — they are what it is called by — and are
// cleaned where they are shown.
s.tools = tools
.filter((t) => toolAllowed(t.name, s.cfg.tools))
.map((t) => ({ ...t, ...(t.description === undefined ? {} : { description: clean(t.description, true) }), ...(t.annotations?.title === undefined ? {} : { annotations: { ...t.annotations, title: clean(t.annotations.title) } }) }))
s.prompts = prompts.map((p) => ({ ...p, ...(p.description === undefined ? {} : { description: clean(p.description, true) }), ...(p.arguments ? { arguments: p.arguments.map((a) => ({ ...a, ...(a.description === undefined ? {} : { description: clean(a.description) }) })) } : {}) }))
s.resources = !!caps.resources && s.cfg.resources !== false
const ins = s.cfg.instructions === false ? undefined : c.getInstructions()?.trim()
const ins = s.cfg.instructions === false ? undefined : clean(c.getInstructions() ?? "", true).trim() || undefined
s.instructions = undefined
if (ins) {
// The server wrote this, not the user: anything aimed at the agent is left out.
@@ -370,24 +392,50 @@ export class McpManager {
return r.contents.map((x) => ("text" in x && typeof x.text === "string" ? x.text : "")).join("\n").trim()
}
/** A tool called directly (not by the model): `/memory` changing the LLeMbas server's memory.
* The text it answered; a tool error is thrown with its text. */
async callText(server: string, tool: string, args: Record<string, unknown>, scope?: string): Promise<string> {
const c = await this.clientOf(server)
const r = (await c.callTool({ name: tool, arguments: args, ...(scope ? { _meta: { lembas: { scope } } } : {}) })) as { content?: { type: string; text?: string }[]; isError?: boolean }
const text = (r.content ?? []).map((x) => (x.type === "text" && typeof x.text === "string" ? x.text : "")).join("\n").trim()
if (r.isError) throw new Error(text || `${tool} failed`)
return text
}
/** Every connected server's tools as LLeMbas CLI tools, and list/read tools for resources. */
tools(): Tool[] {
const out: Tool[] = []
// Different names can come out the same (get.user and get_user; server a.b and a_b): the
// second gets a hash of what it really is, so every tool stays reachable and names stay unique.
// Different names can come out the same (get.user and get_user; server a.b and a_b). Every
// one of such a set gets a hash of what it really is — not only the second to arrive — so a
// server that lists its tools in another order cannot move a name, and with it an "always
// allow", from one tool onto another.
const bare = (s: ServerState, tool: string) => s.name === LIBRARY_SERVER && (s.cfg.tools?.include ?? []).includes(tool)
const counts = new Map<string, number>()
for (const s of this.servers.values()) {
if (s.status !== "connected") continue
for (const t of s.tools) {
const n = bare(s, t.name) ? sanitize(t.name) : toolName(s.name, t.name)
counts.set(n, (counts.get(n) ?? 0) + 1)
}
}
const used = new Set<string>()
const unique = (server: string, tool: string) => {
let n = toolName(server, tool)
if (used.has(n)) n = `${n.slice(0, 55)}_${createHash("sha256").update(`${server}\u0000${tool}`).digest("hex").slice(0, 8)}`
if ((counts.get(n) ?? 0) > 1 || used.has(n)) n = `${n.slice(0, 55)}_${createHash("sha256").update(`${server}\u0000${tool}`).digest("hex").slice(0, 8)}`
used.add(n)
return n
}
for (const s of this.servers.values()) {
if (s.status !== "connected") continue
for (const t of s.tools) {
const library = s.name === LIBRARY_SERVER
// The LLeMbas server's library stands in for this machine's memory tool, so that one tool
// (what its config includes) goes by the bare name and under the memory tool's rules;
// anything else such a server offered is an MCP tool like any other, with a name and a
// permission of its own — never a bare name a built-in tool already has.
const library = bare(s, t.name)
const name = library ? sanitize(t.name) : unique(s.name, t.name)
if (library) used.add(name)
this.names.set(`${s.name}\u0000${t.name}`, name)
const readOnly = t.annotations?.readOnlyHint === true
out.push({
name,
@@ -459,7 +507,7 @@ export class McpManager {
prompts(): McpPromptCommand[] {
return [...this.servers.values()]
.filter((s) => s.status === "connected")
.flatMap((s) => s.prompts.map((p) => ({ name: `${sanitize(s.name)}:${sanitize(p.name)}`, description: p.description ?? `prompt from ${s.name}`, args: (p.arguments ?? []).map((a) => a.name), server: s.name, prompt: p.name })))
.flatMap((s) => s.prompts.map((p) => ({ name: promptCommand(s.name, p.name), description: p.description ?? `prompt from ${s.name}`, args: (p.arguments ?? []).map((a) => a.name), server: s.name, prompt: p.name })))
}
/** A prompt's text with the typed words as its arguments, in order (the last takes the rest). */
@@ -480,8 +528,13 @@ export class McpManager {
/** The system prompt's block of server instructions, or "". */
instructions(): string {
const parts = [...this.servers.values()].filter((s) => s.status === "connected" && s.instructions).map((s) => `<server name="${s.name}">\n${s.instructions}\n</server>`)
return parts.length ? `Instructions from the MCP servers you have tools from (their tools are named mcp__<server>__…):\n<mcp_instructions>\n${parts.join("\n")}\n</mcp_instructions>` : ""
return mcpInstructions(this.serverInstructions())
}
/** Each connected server's own instructions, by server: what the prompt shows (mcpInstructions),
* and what a session note compares (session/prefix.ts). */
serverInstructions(): Record<string, string> {
return Object.fromEntries([...this.servers.values()].filter((s) => s.status === "connected" && s.instructions).map((s) => [s.name, s.instructions!]))
}
/** Sign in to a remote server: show the page, catch the redirect (or take a pasted one). */
@@ -554,3 +607,9 @@ function withTimeout<T>(p: Promise<T>, ms: number, message: string): Promise<T>
let t: ReturnType<typeof setTimeout>
return Promise.race([p, new Promise<T>((_, reject) => (t = setTimeout(() => reject(new Error(message)), ms)))]).finally(() => clearTimeout(t))
}
/** MCP servers' instructions as the system prompt carries them, "" for none. */
export function mcpInstructions(by: Record<string, string>): string {
const parts = Object.entries(by).map(([name, text]) => mcpBlock(name, text))
return parts.length ? `Instructions from the MCP servers you have tools from (their tools are named mcp__<server>__…):\n<mcp_instructions>\n${parts.join("\n")}\n</mcp_instructions>` : ""
}
+93
View File
@@ -0,0 +1,93 @@
// What is said about the MCP servers in words: the states, where a server comes from, and the
// plain list `/mcp` prints where there is no menu (`lembas run`, a prompt sent over the link —
// the web UI shows it as a reply). Lines of a list begin with "- ": they read as they are in a
// terminal and stay one to a line where the reply is drawn as markdown (indented lines would run
// together there). The TUI's menu (tui/mcpmenu.ts) reads the same words.
import { basename } from "node:path"
import type { McpManager, ServerState } from "./index.ts"
import { LIBRARY_SERVER, promptCommand } from "./index.ts"
import { clean, errorLine, mdEscape, redactUrl } from "./clean.ts"
export const STATE_WORDS: Record<ServerState["status"], string> = {
connected: "connected",
connecting: "connecting",
failed: "failed",
needs_auth: "needs sign-in",
disabled: "switched off",
}
/** Where a server is configured: the LLeMbas server's own library (it comes with the login), the
* project's .agent/config.yaml, or the person's own config. */
export function sourceOf(s: Pick<ServerState, "name" | "cfg">): "library" | "project" | "user" {
return s.name === LIBRARY_SERVER ? "library" : s.cfg.source === "project" ? "project" : "user"
}
export const SOURCE_WORDS = { library: "the LLeMbas server's library", project: "this project", user: "your config" } as const
/** `3 tools, 1 prompt, resources` — what a connected server offers. */
export function offers(s: Pick<ServerState, "tools" | "prompts" | "resources">): string {
const n = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`
return [n(s.tools.length, "tool"), ...(s.prompts.length ? [n(s.prompts.length, "prompt")] : []), ...(s.resources ? ["resources"] : [])].join(", ")
}
/** One server's state in a line: `connected — 3 tools`, `failed: <why, one line>`. The reason is
* somebody else's text and may carry what the config resolved to: one line, cleaned, with what
* looks like a secret taken out (clean.ts). */
export function stateLine(s: ServerState): string {
if (s.status === "connected") return `${STATE_WORDS.connected} — ${offers(s)}`
if (s.status === "failed") return `${STATE_WORDS.failed}: ${errorLine(s.error) || "no reason given"}`
if (s.status === "needs_auth") return `${STATE_WORDS.needs_auth} — /mcp auth ${clean(s.name)}`
return STATE_WORDS[s.status]
}
/** Where a server is reached, without what the config may hold that is secret: an address with
* no user, password or query; for a local server the program's name alone — its arguments and
* environment are where tokens are put. */
export function whereOf(s: Pick<ServerState, "cfg">): string {
if (s.cfg.command === undefined) return redactUrl(s.cfg.url ?? "")
const program = Array.isArray(s.cfg.command) ? s.cfg.command[0]! : s.cfg.command.trim().split(/\s+/)[0]!
return `local: ${clean(basename(program))}`
}
/** The servers as a plain list, or one server with its tools and prompts (`name` given) — what
* `/mcp` says where there is no menu. It may leave this machine (a reply in the web UI), so an
* error is its first line only, and never what a local server wrote to stderr. `rule`: what the
* permission rules say of a tool by its name here. `markdown`: the text will be drawn as
* markdown, so names are code and a server's descriptions are escaped — a description cannot
* put a link or an image into the chat. */
export function mcpText(mcp: McpManager, name = "", rule: (tool: string) => string | undefined = () => undefined, o: { markdown?: boolean } = {}): string {
const said = (text: string) => (o.markdown ? mdEscape(text) : text)
const code = (text: string) => (o.markdown ? `\`${text.replace(/`/g, "'")}\`` : text)
const servers = [...mcp.servers.values()]
if (!servers.length) return "No MCP servers are configured. Add one under mcp: in ~/.config/lembas/config.yaml (or this project's .agent/config.yaml)."
if (name) {
const s = mcp.servers.get(name)
if (!s) return `No MCP server "${clean(name)}" — the servers: ${servers.map((x) => clean(x.name)).join(", ")}.`
const lines = [`${said(clean(s.name))} — ${said(stateLine(s))}`, "", `From ${SOURCE_WORDS[sourceOf(s)]} · ${said(whereOf(s))}`]
if (s.status === "connected") {
if (s.tools.length) lines.push("", "Tools:")
for (const t of s.tools) {
const called = mcp.nameOf(s.name, t.name)
const does = { allow: "always allowed", deny: "denied", ask: "asks" }[rule(called) ?? "ask"] ?? "asks"
const about = clean((t.description ?? "").split("\n")[0])
lines.push(`- ${code(clean(called))} — ${does}${t.annotations?.readOnlyHint ? ", read-only" : ""}${about ? ` — ${said(about)}` : ""}`)
}
if (s.prompts.length)
lines.push(
"",
"Prompts:",
...s.prompts.map((p) => {
const about = clean((p.description ?? "").split("\n")[0])
return `- ${code(`/${promptCommand(s.name, p.name)}`)}${about ? ` — ${said(about)}` : ""}`
}),
)
}
return lines.join("\n")
}
return [
"MCP servers:",
...servers.map((s) => `- ${said(clean(s.name))} — ${said(stateLine(s))} (${SOURCE_WORDS[sourceOf(s)]})`),
"",
"/mcp <name> lists one server's tools. A tool asks before it runs unless a permission rule allows it.",
].join("\n")
}
+112
View File
@@ -0,0 +1,112 @@
// HTML pages in answers (harness spec 3.8.0, harness/pages.md): a complete, self-contained HTML
// document the model writes in a fenced block whose info string begins with `html-view`, followed
// by a short title. The web UI and Desktop show it in a sealed frame; a terminal shows a note in
// its place (and keeps the page as a file, pages/store.ts). A terminal's own model is never
// offered pages — this reads replies that have them: a report, a chat seen over the link. How a
// fence is read, the note and the text projection are pinned by harness/conformance/pages.json.
import { LOOP } from "../harness.ts"
import { fillPrompt } from "../prompt/fill.ts"
const P = LOOP.pages
export const TITLE_MAX = P.title_max
const collapse = (s: string) => s.split(/\s+/).filter(Boolean).join(" ")
const cut = (s: string) => collapse(s).slice(0, TITLE_MAX).trim()
/** A fence's info string as a page's title given on the line ("" when none), or null for any
* other code block: the first word is exactly the fence word. */
export function parseInfo(info: string): { title: string } | null {
const m = /^\s*(\S+)(?:\s+([\s\S]*))?$/.exec(info)
if (!m || m[1] !== P.fence) return null
return { title: cut(m[2] ?? "") }
}
/** A page's title: the fence's, else the page's own <title> with its tags stripped, else the
* word for a page without one. */
export function titleFor(code: string, given: string): string {
const own = cut(given)
if (own) return own
const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(code)
return (m ? cut(m[1]!.replace(/<[^>]*>/g, "")) : "") || P.untitled
}
/** A piece of a reply: markdown as it is, or a page fence — `closed` once its closing fence has
* arrived (a fence still streaming is not a page yet). `start` is where the fence begins in the
* text, which stays put as the reply grows: a key for what was saved. */
export type Segment = { kind: "text"; text: string } | { kind: "page"; start: number; title: string; code: string; raw: string; closed: boolean }
const OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/
const CLOSE = (fence: string) => new RegExp(`^ {0,3}${fence[0] === "`" ? "`" : "~"}{${fence.length},}\\s*$`)
/** The reply split into markdown and page fences. A fence of any other language is markdown, to
* its end. Inside a fence nothing opens another (a fence of the other character or a shorter
* one is content), as CommonMark reads them. */
export function splitPages(text: string): Segment[] {
const out: Segment[] = []
const lines = text.split("\n")
let plain: string[] = []
let offset = 0
const flush = () => {
if (plain.length) out.push({ kind: "text", text: plain.join("\n") })
plain = []
}
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!
const open = OPEN.exec(line)
if (!open) {
plain.push(line)
offset += line.length + 1
continue
}
const fence = open[1]!
const close = CLOSE(fence)
let j = i + 1
while (j < lines.length && !close.test(lines[j]!)) j++
const closed = j < lines.length
const page = parseInfo(open[2] ?? "")
if (!page) {
// Some other code block: text, up to its end (or the end of the reply while it streams).
const until = closed ? j : lines.length - 1
for (let k = i; k <= until; k++) {
plain.push(lines[k]!)
offset += lines[k]!.length + 1
}
i = until
continue
}
flush()
const code = lines.slice(i + 1, j).join("\n")
const raw = lines.slice(i, closed ? j + 1 : lines.length).join("\n")
out.push({ kind: "page", start: offset, title: titleFor(code, page.title), code, raw, closed })
offset += raw.length + 1
i = closed ? j : lines.length
}
flush()
return out
}
/** Every finished page of a reply, in order. An unclosed fence is not a page. */
export function pagesOf(text: string): { title: string; html: string }[] {
return splitPages(text).flatMap((s) => (s.kind === "page" && s.closed ? [{ title: s.title, html: s.code }] : []))
}
/** What a client that cannot render shows in a page's place. */
export const pageNote = (title: string) => fillPrompt(P.note, { title })
/** The reply as text, for anything that reads it as text: every finished page as its one line. */
export function textProjection(text: string): string {
if (!text.includes(P.fence)) return text
return splitPages(text)
.map((s) => (s.kind === "text" ? s.text : s.closed ? fillPrompt(P.projection, { title: s.title }) : s.raw))
.join("\n")
}
/** Whether the pages block is in a prompt (pages.md §4): the instance's switch, the model's flag
* and the chat's switch — a scheduled run has no chat switch — and never for a subagent, the
* phone assistant or an agent chat. */
export function pagesOffered(o: { instance?: boolean; model?: boolean; chat?: boolean; where?: string }): boolean {
if (o.where && (P.never as string[]).includes(o.where)) return false
if (o.instance !== true || o.model !== true) return false
return o.where === "scheduled" ? true : o.chat === true
}
+56
View File
@@ -0,0 +1,56 @@
// A page is static (harness pages.md §6): HTML, CSS and inline SVG, nothing that runs and nothing
// that reaches anywhere. This says what in a page breaks that rule, by the spec's lists
// (loop.json pages.static) — the rule as the conformance cases pin it. A terminal shows no page,
// so nothing here is a sanitiser: a client that shows pages rebuilds the document with a real
// parser.
import { LOOP } from "../harness.ts"
const S = LOOP.pages.static
const ELEMENTS = new Set(S.elements.map((e) => e.toLowerCase()))
const ATTRIBUTES = new Set(S.attributes.map((a) => a.toLowerCase()))
const IMAGE = new RegExp(`^data:image/(?:${S.image_types.join("|")});base64,`, "i")
/** Whether an address is one of the two a page may hold: `#fragment`, or an inline picture. */
export const addressAllowed = (v: string) => /^#/.test(v.trim()) || IMAGE.test(v.trim())
/** What CSS would fetch: `@import`, and any url() that is not an allowed address. */
function cssFaults(css: string): string[] {
const out: string[] = []
if (/@import\b/i.test(css)) out.push("css:import")
for (const m of css.matchAll(/url\(\s*(['"]?)([^)'"]*)\1\s*\)/gi)) if (!addressAllowed(m[2]!)) out.push("css:url")
return out
}
/** What makes a page not static, each thing once, in the order first met; none: it is static. */
export function staticFaults(html: string): string[] {
const why: string[] = []
const say = (w: string) => void (why.includes(w) || why.push(w))
const TAG = /<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g
let style = -1
for (const m of html.matchAll(TAG)) {
const name = m[2]!.toLowerCase()
if (m[1]) {
if (name === "style" && style >= 0) {
for (const f of cssFaults(html.slice(style, m.index))) say(f)
style = -1
}
continue
}
if (!ELEMENTS.has(name)) {
say(`element:${name}`)
continue
}
if (name === "style") style = m.index! + m[0].length
for (const a of m[3]!.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {
const attr = a[1]!.toLowerCase()
const value = a[2] ?? a[3] ?? a[4] ?? ""
if (!ATTRIBUTES.has(attr) && !S.attribute_prefixes.some((p) => attr.startsWith(p))) {
say(`attribute:${attr}`)
continue
}
if (S.address_attributes.includes(attr) && !addressAllowed(value)) say(`address:${attr}`)
if (attr === "style") for (const f of cssFaults(value)) say(f)
}
}
return why
}
+20 -19
View File
@@ -1,38 +1,39 @@
// Where a terminal keeps the prototypes a session's model wrote: one file each, the model's
// output as it is, under the state directory — `prototypes/<sessionId>/<n>-<slug>.html` — never in
// the project, and only this user may read them (a page is a page: it may say anything). The web
// UI renders the same fences live; here `/prototype` lists them and a browser opens the file.
// Where a terminal keeps the HTML pages of the replies it shows (harness pages.md): one file each,
// as written, under the state directory — `pages/<sessionId>/<n>-<slug>.html` — never in the
// project, and only this user may read them (a page is a page: it may say anything). The web UI
// and Desktop show the same fences in a sealed frame; here `/pages` lists them and a browser
// opens the file.
import { createHash } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"
import { join } from "node:path"
import { paths } from "../config/paths.ts"
import { titleFor, type PrototypeKind } from "./fence.ts"
import { titleFor } from "./fence.ts"
export interface SavedPrototype {
export interface SavedPage {
n: number
name: string
path: string
}
export const prototypeDir = (sessionId: string) => join(paths.state, "prototypes", sessionId.replace(/[^\w.-]/g, "_"))
export const pageDir = (sessionId: string) => join(paths.state, "pages", sessionId.replace(/[^\w.-]/g, "_"))
const FILE = /^(\d+)-(.*)\.html$/
/** A file name's slug from a title: letters and digits, dashes between, at most 48; the kind
* when the title says nothing. */
export function slugOf(title: string, kind: PrototypeKind): string {
/** A file name's slug from a title: letters and digits, dashes between, at most 48; `page` when
* the title has neither. */
export function slugOf(title: string): string {
const s = title
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 48)
.replace(/-+$/, "")
return s || kind
return s || "page"
}
/** This session's prototypes, in the order they were saved. */
export function listPrototypes(sessionId: string): SavedPrototype[] {
const dir = prototypeDir(sessionId)
/** This session's pages, in the order they were saved. */
export function listPages(sessionId: string): SavedPage[] {
const dir = pageDir(sessionId)
if (!existsSync(dir)) return []
return readdirSync(dir)
.map((name) => ({ name, m: FILE.exec(name) }))
@@ -43,13 +44,13 @@ export function listPrototypes(sessionId: string): SavedPrototype[] {
const hash = (s: string) => createHash("sha256").update(s).digest("hex")
/** Save a prototype the first time it is seen: the fence's code written as it is, mode 0600, as
/** Save a page the first time it is seen: the fence's code written as it is, mode 0600, as
* the next number in the session's directory. The same code seen again (a session reopened,
* a reply redrawn) is the file already there. Returns the path. */
export function savePrototype(sessionId: string, code: string, o: { kind: PrototypeKind; title: string }): string {
const dir = prototypeDir(sessionId)
export function savePage(sessionId: string, code: string, title: string): string {
const dir = pageDir(sessionId)
mkdirSync(dir, { recursive: true, mode: 0o700 })
const have = listPrototypes(sessionId)
const have = listPages(sessionId)
const h = hash(code)
for (const f of have) {
try {
@@ -57,7 +58,7 @@ export function savePrototype(sessionId: string, code: string, o: { kind: Protot
} catch {}
}
const n = (have.at(-1)?.n ?? 0) + 1
const path = join(dir, `${n}-${slugOf(titleFor(code, o.title), o.kind)}.html`)
const path = join(dir, `${n}-${slugOf(titleFor(code, title))}.html`)
writeFileSync(path, code, { mode: 0o600 })
return path
}
+54 -13
View File
@@ -63,21 +63,62 @@ export function toRules(config: PermissionConfig, source?: Rule["source"]): Rule
return rules
}
/** Whether rule `a` speaks of less than rule `b`: everything `a`'s permission and pattern take in
* is taken in by `b`'s, and they are not the same rule (`read *.env` under `read *`, and `read *`
* under `* *`). */
export function narrowerThan(a: Pick<Rule, "permission" | "pattern">, b: Pick<Rule, "permission" | "pattern">): boolean {
if (a.permission === b.permission && a.pattern === b.pattern) return false
return match(a.permission, b.permission) && match(a.pattern, b.pattern)
}
/** What stands in a new rule's way, so that making it would change nothing or loosen what was
* written on purpose: the person's own (global) rule, or any written deny, that takes in all the
* new rule would — and is stricter. Such a rule is changed where it was written. */
export function standsInTheWay(rule: Pick<Rule, "permission" | "pattern" | "action">, rules: Rule[]): Rule | undefined {
return rules.findLast((r) => !r.learned && RANK[r.action] > RANK[rule.action] && (r.source === "global" || r.action === "deny") && match(rule.permission, r.permission) && match(rule.pattern, r.pattern))
}
/** The written rules a new rule does not change, because they are stricter and speak of less
* than it (or are the person's own): what "still applies" after it is made. */
export function stillStricter(rule: Pick<Rule, "permission" | "pattern" | "action">, rules: Rule[]): Rule[] {
return rules.filter((r) => !r.learned && RANK[r.action] > RANK[rule.action] && match(r.permission, rule.permission) && match(r.pattern, rule.pattern) && narrowerThan(r, rule))
}
/** What the rules say of a permission and pattern, before any mode: undefined where none speaks
* (the call is then asked or allowed by its class and the mode). */
export function ruleAction(permission: string, pattern: string, rules: Rule[]): Action | undefined {
return lookupRule(permission, pattern, rules)?.action
}
/** The rule that decides (harness permission/rules.md §2). The last matching rule is the
* candidate. One made after the written ones — a project's, an "always" answer, one set in a
* menu — gives way to whichever of these is stricter than it, the strictest deciding:
* a narrower written rule (`read: allow` leaves `read *.env: ask` asking); the person's own
* answer (their config's last matching rule, of any breadth); and, for an "always" answer, a
* written deny. A candidate from the defaults or the person's own config decides as it is. */
function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule | undefined {
const hit = rules.findLast((r) => match(permission, r.permission) && match(pattern, r.pattern))
// A project's rule (or an "always" answer) that is looser than what the user's global config says
// for the same call gives way to it: the user's ask and deny are the floor a cloned repository
// stands on, not something it can write over.
if (hit && (hit.source === "project" || hit.learned)) {
const own = rules.findLast((r) => r.source === "global" && !r.learned && match(permission, r.permission) && match(pattern, r.pattern))
if (own && RANK[own.action] > RANK[hit.action]) return own
const matches = (r: Rule) => match(permission, r.permission) && match(pattern, r.pattern)
const hit = rules.findLast(matches)
if (!hit || !(hit.source === "project" || hit.learned)) return hit
const floors: Rule[] = rules.filter((r) => r !== hit && !r.learned && matches(r) && narrowerThan(r, hit))
const own = rules.findLast((r) => r.source === "global" && !r.learned && matches(r))
if (own) floors.push(own)
if (hit.learned) {
const written = rules.findLast((r) => !r.learned && matches(r))
if (written?.action === "deny") floors.push(written)
}
// "Always allow git push *" must not undo a configured "git push --force *": deny.
if (hit?.learned) {
const written = rules.findLast((r) => !r.learned && match(permission, r.permission) && match(pattern, r.pattern))
if (written?.action === "deny") return written
}
return hit
return floors.reduce((best, r) => (RANK[r.action] > RANK[best.action] ? r : best), hit)
}
/** What making a rule would do (permission/rules.md §3), before anything is changed: nothing —
* the action is already in force; refused, by the rule in its way; or made, leaving `still`, the
* stricter narrower rules that go on applying. `written`: the rules of the defaults, the
* person's config and the project; `all`: those and the session's own. */
export function judgeNewRule(rule: Pick<Rule, "permission" | "pattern" | "action">, written: Rule[], all: Rule[] = written): { result: "unchanged" } | { result: "refused"; by: Rule } | { result: "made"; still: Rule[] } {
if (ruleAction(rule.permission, rule.pattern, all) === rule.action) return { result: "unchanged" }
const by = standsInTheWay(rule, written)
if (by) return { result: "refused", by }
return { result: "made", still: stillStricter(rule, written) }
}
/** Whether an allow would cover something a written rule denies (its pattern, read as text,
+2 -1
View File
@@ -13,6 +13,7 @@ export interface AgentSpec {
name: string
description: string
instructions: string
/** Read, and not used for a subagent (spec 3.3.0, subagents.md §2): shown so a file that sets it says so. */
model?: string
/** A fixed permission mode; absent = the parent's. */
mode?: Mode
@@ -25,7 +26,7 @@ export interface AgentSpec {
/** Never given to a subagent: it cannot spawn more (so nothing to send to), and it has no user of
* its own to ask. */
export const NOT_FOR_SUBAGENTS = new Set(["task", "job_send", "ask_user", "plan_submit", "plan_write", "plan_update", "tasks", "decisions", "memory", "skill_manage", "settings", "note_manage"])
export const NOT_FOR_SUBAGENTS = new Set(["task", "job_send", "ask_user", "plan_submit", "plan_write", "plan_update", "tasks", "decisions", "memory", "skill_manage", "settings", "note_manage", "report_write"])
export const BUILTIN_AGENTS: AgentSpec[] = [
{
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more