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>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-13 09:17:49 +00:00
1 parent 22bfb5b579
commit 97fb03210a
49 files changed
+2188 -402

No files matched your search

+23
View File
@@ -6,8 +6,24 @@ All notable changes to LLeMbas CLI. The format follows
## [Unreleased]
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, 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.
- **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
@@ -68,6 +84,13 @@ All notable changes to LLeMbas CLI. The format follows
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.
+42 -2
View File
@@ -22,13 +22,16 @@ page *Harness-parity* in LLeMbas CLI's wiki.
| `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 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 |
| `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; 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 |
@@ -55,7 +58,8 @@ page *Harness-parity* in LLeMbas CLI's wiki.
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). A requirement that goes away between the offer and the call makes the call answer the
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.
@@ -74,6 +78,42 @@ page *Harness-parity* in LLeMbas CLI's wiki.
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.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. 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`,
+1 -1
View File
@@ -1 +1 @@
3.7.0
3.8.0
+22 -2
View File
@@ -60,7 +60,6 @@ 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` |
@@ -69,6 +68,7 @@ change to the protocol is a change here first, then in both projects.
| `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
@@ -146,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
@@ -407,6 +406,27 @@ In a scheduled turn:
"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
+286
View File
@@ -0,0 +1,286 @@
{
"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`. 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."
}
}
]
}
-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"
}
}
]
}
+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"
}
]
}
}
]
}
+49 -2
View File
@@ -315,7 +315,7 @@
"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.",
"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}}.",
@@ -327,6 +327,8 @@
"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.",
@@ -442,7 +444,7 @@
"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.",
"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.",
"setting": {
"key": "remote.scheduled",
"label": "Accept scheduled work",
@@ -482,6 +484,30 @@
"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",
"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": {
@@ -773,5 +799,26 @@
"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.",
"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"
]
}
}
+1
View File
@@ -17,6 +17,7 @@
"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": {
+105
View File
@@ -0,0 +1,105 @@
# 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. 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; a page is a complete
document in an `html-view` fence with a short title, one page per fence; everything is inline —
no external script, style, font or image, the frame has no network; charts are drawn with inline
SVG or a canvas script; colours come from the frame's variables so the page follows light and
dark; no forms that submit, no links that navigate.
**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. The frame
What a rendering client must hold to (the server's and Desktop's own tests prove it; it is here
so that a third client does not weaken it): the page runs in a frame of its own origin with
scripts allowed and nothing else — no cookie, no storage of the app's, **no network** (no fetch,
no image, font, script or style from anywhere), no navigation of itself or its parent, no forms
that submit, no pop-ups. The client gives it the five variables and takes its height. A page
never reaches the app that shows it.
+1
View File
@@ -26,6 +26,7 @@
"job_stop": "allow",
"job_send": "allow",
"report": "allow",
"report_write": "allow",
"team_add": "allow",
"team_send": "allow",
"team_read": "allow",
+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.
+8
View File
@@ -0,0 +1,8 @@
<!-- Spec 3.8.0 (pages.md). 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 and the variables 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 small calculator — 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.
- Everything the page needs is inside it: no external scripts, styles, fonts or images — the frame has no network, and anything loaded from elsewhere is simply missing. Draw charts with inline SVG, or with a script that draws on a canvas. No forms that submit, no links that navigate.
- 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.
+6 -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": [],
@@ -268,6 +259,12 @@
"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)."
}
}
}
+121
View File
@@ -0,0 +1,121 @@
# 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 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 any model: the notify-when
texts replace the hint. 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` and offers no tool: 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.
+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"
]
}
}
-4
View File
@@ -1040,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",
+36 -7
View File
@@ -45,7 +45,7 @@ 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, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import { isNote } from "../session/prefix.ts"
import { deniedText, finalReply, judgeMonitor, monitorTimeout, permissionFor, refusalText, runMonitor, runOutcome, scheduledMode, type ScheduledTurn } from "./scheduled.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:
@@ -184,6 +184,10 @@ 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
@@ -220,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
}
@@ -266,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
@@ -290,6 +292,9 @@ export const CAPABILITIES = [
// 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" }
@@ -613,7 +618,7 @@ export class AcpAgent {
const wanted = asMode(p?._meta?.mode) ?? undefined
// 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 } : {}) }
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
@@ -799,6 +804,7 @@ 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
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) => {
@@ -808,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
@@ -1107,7 +1133,8 @@ export class AcpAgent {
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) : "")
return { scheduleId: str(m.schedule_id), runId: str(m.run_id), title: str(m.title), mode: judged.mode, waitMs: judged.wait_s * 1000 }
// 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
@@ -1117,13 +1144,15 @@ export class AcpAgent {
const meta = (extra: Record<string, unknown>, reason: string, text: string, error?: string) => ({
turnId,
...extra,
scheduled: runOutcome({ runId: turn.runId, reason, text, error }),
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
+72 -3
View File
@@ -31,6 +31,8 @@ export interface ScheduledMeta {
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. */
@@ -40,6 +42,10 @@ export interface ScheduledTurn {
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
@@ -107,7 +113,7 @@ export function finalReply(messages: Message[]): string {
}
/** The run's outcome, for `session/prompt`'s `_meta.lembas.scheduled`. */
export function runOutcome(o: { runId: string; reason: string; text: string; error?: string }) {
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"
@@ -117,8 +123,10 @@ export function runOutcome(o: { runId: string; reason: string; text: string; err
} else if (!o.text.trim()) {
status = "failed"
error = SCHEDULED.texts.no_reply
} else status = isSilent(o.text) ? "silent" : "ok"
return { run_id: o.runId, status, text: o.text, error }
} 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 ---------------------------------------------------------------------
@@ -236,3 +244,64 @@ export function runMonitor(command: string, cwd: string, timeoutS: number, env:
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 }
}
-5
View File
@@ -91,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 {
@@ -352,8 +350,6 @@ 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)
/** What may change during the session, as it is now (session/prefix.ts `Changing`): what the
@@ -406,7 +402,6 @@ export function createApp(o: AppOptions): App {
plan,
...(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).
+7 -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") {
@@ -198,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[] = []
+1 -1
View File
@@ -56,6 +56,7 @@ export const ModelSpec = z.strictObject({
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."),
@@ -310,7 +311,6 @@ export const Config = z.strictObject({
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({
+18 -3
View File
@@ -38,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"
@@ -95,7 +96,7 @@ export interface ToolSpecDef {
* `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")[]
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). */
@@ -187,7 +188,21 @@ export const LOOP: {
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
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[] }
/** 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: {
@@ -245,7 +260,7 @@ export const LOOP: {
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; mcp: string; empty: string
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. */
@@ -339,7 +354,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_phone_action, 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_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]),
([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
+2
View File
@@ -99,6 +99,8 @@ export function specFor(m: ServedModel, connection: string): ModelSpec {
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
+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
}
+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
}
+27 -21
View File
@@ -90,29 +90,35 @@ export function ruleAction(permission: string, pattern: string, rules: Rule[]):
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
}
// A rule made after the written ones — a project's, an "always" answer, one set in a menu —
// decides what a broader rule decided, never what a narrower one did: `read: allow` leaves
// `read *.env: ask` asking, `bash: allow` leaves `bash "git push *": ask`. The strictest
// narrower rule that matches this call keeps winning.
if (hit && (hit.source === "project" || hit.learned)) {
const narrower = rules.filter((r) => r !== hit && !r.learned && RANK[r.action] > RANK[hit.action] && match(permission, r.permission) && match(pattern, r.pattern) && narrowerThan(r, hit))
if (narrower.length) return narrower.reduce((a, b) => (RANK[b.action] > RANK[a.action] ? b : a))
}
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,
+1 -1
View File
@@ -26,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[] = [
{
+5 -11
View File
@@ -15,7 +15,7 @@ import blockAgentsMissing from "../../harness/prompts/blocks/agents-missing.md"
import blockAgentsGit from "../../harness/prompts/blocks/agents-git.md" with { type: "text" }
import blockAgentsKeep from "../../harness/prompts/blocks/agents-keep.md" with { type: "text" }
import blockLibrary from "../../harness/prompts/blocks/library.md" with { type: "text" }
import blockPrototypes from "../../harness/prompts/blocks/prototypes.md" with { type: "text" }
import blockHtmlPages from "../../harness/prompts/blocks/html-pages.md" with { type: "text" }
import blockSubagent from "../../harness/prompts/blocks/subagent.md" with { type: "text" }
import blockContext from "../../harness/prompts/blocks/context.md" with { type: "text" }
import blockTeamLead from "../../harness/prompts/blocks/team_lead.md" with { type: "text" }
@@ -57,7 +57,9 @@ const BUILTIN: Record<string, string> = {
"blocks/agents-git.md": blockAgentsGit,
"blocks/agents-keep.md": blockAgentsKeep,
"blocks/library.md": blockLibrary,
"blocks/prototypes.md": blockPrototypes,
// Spec 3.8.0 (pages.md): the server's to send — an agent chat is never offered pages. Here so the
// spec's texts are all one map (and for the note a chat seen over the link may quote).
"blocks/html-pages.md": blockHtmlPages,
"blocks/subagent.md": blockSubagent,
"blocks/context.md": blockContext,
"blocks/team_lead.md": blockTeamLead,
@@ -126,9 +128,6 @@ const GIT_SECTION = [
"- Before a commit, look at `git status`, `git diff` and recent `git log`, stage files by name, and write a message in the repository's style.",
"- Never change git config, skip hooks, force-push or rewrite history unless the user explicitly asks.",
].join("\n")
/** Where a prototype is seen from a terminal (blocks/prototypes.md's {{prototype_surface}}). */
export const PROTOTYPE_SURFACE = "It is saved as a file you can open, and the LLeMbas web UI renders it live."
/** `{{plan_context}}`: the plan with its ids under a heading, and the sentence to work to it. */
export function planContext(plan: Plan | undefined): string {
if (!plan) return ""
@@ -270,9 +269,6 @@ export interface PromptContext {
library?: { scope: string }
/** recall is offered: the tool results carry ids and may be stubs (blocks/context.md, spec 3.0.0). */
context?: boolean
/** Prototypes are offered (blocks/prototypes.md); `sources` the sentence saying what a page
* may load, or "" where nothing says. */
prototypes?: { sources: string }
}
const MAX_INSTRUCTION_CHARS = 40_000
@@ -381,12 +377,10 @@ export function assembleSystem(ctx: PromptContext): string {
}).replace(/\n{3,}/g, "\n\n"),
)
else if (ctx.manageSkills && !ctx.subagent) sections.push(promptText("blocks/skills-empty.md"))
// The library and prototypes (shared blocks): the library whenever its tools are offered, named
// to the bases in scope; prototypes only where they are offered, with where the page is seen.
// The library (a shared block) whenever its tools are offered, named to the bases in scope.
// How tool results are kept short (ids, stubs, recall): wherever recall is offered.
if (ctx.context) sections.push(promptText("blocks/context.md"))
if (ctx.library && !ctx.subagent) sections.push(fillPrompt(promptText("blocks/library.md"), { knowledge_scope: ctx.library.scope }))
if (ctx.prototypes && !ctx.subagent) sections.push(fillPrompt(promptText("blocks/prototypes.md"), { prototype_sources: ctx.prototypes.sources, prototype_surface: PROTOTYPE_SURFACE }))
if (ctx.teamLead && !ctx.subagent) sections.push(promptText("blocks/team_lead.md"))
if (ctx.subagent && ctx.member)
-96
View File
@@ -1,96 +0,0 @@
// A prototype (harness/prompts/blocks/prototypes.md, shared with LLeMbas: services/prototypes.py):
// a complete HTML page the model writes in a fenced block whose language is `prototype-chat` or
// `prototype-page`, with a short title on the same line. The web UI renders it live; a terminal
// saves it as a file (prototype/store.ts) and draws one line in its place. How the fence's info
// string is read, and where the title comes from, is pinned by harness/conformance/prototype.json.
export type PrototypeKind = "chat" | "page"
export interface PrototypeInfo {
kind: PrototypeKind
/** The title given on the fence line, "" when none was. */
title: string
}
/** The languages that make a fence a prototype; bare `prototype` is the inline kind. */
const KINDS: Record<string, PrototypeKind> = { "prototype-chat": "chat", "prototype-page": "page", prototype: "chat" }
export const TITLE_MAX = 80
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 prototype, or null for any other code block. The first word
* (whatever its case) is the language; the rest of the line is the title. */
export function parseInfo(info: string): PrototypeInfo | null {
const m = /^\s*(\S+)(?:\s+([\s\S]*))?$/.exec(info)
if (!m) return null
const kind = KINDS[m[1]!.toLowerCase()]
if (!kind) return null
return { kind, title: cut(m[2] ?? "") }
}
/** The prototype's title: the fence's, else the page's own <title> with its tags stripped,
* whitespace collapsed, at most TITLE_MAX characters; "" when neither says. */
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, "")) : ""
}
/** A piece of a reply: markdown as it is, or a prototype fence — `closed` once its closing fence
* has arrived (a fence still streaming is drawn as the code block it is so far). `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: "prototype"; start: number; info: PrototypeInfo; 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 prototype fences. A fence of any other language is markdown.
* Inside a fence nothing opens another (a fence of the other character or a longer one is
* content), as CommonMark reads them. */
export function splitPrototypes(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 info = open[2] ?? ""
const close = CLOSE(fence)
let j = i + 1
while (j < lines.length && !close.test(lines[j]!)) j++
const closed = j < lines.length
const proto = parseInfo(info)
const body = lines.slice(i + 1, j)
if (!proto) {
// 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 raw = lines.slice(i, closed ? j + 1 : lines.length).join("\n")
out.push({ kind: "prototype", start: offset, info: proto, code: body.join("\n"), raw, closed })
offset += raw.length + 1
i = closed ? j : lines.length
}
flush()
return out
}
+1 -1
View File
@@ -37,7 +37,7 @@ export interface CommandInfo {
* the two equal). A custom command or a skill of one of these names is not a command — in the TUI
* the built-in wins — so it is not one here either, even where the built-in is not offered. */
export const TUI_COMMAND_NAMES = [
"agents", "continue", "help", "model", "effort", "mode", "plan", "plans", "prototype", "review", "changelog", "init", "release", "tasks", "decisions", "decide",
"agents", "continue", "help", "model", "effort", "mode", "plan", "plans", "pages", "review", "changelog", "init", "release", "tasks", "decisions", "decide",
"jobs", "sessions", "resume", "remote", "delete", "new", "clear", "copy", "undo", "redo", "diff", "checkpoint", "checkpoints", "branch", "commit", "context",
"compact", "memory", "skills", "skill", "personality", "voice", "speak", "mcp", "login", "logout", "settings", "usage", "kb", "theme", "skin", "terminal",
"icons", "trust", "reload", "restart", "quit", "exit", "q", "team", "rename", "schedule", "schedules", "search", "permissions", "status", "command",
+9 -5
View File
@@ -8,7 +8,7 @@ import { isAbsolute } from "node:path"
import type { Asker, AttachmentInfo, Bus } from "../bus/index.ts"
import type { Mode } from "../config/schema.ts"
import type { Level } from "../provider/effort.ts"
import { evaluate, ruleAction, shadowsDeny, standsInTheWay, stillStricter, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
import { evaluate, judgeNewRule, ruleAction, shadowsDeny, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
import { ProviderError, type Client, type ImagePart, type Message, type ResolvedModel, type ToolCallPart, type Usage } from "../provider/types.ts"
import type { Plan } from "../plan/plan.ts"
import { LOOP } from "../harness.ts"
@@ -270,6 +270,8 @@ export class Engine {
// The team tools' requirement: offered as the prompt is made; whether it is met is the team's
// to answer at each call (team.md §2: one_agent or one_request).
if (this.o.team?.offered()) could.add("team")
// A schedule's run that notifies (reports.md §2): report_write is in the list for the session.
if (this.o.toolCtx.report !== undefined) could.add("scheduled")
const L = this.o.toolCtx.library
const have = L?.lib.bases().filter((b) => b.documents > 0).map((b) => b.name) ?? []
if (have.some((b) => !L!.bases || L!.bases.includes(b))) could.add("knowledge")
@@ -281,6 +283,8 @@ export class Engine {
const met = this.could()
if (this.mode !== "plan") met.delete("plan")
if (this.o.toolCtx.show === undefined) met.delete("display")
// …and met only while the turn is the schedule's own.
if (!this.o.toolCtx.report?.active()) met.delete("scheduled")
return met
}
@@ -426,14 +430,14 @@ export class Engine {
* that still apply are named in `still`.
* - A save that fails leaves the rule in force for this session, and says why. */
setRule(rule: Pick<Rule, "permission" | "pattern" | "action">): { saved: "project" | "session"; still: Rule[]; failed?: string } | { unchanged: true } | { refused: Rule } {
if (ruleAction(rule.permission, rule.pattern, this.rules) === rule.action) return { unchanged: true }
const floor = standsInTheWay(rule, this.o.perm.rules)
if (floor) return { refused: floor }
const judged = judgeNewRule(rule, this.o.perm.rules, this.rules)
if (judged.result === "unchanged") return { unchanged: true }
if (judged.result === "refused") return { refused: judged.by }
this.sessionRules = this.sessionRules.filter((r) => !(r.permission === rule.permission && r.pattern === rule.pattern))
const made: Rule = { ...rule, source: "project" }
this.sessionRules.push(made)
this.set.add(made)
const still = stillStricter(rule, this.o.perm.rules)
const still = judged.still
if (!this.o.persistRule) return { saved: "session", still }
try {
this.o.persistRule({ ...rule })
+1 -1
View File
@@ -120,7 +120,7 @@ export function today(at = new Date()): string {
/** A requirement a tool can have (the spec's `requires`, and the CLI's own: vision, project,
* knowledge). */
export type Requirement = "vision" | "plan" | "project" | "knowledge" | "display" | "page" | "forge" | "team"
export type Requirement = "vision" | "plan" | "project" | "knowledge" | "display" | "page" | "forge" | "team" | "scheduled"
/** Rule 4: the tool list is fixed for the session. A tool is offered when every requirement it has
* is one the session could meet at some point (`could`), decided once as the prompt is made; a
+2
View File
@@ -8,6 +8,7 @@ import { readTool } from "./read.ts"
import { globTool, grepTool, listTool } from "./search.ts"
import { viewImageTool } from "./view_image.ts"
import { planSubmitTool } from "./plan_submit.ts"
import { reportWriteTool } from "./report_write.ts"
import { planUpdateTool } from "./plan_update.ts"
import { planWriteTool } from "./plan_write.ts"
import { taskTool } from "./task.ts"
@@ -60,6 +61,7 @@ export const BUILTIN_TOOLS: Tool[] = [
decisionsTool,
askUserTool,
planSubmitTool,
reportWriteTool,
memoryTool,
sessionSearchTool,
notesSearchTool,
+29
View File
@@ -0,0 +1,29 @@
// report_write (harness reports.md, spec 3.8.0): a scheduled run files its report. On a device the
// report is kept with the turn and travels back in the turn's answer (acp.md *Scheduled work*):
// the server stores it, notifies, and lists it. Offered only in a session a schedule opened for
// its run (`requires: scheduled`), and it answers the spec's unavailable text in a turn of that
// session that is not the schedule's.
import { z } from "zod"
import { reportResult } from "../acp/scheduled.ts"
import { described } from "../harness.ts"
import { defineTool } from "./tool.ts"
export const reportWriteTool = defineTool({
...described("report_write"),
purpose: false,
access: "report_write",
requires: "scheduled",
schema: z.object({
title: z.string().min(1).max(160),
body: z.string().min(1),
summary: z.string().min(1).max(400),
importance: z.enum(["normal", "high"]).optional(),
}),
// It writes nothing here and reaches nobody but the schedule's owner: allowed without asking.
permission: () => ({ permission: "report_write", class: "interact", patterns: ["*"] }),
async run(a, ctx) {
// The engine answers `unavailable` where the turn is not a run; this is the run.
const calls = ctx.report!.file({ title: a.title.trim(), body: a.body, summary: a.summary.trim(), importance: a.importance ?? "normal" })
return { output: reportResult(calls), title: `${a.title.trim()}${calls > 1 ? " · replaces the first" : ""}` }
},
})
+6 -1
View File
@@ -74,6 +74,11 @@ export interface ToolContext {
/** Open a file in the user's viewer (the show tool): set only where a client over the link said
* it can show files (harness/acp.md, capability `show`). Absent: no display, and show is not offered. */
show?: (req: import("./show.ts").ShowRequest, callId?: string) => Promise<import("./show.ts").ShowReply>
/** A scheduled run's report (harness reports.md): set only in a session a schedule opened for
* its run that notifies at all. `active`: the turn running now is the schedule's (not a person
* writing into the run's session); `file` keeps the report — the last one written is the
* run's — and says how many this run has written. Absent: report_write is not offered. */
report?: { active(): boolean; file(report: { title: string; body: string; summary: string; importance: "normal" | "high" }): number }
/** The scope sent on every call to the server's memory (`_meta.lembas.scope`, harness/acp.md
* *Memory*): the id of a session the client opened; none for a session of this device's own. */
libraryScope?: string
@@ -131,7 +136,7 @@ export interface Tool<S extends z.ZodType = z.ZodType> {
* display`). The tool list is the session's (harness context.md §10): one the session could
* never meet leaves the tool out; one that comes and goes (plan mode, a display) keeps it in, and
* a call while it is unmet answers the spec's `unavailable` text. */
requires?: "vision" | "plan" | "project" | "knowledge" | "display" | "team"
requires?: "vision" | "plan" | "project" | "knowledge" | "display" | "team" | "scheduled"
description: string
schema: S
/** The JSON Schema sent to the model, when it does not come from `schema` (MCP tools). */
+6 -6
View File
@@ -26,7 +26,7 @@ import { findSetting, show, type Scope } from "../config/settings.ts"
import { ingest } from "../library/ingest.ts"
import { findSkill, skillMessage, slug } from "../skill/index.ts"
import { PERSONALITIES, personalityText } from "../prompt/personality.ts"
import { listPrototypes } from "../prototype/store.ts"
import { listPages } from "../pages/store.ts"
import { keyMatcher } from "../voice/index.ts"
import { PLAYER_NAMES, playerFor, recorderFor } from "../voice/audio.ts"
import { duration } from "../duration.ts"
@@ -386,17 +386,17 @@ export const COMMANDS: Command[] = [
},
},
{
name: "prototype",
name: "pages",
args: "[n]",
description: "this session's prototypes — HTML pages the model wrote, saved as files; with a number, that one's path",
description: "the HTML pages in this session's replies, saved as files to open in a browser; with a number, that one's path",
run(c, arg) {
const id = c.app.engine.sessionId
const list = id ? listPrototypes(id) : []
if (!list.length) return c.view.info("no prototypes in this session yet")
const list = id ? listPages(id) : []
if (!list.length) return c.view.info("no pages in this session's replies")
const wanted = arg.trim()
if (wanted) {
const one = list.find((p) => String(p.n) === wanted)
return one ? c.view.info(one.path) : c.view.info(`no prototype ${wanted} here — ${list.map((p) => p.n).join(", ")}`, "warn")
return one ? c.view.info(one.path) : c.view.info(`no page ${wanted} here — ${list.map((p) => p.n).join(", ")}`, "warn")
}
c.view.info(list.map((p) => `${p.n} ${p.path}`).join("\n"))
},
+9 -9
View File
@@ -8,7 +8,7 @@ import { clipDiff } from "../diffclip.ts"
import { blockOf, callDuration, callTitle, drawnBlock, type CallState } from "../../session/display.ts"
import { num } from "../locale.ts"
import { NOTICES } from "../notices.ts"
import { splitPrototypes } from "../../prototype/fence.ts"
import { pageNote, splitPages } from "../../pages/fence.ts"
/** A call the transcript does not draw: a plan change (the panel above the prompt follows it) or a
* tool the spec marks hidden — under its former name too (a stored session's `todo`). */
@@ -35,27 +35,27 @@ function UserMessage(p: { item: Extract<Item, { kind: "user" }> }) {
)
}
/** A reply as markdown — except a completed prototype fence, which is saved as a file
* (state.ts) and drawn as one line saying so in its place; while it still streams it is the
* code block it is so far. */
/** A reply as markdown — except a finished page fence (harness pages.md): a terminal cannot show
* a page, so the note stands in its place, with where the page was saved (state.ts); while it
* still streams it is the code block it is so far. */
function AssistantMessage(p: { item: Extract<Item, { kind: "assistant" }> }) {
const { theme, md } = useTui()
const segments = () => (p.item.text.includes("```") || p.item.text.includes("~~~") ? splitPrototypes(p.item.text) : [])
const whole = () => !segments().some((s) => s.kind === "prototype")
const segments = () => (p.item.text.includes("```") || p.item.text.includes("~~~") ? splitPages(p.item.text) : [])
const whole = () => !segments().some((s) => s.kind === "page")
return (
<box paddingLeft={2} marginTop={1} flexDirection="column">
<Show when={!whole()} fallback={<markdown content={p.item.text.trim()} syntaxStyle={md()} streaming={p.item.streaming} fg={theme().colors.text} conceal />}>
<For each={segments()}>
{(seg, i) => {
const saved = () => (seg.kind === "prototype" && seg.closed ? p.item.prototypes?.[seg.start] : undefined)
const saved = () => (seg.kind === "page" && seg.closed ? (p.item.pages?.[seg.start] ?? { title: seg.title }) : undefined)
const last = () => i() === segments().length - 1
return (
<Show
when={saved()}
fallback={<markdown content={(seg.kind === "text" ? seg.text : seg.raw).trim()} syntaxStyle={md()} streaming={p.item.streaming && last()} fg={theme().colors.text} conceal />}
>
<text fg={theme().colors.muted} wrapMode="none" truncate>
{`prototype · ${saved()!.title || saved()!.kind} · saved to ${saved()!.path}`}
<text fg={theme().colors.muted} wrapMode="word">
{`${pageNote(saved()!.title)}${saved()!.path ? ` — saved to ${saved()!.path}` : ""}`}
</text>
</Show>
)
+1 -1
View File
@@ -17,7 +17,7 @@ import type { Mark } from "./notices.ts"
const GROUPS: [string, string[]][] = [
["This session", ["new", "sessions", "search", "rename", "delete", "continue", "undo", "redo", "compact", "context", "copy", "remote"]],
["Model and how it works", ["model", "effort", "mode", "permissions", "plan", "plans", "personality", "team", "agents", "jobs"]],
["The project", ["diff", "commit", "branch", "checkpoint", "checkpoints", "review", "init", "changelog", "release", "tasks", "decisions", "decide", "prototype", "trust"]],
["The project", ["diff", "commit", "branch", "checkpoint", "checkpoints", "review", "init", "changelog", "release", "tasks", "decisions", "decide", "pages", "trust"]],
["What it knows and can use", ["memory", "skills", "skill", "command", "kb", "mcp", "schedule"]],
["Account and settings", ["status", "login", "logout", "usage", "settings", "voice", "speak"]],
["Look", ["theme", "icons", "terminal"]],
+22 -21
View File
@@ -13,8 +13,8 @@ import type { QuestionReply, QuestionRequest } from "../tool/ask_user.ts"
import { CONTINUE_PROMPT, STEER_MARK } from "../session/engine.ts"
import { shownLine, stripMark } from "../jobs/note.ts"
import type { JobInfo } from "../jobs/registry.ts"
import { splitPrototypes, titleFor, type PrototypeKind } from "../prototype/fence.ts"
import { savePrototype } from "../prototype/store.ts"
import { splitPages } from "../pages/fence.ts"
import { savePage } from "../pages/store.ts"
import { CHARS_PER_TOKEN } from "../provider/tokens.ts"
import { isNote } from "../session/prefix.ts"
import { blockOf, callTitle, resultFacts as factsOf } from "../session/display.ts"
@@ -28,8 +28,9 @@ export type Item =
/** `mid`: sent while the agent worked, and given to it at a step boundary. `machine`: the harness
* said it (a job's note), not the person. */
| { kind: "user"; id: string; text: string; mid?: boolean; machine?: boolean }
/** `prototypes`: the prototype fences in the text that have been saved, by where each starts. */
| { kind: "assistant"; id: string; text: string; streaming: boolean; prototypes?: Record<number, SavedPrototype> }
/** `pages`: the page fences in the text (harness pages.md), by where each starts — its title,
* and where it was saved when it could be. */
| { kind: "assistant"; id: string; text: string; streaming: boolean; pages?: Record<number, SavedPage> }
| { kind: "reasoning"; id: string; text: string; streaming: boolean; started: number; ms?: number; tokens?: number }
| {
kind: "tool"
@@ -65,28 +66,28 @@ export type Item =
export type Phase = "idle" | "waiting" | "thinking" | "writing" | "tools"
/** A prototype the model wrote, saved as a file (prototype/store.ts). */
export interface SavedPrototype {
kind: PrototypeKind
/** A page in a reply: its title, and the file it was saved as (pages/store.ts) when there is a
* session to keep it under. */
export interface SavedPage {
title: string
path: string
path?: string
}
/** Whether a reply might hold a fenced block at all, before it is split. */
const mayFence = (text: string) => text.includes("```") || text.includes("~~~")
/** Every completed prototype fence in a reply, saved the first time it is seen — the model's
* output as it is, under the state directory — and noted on the item, so the transcript draws
* one line in its place. Nothing without a session to keep it under. */
function keepPrototypes(sessionId: string | undefined, it: Extract<Item, { kind: "assistant" }>) {
if (!sessionId || !mayFence(it.text)) return
for (const seg of splitPrototypes(it.text)) {
if (seg.kind !== "prototype" || !seg.closed || it.prototypes?.[seg.start]) continue
const title = titleFor(seg.code, seg.info.title)
/** Every finished page fence in a reply, noted on the item so the transcript draws the note in
* its place — and saved the first time it is seen, as written, under the state directory, where
* there is a session to keep it under. */
function keepPages(sessionId: string | undefined, it: Extract<Item, { kind: "assistant" }>) {
if (!mayFence(it.text)) return
for (const seg of splitPages(it.text)) {
if (seg.kind !== "page" || !seg.closed || it.pages?.[seg.start]) continue
let path: string | undefined
try {
const path = savePrototype(sessionId, seg.code, { kind: seg.info.kind, title })
;(it.prototypes ??= {})[seg.start] = { kind: seg.info.kind, title, path }
if (sessionId) path = savePage(sessionId, seg.code, seg.title)
} catch {}
;(it.pages ??= {})[seg.start] = { title: seg.title, ...(path ? { path } : {}) }
}
}
@@ -195,7 +196,7 @@ export function createView(bus: Bus) {
if (last?.kind === "assistant" && last.streaming) last.text += c.text
else s.items.push({ kind: "assistant", id: nextId(), text: c.text, streaming: true })
const reply = s.items[s.items.length - 1]!
if (reply.kind === "assistant") keepPrototypes(s.sessionId, reply)
if (reply.kind === "assistant") keepPages(s.sessionId, reply)
s.phase = "writing"
} else {
if (last?.kind === "reasoning" && last.streaming) last.text += c.text
@@ -215,7 +216,7 @@ export function createView(bus: Bus) {
if ((it.kind === "assistant" || it.kind === "reasoning") && it.streaming) {
it.streaming = false
if (it.kind === "reasoning") it.ms = Date.now() - it.started
else keepPrototypes(s.sessionId, it)
else keepPages(s.sessionId, it)
}
}
@@ -528,7 +529,7 @@ export function createView(bus: Bus) {
for (const p of m.parts) {
if (p.type === "text" && p.text.trim()) {
const it: Extract<Item, { kind: "assistant" }> = { kind: "assistant", id: nextId(), text: p.text, streaming: false }
keepPrototypes(state.sessionId, it)
keepPages(state.sessionId, it)
items.push(it)
}
else if (p.type === "reasoning" && p.text.trim()) items.push({ kind: "reasoning", id: nextId(), text: p.text, streaming: false, started: 0 })
+6 -6
View File
@@ -309,7 +309,7 @@ test("initialize lists the 1.1.0 capabilities", async () => {
fake = fakeProvider([])
config(fake.url)
const { init } = await client(limitsFor(project()))
for (const cap of ["context", "library", "prototypes", "plan_state", "rewind"]) expect(init._meta.lembas.capabilities).toContain(cap)
for (const cap of ["context", "library", "plan_state", "rewind"]) expect(init._meta.lembas.capabilities).toContain(cap)
})
test("show (spec 3.0.0): offered only to a client that shows files; the file goes over _lembas/show", async () => {
@@ -332,7 +332,7 @@ test("show (spec 3.0.0): offered only to a client that shows files; the file goe
expect(fake.requests[2].tools.map((t: any) => t.function.name)).not.toContain("show")
})
test("the context reaches the prompt: the instance's instructions, its personalization, prototypes; not its knowledge bases", async () => {
test("the context reaches the prompt: the instance's instructions, its personalization; not its knowledge bases, and no pages", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "one" })] }, { chunks: [delta({ content: "two" })] }, { chunks: [delta({ content: "three" })] }])
config(fake.url, "personality: concise\ninstructions: local words\n")
const root = project()
@@ -352,10 +352,10 @@ test("the context reaches the prompt: the instance's instructions, its personali
expect(system()).not.toContain("local words")
expect(system()).toContain("## Personality\n\n")
expect(system()).toContain("formal")
// Prototypes offered, with what a page may load and where it is seen from a terminal.
expect(system()).toContain("prototype-chat")
expect(system()).toContain("The page may load nothing from the network.")
expect(system()).toContain("It is saved as a file you can open, and the LLeMbas web UI renders it live.")
// An older client's `prototypes` is not read, and an agent chat is never offered HTML pages
// (spec 3.8.0, pages.md §4).
expect(system()).not.toContain("prototype-chat")
expect(system()).not.toContain("html-view")
// The instance's knowledge bases are not the device's (spec 3.0.0): an older client's `library`
// names nothing to the model — nothing unfilled reaches it either.
expect(system()).not.toContain("Manuals")
+1 -1
View File
@@ -275,7 +275,7 @@ test("the terminal: a real shell through the link, only where remote.terminal sa
config(fake.url)
const root = project()
const off = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true })
expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "prototypes", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled"])
expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled", "reports"])
await expect(off.c.request("_lembas/terminal/open", { cwd: root })).rejects.toThrow("lembas remote terminal on")
const { c, init } = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true, terminal: true })
+50 -6
View File
@@ -1,7 +1,7 @@
// What the CLI does with each conformance case (harness/conformance/*.json). The cases are the
// harness spec's: LLeMbas runs the same files through its own implementation. The test compares
// this with each case's `expect`; `bun run harness record` fills in an `expect` a new case lacks.
import { alwaysPatterns, toRules, evaluate, DEFAULT_RULES, type PermissionRequest } from "../src/permission/evaluate.ts"
import { alwaysPatterns, toRules, evaluate, judgeNewRule, ruleAction, DEFAULT_RULES, type PermissionRequest, type Rule } from "../src/permission/evaluate.ts"
import { BUILTIN_HARDLINE, hardlineCommand, plainCommands } from "../src/permission/hardline.ts"
import { splitCommand, words } from "../src/permission/bash.ts"
import { prefix } from "../src/permission/arity.ts"
@@ -15,7 +15,7 @@ import type { Mode, PermissionConfig } from "../src/config/schema.ts"
import { apply, fromTodos, normalise, type Plan } from "../src/plan/plan.ts"
import { ToolCallAccumulator, toOpenAIMessages } from "../src/provider/openai-chat.ts"
import type { Message } from "../src/provider/types.ts"
import { parseInfo, titleFor } from "../src/prototype/fence.ts"
import { pageNote, pagesOf, pagesOffered, textProjection } from "../src/pages/fence.ts"
import { resolveBase } from "../src/library/store.ts"
import { NarrowError, narrowParameters, type Narrow } from "../src/harness.ts"
import { fillPrompt } from "../src/prompt/fill.ts"
@@ -35,7 +35,7 @@ import { endLine, progressLine, progressText, type Progress } from "../src/sessi
import { callDuration, callFacts, callTitle, changeText, diffCounts, drawnBlock, type CallState } from "../src/session/display.ts"
import { checkMode, requestRefusal, tighten, whoDecides, type Grant } from "../src/team/delegation.ts"
import { fillPrompt as fillText } from "../src/prompt/fill.ts"
import { isSilent, judgeCase, monitorHash, scheduledMode, stripSentinel } from "../src/acp/scheduled.ts"
import { isSilent, judgeCase, monitorHash, notifyInstruction, reportResult, reportTool, runLeaves, scheduledMode, stripSentinel } from "../src/acp/scheduled.ts"
type Case = Record<string, unknown>
@@ -115,10 +115,54 @@ export const AREAS: Record<string, (c: Case) => unknown> = {
if (c.op === "todos") return fromTodos(c.todos)
throw new Error(`plan: unknown op ${String(c.op)}`)
},
prototype: (c) => {
const info = parseInfo(c.info as string)
return info ? { kind: info.kind, title: titleFor(c.code as string, info.title) } : null
// HTML pages in answers (pages.md, spec 3.8.0): the fence, the note, the text projection, where
// pages are offered, the session note for a switch changed mid-chat.
pages: (c) => {
switch (c.show) {
case "fence":
return { pages: pagesOf(c.text as string), projection: textProjection(c.text as string) }
case "note":
return { note: pageNote(c.title as string) }
case "offered":
return { offered: pagesOffered(c as { instance?: boolean; model?: boolean; chat?: boolean; where?: string }) }
case "note_line":
return { line: c.change === "on" ? fillText(CONTEXT.note.pages_on, { pages_text: c.pages_text as string }) : CONTEXT.note.pages_off }
default:
throw new Error(`pages: unknown show ${String(c.show)}`)
}
},
// Reports (reports.md, spec 3.8.0): where report_write is offered, the instruction in the run's
// prompt, the tool's answer, and what a run leaves.
reports: (c) => {
switch (c.show) {
case "offered": {
const tool = reportTool(c as { session: string; notify?: unknown; turn: string; subagent?: boolean })
return tool === "unavailable" ? { tool, text: TOOL_SPECS.report_write!.unavailable } : { tool }
}
case "instruction":
return { text: notifyInstruction(c.notify, c.condition) }
case "result":
return { text: reportResult(c.calls as number) }
case "run":
return runLeaves(c as never)
default:
throw new Error(`reports: unknown show ${String(c.show)}`)
}
},
// Which permission rule decides, and what making one does (permission/rules.md, spec 3.8.0).
rules: (c) => {
const written: Rule[] = [...(c.defaults ? toRules(DEFAULT_RULES, "default") : []), ...toRules((c.user ?? {}) as PermissionConfig, "global"), ...toRules((c.project ?? {}) as PermissionConfig, "project")]
// An "always" answer is a learned rule; one set in a menu is a project's rule, in the session as in the file.
const made: Rule[] = ((c.made ?? []) as { permission: string; pattern: string; action: Rule["action"]; by: string }[]).map((m) => ({ permission: m.permission, pattern: m.pattern, action: m.action, ...(m.by === "always" ? { learned: true } : { source: "project" as const }) }))
const bare = (r: Rule) => ({ permission: r.permission, pattern: r.pattern, action: r.action })
if (c.set) {
const j = judgeNewRule(c.set as Rule, written, [...written, ...made])
return j.result === "made" ? { result: "made", still: j.still.map(bare) } : j.result === "refused" ? { result: "refused", by: bare(j.by) } : { result: "unchanged" }
}
const q = c.request as { permission: string; pattern: string }
return ruleAction(q.permission, q.pattern, [...written, ...made]) ?? null
},
fill: (c) => {
try {
return { text: fillPrompt(c.text as string, c.vars as Record<string, string>) }
+4 -3
View File
@@ -153,7 +153,7 @@ test("spec 3.0.0: every tool says where it is offered; the CLI's are the agent's
// plan_write's former name rather than a tool.
expect(TOOL_SPECS.todo).toBeUndefined()
expect(TOOL_SPECS.plan_write!.aliases.cli).toEqual(["todo"])
const shared = ["ask_user", "edit", "glob", "grep", "job_list", "job_output", "job_send", "job_stop", "list", "memory", "plan_submit", "plan_update", "plan_write", "read", "recall", "report", "session_search", "show", "skill_manage", "skill_view", "skills_list", "task", "team_add", "team_assign", "team_decide", "team_findings", "team_finish", "team_read", "team_replace", "team_request", "team_send", "team_stop", "team_whoami", "web_fetch", "web_search", "write"]
const shared = ["ask_user", "edit", "glob", "grep", "job_list", "job_output", "job_send", "job_stop", "list", "memory", "plan_submit", "plan_update", "plan_write", "read", "recall", "report", "report_write", "session_search", "show", "skill_manage", "skill_view", "skills_list", "task", "team_add", "team_assign", "team_decide", "team_findings", "team_finish", "team_read", "team_replace", "team_request", "team_send", "team_stop", "team_whoami", "web_fetch", "web_search", "write"]
expect(Object.values(TOOL_SPECS).filter((t) => t.scope === "shared").map((t) => t.name).sort()).toEqual(shared.sort())
})
@@ -232,11 +232,12 @@ test("every {{variable}} in a description is declared, and none reaches a model"
else expect(system).not.toContain("The current plan")
}
}
app.setContext({ instructions: "Be brief.", prototypes: { offered: true, sources: "" } }, "example")
app.setContext({ instructions: "Be brief." }, "example")
const withContext = app.engine.compose("manual", plan)
expect(withContext).not.toContain("{{")
expect(withContext).toContain("## Instructions from example\n\nBe brief.")
expect(withContext).toContain("prototype-page")
// Spec 3.8.0 (pages.md §4): an agent chat is never offered HTML pages.
expect(withContext).not.toContain("html-view")
})
test("acp.md names every _lembas method the code handles or sends, and every capability", async () => {
+95
View File
@@ -0,0 +1,95 @@
// HTML pages in a terminal (harness spec 3.8.0, pages.md): a terminal's model is never offered
// pages, but a reply that has one — a report, a chat seen over the link, an older session — is
// drawn with the note in the page's place, and the page is kept as a file under the state
// directory; /pages lists them. How a fence is read is the conformance area `pages`.
import { afterEach, expect, test } from "bun:test"
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import { join } from "node:path"
import { paths } from "../src/config/paths.ts"
import { loadConfig } from "../src/config/load.ts"
import { pageNote, parseInfo, splitPages, textProjection, titleFor } from "../src/pages/fence.ts"
import { listPages, pageDir, savePage, slugOf } from "../src/pages/store.ts"
import { delta } from "./fake-provider.ts"
import { tui } from "./tui/harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
const PAGE = "<!doctype html>\n<title>Bakery</title>\n<p>Fresh bread.</p>"
test("the info line: exactly html-view, the title the rest of the line or the page's own", () => {
expect(parseInfo("html-view Monthly sales")).toEqual({ title: "Monthly sales" })
expect(parseInfo("html-view")).toEqual({ title: "" })
expect(parseInfo("HTML-View x")).toBeNull()
expect(parseInfo("html")).toBeNull()
expect(parseInfo("prototype-page Old")).toBeNull()
expect(titleFor("<title> <b>From</b>\n the page </title>", "")).toBe("From the page")
expect(titleFor(PAGE, "Given")).toBe("Given")
expect(titleFor("<p>none</p>", "")).toBe("Page")
})
test("a reply split: markdown as it is, a page fence closed or still streaming, other code blocks left alone", () => {
const text = "Here:\n\n```html-view Bakery landing\n" + PAGE + "\n```\n\nAnd code:\n\n```js\nconsole.log(1)\n```\n\n```html-view\n<p>half"
const segs = splitPages(text)
expect(segs.map((s) => s.kind)).toEqual(["text", "page", "text", "page"])
expect(segs[1]).toMatchObject({ kind: "page", title: "Bakery landing", code: PAGE, closed: true })
expect(segs[3]).toMatchObject({ kind: "page", closed: false, code: "<p>half" })
// As text: the finished page is its one line; the unfinished one is the code block it is.
expect(textProjection(text)).toBe("Here:\n\n[page: Bakery landing]\n\nAnd code:\n\n```js\nconsole.log(1)\n```\n\n```html-view\n<p>half")
expect(pageNote("Bakery landing")).toBe("This answer has a page: Bakery landing")
})
test("a page is saved once, as written, for this user only, under the state directory", () => {
const id = `s-${Date.now()}`
const path = savePage(id, PAGE, "Bakery landing")
expect(path).toBe(join(pageDir(id), "1-bakery-landing.html"))
expect(path.startsWith(join(paths.state, "pages"))).toBe(true)
expect(readFileSync(path, "utf8")).toBe(PAGE)
expect(statSync(path).mode & 0o777).toBe(0o600)
expect(savePage(id, PAGE, "Another name")).toBe(path)
expect(savePage(id, "<title>Sales: Q3</title><p>x</p>", "")).toBe(join(pageDir(id), "2-sales-q3.html"))
expect(savePage(id, "<p>bare</p>", "")).toBe(join(pageDir(id), "3-page.html"))
expect(listPages(id).map((p) => p.n)).toEqual([1, 2, 3])
expect(slugOf("Čaj & káva: ráno")).toBe("čaj-káva-ráno")
})
test("in the TUI a finished page is the note saying what it is and where it was saved; /pages lists them", async () => {
const reply = "A page for you:\n\n```html-view Bakery landing\n" + PAGE + "\n```\n\nThat is the landing page."
t = await tui([{ chunks: [delta({ content: reply.slice(0, 40) }), delta({ content: reply.slice(40) })] }], { width: 140, height: 30 }, "", { store: true })
await t.input.typeText("make a page")
t.input.pressEnter()
expect(await t.until("That is the landing page.")).toBe(true)
const id = t.app.engine.sessionId!
const saved = listPages(id)
expect(saved).toHaveLength(1)
expect(saved[0]!.name).toBe("1-bakery-landing.html")
expect(readFileSync(saved[0]!.path, "utf8")).toBe(PAGE)
// The note in its place, not the source; the markdown around it as before.
expect(await t.until("This answer has a page: Bakery landing — saved to")).toBe(true)
expect(t.frame()).toContain("A page for you:")
expect(t.frame()).not.toContain("Fresh bread.")
await t.input.typeText("/pages")
t.input.pressEnter()
expect(await t.until(`1 ${saved[0]!.path}`.slice(0, 60))).toBe(true)
await t.input.typeText("/pages 2")
t.input.pressEnter()
expect(await t.until("no page 2 here")).toBe(true)
expect(existsSync(saved[0]!.path)).toBe(true)
// A terminal's own model is never told about pages.
expect(JSON.stringify(t.fake.requests[0].messages[0])).not.toContain("html-view")
})
test("the old `prototypes: true` setting is dropped with a line saying so, never an error", () => {
mkdirSync(paths.config, { recursive: true })
const file = join(paths.config, "config.yaml")
const before = existsSync(file) ? readFileSync(file, "utf8") : undefined
writeFileSync(file, "prototypes: true\n")
try {
const loaded = loadConfig()
expect(loaded.warnings.some((w) => w.includes("prototypes was removed"))).toBe(true)
expect((loaded.config as Record<string, unknown>).prototypes).toBeUndefined()
} finally {
if (before === undefined) writeFileSync(file, "")
else writeFileSync(file, before)
}
})
-81
View File
@@ -1,81 +0,0 @@
// Prototypes in the terminal (harness spec 1.1.0, blocks/prototypes.md): a completed
// `prototype-chat` / `prototype-page` fence is saved as a file under the state directory, the
// model's output as it is, and drawn as one line in its place; /prototype lists them. How the
// fence's info line is read is the conformance area `prototype` (tests/conformance.ts).
import { afterEach, expect, test } from "bun:test"
import { existsSync, readFileSync, statSync } from "node:fs"
import { join } from "node:path"
import { paths } from "../src/config/paths.ts"
import { parseInfo, splitPrototypes, titleFor } from "../src/prototype/fence.ts"
import { listPrototypes, prototypeDir, savePrototype, slugOf } from "../src/prototype/store.ts"
import { delta } from "./fake-provider.ts"
import { tui } from "./tui/harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
const PAGE = "<!doctype html>\n<title>Bakery</title>\n<p>Fresh bread.</p>"
test("the info line: the kind whatever its case, the title the rest of the line or the page's own", () => {
expect(parseInfo("prototype-chat Monthly sales")).toEqual({ kind: "chat", title: "Monthly sales" })
expect(parseInfo("Prototype-Page")).toEqual({ kind: "page", title: "" })
expect(parseInfo("prototype")).toEqual({ kind: "chat", title: "" })
expect(parseInfo("html")).toBeNull()
expect(titleFor("<title> <b>From</b>\n the page </title>", "")).toBe("From the page")
expect(titleFor(PAGE, "Given")).toBe("Given")
expect(titleFor("<p>none</p>", "")).toBe("")
})
test("a reply split: markdown as it is, a prototype fence closed or still streaming, other code blocks left alone", () => {
const text = "Here:\n\n```prototype-page Bakery landing\n" + PAGE + "\n```\n\nAnd code:\n\n```js\nconsole.log(1)\n```\n\n```prototype-chat Chart\n<p>half"
const segs = splitPrototypes(text)
expect(segs.map((s) => s.kind)).toEqual(["text", "prototype", "text", "prototype"])
expect(segs[1]).toMatchObject({ kind: "prototype", info: { kind: "page", title: "Bakery landing" }, code: PAGE, closed: true, start: 7 })
expect(segs[2]).toEqual({ kind: "text", text: "\nAnd code:\n\n```js\nconsole.log(1)\n```\n" })
expect(segs[3]).toMatchObject({ kind: "prototype", closed: false, code: "<p>half" })
// A fence that is a longer run of backticks, or tildes, closes only with its own; `~~~` inside
// a backtick fence is content.
const tilde = splitPrototypes("~~~prototype\n```\nnot a fence\n```\n~~~\n")
expect(tilde[0]).toMatchObject({ kind: "prototype", closed: true, code: "```\nnot a fence\n```" })
expect(splitPrototypes("plain text, no fence")).toEqual([{ kind: "text", text: "plain text, no fence" }])
})
test("saved under the state directory, numbered, slugged from the title, 0600, once per content", () => {
const id = "ses_proto_test"
const path = savePrototype(id, PAGE, { kind: "page", title: "Bakery landing" })
expect(path).toBe(join(prototypeDir(id), "1-bakery-landing.html"))
expect(path.startsWith(join(paths.state, "prototypes"))).toBe(true)
expect(readFileSync(path, "utf8")).toBe(PAGE)
expect(statSync(path).mode & 0o777).toBe(0o600)
// The same page again is the same file; a different one is the next number, named by its
// own <title> when the fence gave none, by its kind when neither says.
expect(savePrototype(id, PAGE, { kind: "page", title: "Bakery landing" })).toBe(path)
expect(savePrototype(id, "<title>Sales: Q3</title><p>x</p>", { kind: "chat", title: "" })).toBe(join(prototypeDir(id), "2-sales-q3.html"))
expect(savePrototype(id, "<p>bare</p>", { kind: "chat", title: "" })).toBe(join(prototypeDir(id), "3-chat.html"))
expect(listPrototypes(id).map((p) => p.name)).toEqual(["1-bakery-landing.html", "2-sales-q3.html", "3-chat.html"])
expect(slugOf("Čaj & káva: ráno", "chat")).toBe("čaj-káva-ráno")
})
test("in the TUI a completed prototype fence is one line saying where it was saved; /prototype lists them", async () => {
const reply = "A page for you:\n\n```prototype-page Bakery landing\n" + PAGE + "\n```\n\nThat is the landing page."
t = await tui([{ chunks: [delta({ content: reply.slice(0, 40) }), delta({ content: reply.slice(40) })] }], { width: 120, height: 30 }, "", { store: true })
await t.input.typeText("make a page")
t.input.pressEnter()
expect(await t.until("That is the landing page.")).toBe(true)
const id = t.app.engine.sessionId!
const saved = listPrototypes(id)
expect(saved).toHaveLength(1)
expect(saved[0]!.name).toBe("1-bakery-landing.html")
expect(readFileSync(saved[0]!.path, "utf8")).toBe(PAGE)
// Drawn as the one line, not as the code block; the markdown around it as before.
expect(await t.until("prototype · Bakery landing · saved to")).toBe(true)
expect(t.frame()).toContain("A page for you:")
expect(t.frame()).not.toContain("Fresh bread.")
await t.input.typeText("/prototype")
t.input.pressEnter()
expect(await t.until(`1 ${saved[0]!.path}`.slice(0, 60))).toBe(true)
await t.input.typeText("/prototype 2")
t.input.pressEnter()
expect(await t.until("no prototype 2 here")).toBe(true)
expect(existsSync(saved[0]!.path)).toBe(true)
})
+84
View File
@@ -12,6 +12,7 @@ import { paths } from "../src/config/paths.ts"
import { remoteState } from "../src/config/remote.ts"
import { setTrust } from "../src/project/root.ts"
import { remoteCommand } from "../src/remote.ts"
import { TOOL_SPECS } from "../src/harness.ts"
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
let fake: Fake | undefined
@@ -189,3 +190,86 @@ test("lembas remote scheduled on|off writes remote.scheduled, and --json says it
expect(remoteState().scheduled).toBe(false)
expect(remoteCommand(["scheduled", "maybe"], { out: () => {}, err: () => {} })).toBe(2)
})
// ---- Reports (harness spec 3.8.0, reports.md) ----
/** A tool result without the id every result carries (context.md). */
const bare = (text: string) => text.replace(/^\[#\d+\]\n/, "")
const toolNames = (i: number) => ((fake!.requests[i].tools ?? []) as { function: { name: string } }[]).map((t) => t.function.name)
const R = (extra: Record<string, unknown> = {}) => JSON.stringify({ title: "Disk almost full", body: "## What\n\n`/var` is at 94%.", summary: "The log partition is at 94%.", importance: "high", ...extra })
test("capability reports; a run that notifies is offered report_write, and the report it writes travels in the answer", async () => {
fake = fakeProvider([{ chunks: [toolCall(0, "c1", "report_write", R())] }, { chunks: [delta({ content: "Filed a report: the disk is almost full." })] }])
config(fake.url)
const root = project()
const { c, init, asked } = await client(limitsFor(root))
expect(init._meta.lembas.capabilities).toContain("reports")
const meta = { lembas: { scheduled: sched({ notify: "when" }) } }
const s: any = await c.request("session/new", { cwd: root, _meta: meta })
const r: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check the disks" }], _meta: { lembas: { turnId: "run7", ...meta.lembas } } })
expect(toolNames(0)).toContain("report_write")
// Allowed without asking: it writes nothing here.
expect(asked).toEqual([])
expect(r._meta.lembas.scheduled).toEqual({
run_id: "run7",
status: "ok",
text: "Filed a report: the disk is almost full.",
error: null,
report: { title: "Disk almost full", body: "## What\n\n`/var` is at 94%.", summary: "The log partition is at 94%.", importance: "high" },
})
// The model was told the report is filed and to end with one line.
expect(bare(fake.requests[1].messages.at(-1).content)).toBe(SCHEDULED.notify.result.filed)
})
test("one report per run: a second call replaces the first; the next run starts with none; the sentinel is no status any more", async () => {
fake = fakeProvider([
{ chunks: [toolCall(0, "c1", "report_write", R()), toolCall(1, "c2", "report_write", R({ title: "Disk fine again", importance: undefined }))] },
{ chunks: [delta({ content: "Done." })] },
{ chunks: [delta({ content: "Nothing needs attention.\n[SILENT]" })] },
])
config(fake.url)
const root = project()
const { c } = await client(limitsFor(root))
const meta = (run: string) => ({ lembas: { turnId: run, scheduled: sched({ run_id: run, notify: "always" }) } })
const s: any = await c.request("session/new", { cwd: root, _meta: meta("run7") })
const r1: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check" }], _meta: meta("run7") })
expect(r1._meta.lembas.scheduled.report).toMatchObject({ title: "Disk fine again", importance: "normal" })
const results = (fake.requests[1].messages as { role: string; content: string }[]).filter((m) => m.role === "tool").map((m) => bare(m.content))
expect(results).toEqual([SCHEDULED.notify.result.filed, SCHEDULED.notify.result.replaced])
// The schedule's next run, in the same session: no report of its own, so none in its answer —
// and `silent` is not a status for a turn whose request said notify.
const r2: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check" }], _meta: meta("run8") })
expect(r2._meta.lembas.scheduled.report).toBeUndefined()
expect(r2._meta.lembas.scheduled.status).toBe("ok")
})
test("notify never, and a server that says no notify at all: the tool is not in the list; the person's own turn in a run's session finds it unavailable", async () => {
fake = fakeProvider([
{ chunks: [delta({ content: "ok" })] },
{ chunks: [delta({ content: "ok" })] },
{ chunks: [delta({ content: "run" })] },
{ chunks: [toolCall(0, "c9", "report_write", R())] },
{ chunks: [delta({ content: "I cannot file one here." })] },
])
config(fake.url)
const root = project()
const { c } = await client(limitsFor(root))
const run = async (scheduled: Record<string, unknown>, id: string) => {
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas: { scheduled } } })
const r: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check" }], _meta: { lembas: { turnId: id, scheduled } } })
return { s, r }
}
await run(sched({ notify: "never" }), "a")
expect(toolNames(0)).not.toContain("report_write")
// A server before 3.8.0 sends no notify: as before, and the tool is not offered.
await run(sched(), "b")
expect(toolNames(1)).not.toContain("report_write")
// A run that notifies, then the person writes into its session: the list is the session's,
// and the tool answers the spec's unavailable text.
const { s } = await run(sched({ notify: "always" }), "c")
expect(toolNames(2)).toContain("report_write")
const mine: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "and file that for me" }] })
expect(toolNames(3)).toContain("report_write")
expect(bare(fake.requests[4].messages.at(-1).content)).toBe(TOOL_SPECS.report_write!.unavailable!)
expect(mine._meta.lembas.scheduled).toBeUndefined()
})