Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:32:15 +00:00
49 changed files with 4741 additions and 199 deletions

No files matched your search

+85
View File
@@ -4,6 +4,91 @@ All notable changes to LLeMbas CLI. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[Semantic Versioning](https://semver.org/).
## [2.0.0-beta.9] — 2026-11-12
Harness spec 3.7.0: one display in every client.
### Added
- **Harness spec 3.7.0: one display everywhere** (`harness/display.md`). The spec now says how
every client — the web UI, Desktop, the CLI, Android — shows a tool call: one short title made
from the call's arguments (the same in the transcript, on the progress line and over the link),
the four states running, done, failed and denied, how long a finished call took, `+added
−removed` for an edit, and the kinds of block. A reply that was stopped or failed keeps the
spec's line (`Stopped: by you`, `Failed: …`) on it. The approval, question and plan cards offer
the same actions everywhere, and numbers are written in the client's locale format.
- **Harness spec 3.7.0: `python` says why it could not run.** The server's `python` tool had one
answer for three situations; the spec now has one each — no page of the chat is open (and where
to open it), the page did not answer, the run took too long.
- **Paste placeholders in the prompt box.** A paste of three lines or more, or of more than 150
characters, shows as `[Pasted text 40 lines]` (or `[Pasted text 300 chars]`), and an image as
`[Image 1]`, `[Image 2]`…; what is sent is the text itself and the image. One backspace removes
a placeholder and what it stands for — cutting into one removes all of it; pasting the same
text again right after its placeholder opens it. The transcript shows the placeholder; prompt history, `/undo` and copying from the box
give the text in full. `paste: full` in the config (or `/settings`) shows pastes whole, as
before.
- **Images from the clipboard on macOS and Windows, and JPEG, WebP and GIF** besides PNG: ctrl+v
reads the clipboard through OpenTUI's host clipboard, with `wl-paste` / `xclip` behind it. It
no longer holds the screen while a clipboard answers, and says so when there is no image.
Pasted images are kept under the state directory and removed after a week.
- **Images over SSH.** A terminal cannot hand over the clipboard image of the machine you sit at,
so: an image pasted as text — a `data:image/png;base64,…` URL, or the base64 itself — is
recognised, saved and shown as `[Image N]`; with `ssh -X` the forwarded X clipboard is read; in
kitty, with `kitty_clipboard: true`, the terminal itself is asked for its clipboard (its
clipboard protocol, OSC 5522 — it asks you once). That one is off by default: on a connection
that stalls, part of the image can be lost on the way, and it is then refused with a line —
never saved broken, never typed into the box. And when nothing came through, one line names what works: the data URL, `@path` after
copying the file over, or attaching it to the same chat in the web, Desktop or Android app.
### Changed
- **The terminal opened from the web UI or Desktop picks a shell that exists.** `$SHELL` when
it is there, else bash, zsh or sh; on Windows PowerShell 7, then Windows PowerShell, then
`cmd.exe` — started without `-l`, which none of them takes. (The runtime's pseudo-terminal is
documented for Linux and macOS only, and there is no Windows build of the CLI yet: where a
terminal cannot be opened, the refusal now says so in a sentence.)
- **Tool calls are shown as spec 3.7.0 says.** A call has one title from its start to its end —
the command, the pattern, the path — the same in the transcript, on the progress line, in
`lembas run` and over the link (a `bash` call used to be titled by its description in the
transcript and by its command elsewhere; a `grep` by its directory on the progress line). After
the title come what the result adds (`+12 −3`, `exit 2`, `14 hits`, the lines read) and how long
it took; a denied call shows its reason and no time; a call cut off by a stop no longer stays
"running".
- **A reply that was stopped or failed says so on the reply**, in the spec's words — `Stopped: by
you`, `Stopped: step limit`, `Stopped: budget`, `Failed: …` — once, in place of the separate
"cancelled" notice and the raw error line; a session opened again from the store says it again.
- **One clock on the working line**: the phase's own (`Running bash: bun test · 12s`); once the
turn has gone on longer than the phase it reads `12s of 1m 05s`, instead of a second
`turn 1m 05s`.
- **`Waiting for subagents: N running` counts the subagents that are running** (it always said 1).
- **Numbers in your locale's format** (`LC_ALL`, `LC_NUMERIC`, `LANG`): token counts, rates, hits.
Durations stay as they are; with no locale set, English grouping as before.
- **Completing an `@file` or moving through the prompt box now counts columns as the box does**:
with a wide character (CJK, an emoji) before the cursor, the `@` list could replace the wrong
part of the line.
- **An approval card over the link names its tool** (`_meta.lembas.tool`); its title stays the
whole command, or the tool's name.
- **A duration just under a minute** is `1m 00s`, not `60.0s`.
- **A refused tool call reaches a plain ACP client** (an editor): it was sent as an update of a
call the client had never been told about, which a client drops; it is now announced as a failed
call, with its title and the reason.
- **Dictating into a box that holds a paste placeholder** keeps the placeholder.
- **Plainer refusals when a terminal or a folder cannot be used**: each says what to do —
`lembas remote terminal on`, `lembas remote add <dir>`, close one of the open terminals.
## [2.0.0-beta.8] — 2026-11-10
### Added
- **Harness spec 3.6.0: phone actions.** The spec now describes `phone_action`, the LLeMbas
server's tool for doing something on the person's phone when they write from the LLeMbas app on
it — alarms and timers, calendar events, SMS and email drafts, the dialer, routes (start one,
add a stop, search nearby, stop), opening an app or an address, media, the torch, settings
panels and automations — confirmed on the phone every time (`harness/phone.md`). The server's
alone: the CLI does not offer it, and its conformance area is the server's.
## [2.0.0-beta.7] — 2026-11-10
Harness spec 3.5.0: scheduled work on a linked computer.
+55 -3
View File
@@ -15,19 +15,21 @@ page *Harness-parity* in LLeMbas CLI's wiki.
|---|---|
| `VERSION` | The spec's own version, apart from LLeMbas CLI's |
| `purpose.json` | The `purpose` argument added to a tool whose calls say what they are for |
| `tools/<name>.json` | One tool each: name, `scope`, `sessions`, `risk`, `exclusive`, `block` (how a call is shown: `shell`, `edit`, `read`, `search`, `web`, `task`, `plan` — not drawn, the plan card refreshes — `hidden`, `tool`), `purpose`, former names (`aliases`, per project), renamed arguments, `variables`, what a project offers of the parameters (`narrow`, per project), `offered` (`subagent`: given to subagents only, never to the main agent — `report`, `team_finish`, `team_request`; `main`, spec 3.4.0: given to the main agent only, never to a subagent — `team_add`, `team_assign`, `team_replace`, `team_stop`, `team_decide`), `requires` and `unavailable` (when it can be offered, and what a call answers when that has gone), `confirm` (`always`: the person is asked in every mode), the description and the JSON Schema of its parameters — exactly what a model is sent |
| `tools/<name>.json` | One tool each: name, `scope`, `sessions`, `risk`, `exclusive`, `block` (how a call is shown: `shell`, `edit`, `read`, `search`, `web`, `task`, `plan` — not drawn, the plan card refreshes — `hidden`, `tool`), `purpose`, former names (`aliases`, per project), renamed arguments, `variables`, what a project offers of the parameters (`narrow`, per project), `offered` (`subagent`: given to subagents only, never to the main agent — `report`, `team_finish`, `team_request`; `main`, spec 3.4.0: given to the main agent only, never to a subagent — `team_add`, `team_assign`, `team_replace`, `team_stop`, `team_decide`), `requires` and `unavailable` (when it can be offered, and what a call answers when that has gone), `texts` (3.7.0: a tool's other fixed answers by key — `python`'s `no_answer` and `timeout`), `confirm` (`always`: the person is asked in every mode), the description and the JSON Schema of its parameters — exactly what a model is sent |
| `prompts/` | The prompt texts; `prompts/index.json` says which are shared, which LLeMbas fragment each one is, and what each `{{variable}}` in a text means. `prompts/personality/` holds the personality presets both offer |
| `permission/hardline.json` | The floor: commands refused in every mode, protected paths, and how a command is spelled plainly before it is checked again |
| `permission/arity.json` | How much of a command an "always allow" covers |
| `permission/defaults.json` | The rules every session starts from |
| `permission/modes.json` | The four modes — manual, edit, auto, plan — as what each does with each risk class |
| `models/schema.json` | Model metadata: context, output limit, efforts 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 |
| `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 |
| `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 |
| `display.md` | Display (3.7.0): one display in every client — a tool call's title, its four states, the duration and the facts beside it, the kinds of block; how `stopped` and `failed` stay on a finished reply; what the approval, question and plan cards offer; numbers in the client's locale |
| `quirks.json` | What real servers do, and how both harnesses cope |
| `conformance/<area>.json` | Cases with their expected results, run by both test suites |
| `acp.md` | The link between them: ACP plus every `_lembas/*` method, field and capability |
@@ -52,7 +54,8 @@ page *Harness-parity* in LLeMbas CLI's wiki.
`forge`: the session's view holds a repository mounted from a forge; `plan`: the session is in
plan mode; `team` (3.2.0): the session's team setting allows more than one agent, and a model could
serve as a subagent (3.3.0: `subagents.md` §4; before, the chat's model serving two requests at
once). A requirement that goes away between the offer and the call makes the call answer the
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
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.
@@ -71,6 +74,55 @@ 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.7.0
Written ahead of the implementations; the CLI carries it in the same round (`display.md`,
`loop.json` `display`).
- **One display in every client** (`display.md`). **A tool call has one short title**, made from
its arguments alone — `questions` and `patch` by what they name, else the first non-blank string
among `summary`, `command`, `code`, `pattern`, `query`, `url`, `path`, `file_path`, `from`,
`description`, `name`, `id`, `title`, `key`, `target`, `to`, `action`; first line, 80 characters
— and it is the same string in the transcript, as `running_tool`'s `what` and as the link's
`tool_call` title. **This fixes the order `what` is taken in**: before, both implementations
looked at `path` before `pattern` and `query`, so a `grep` was titled by its directory.
- **Four states** — `running`, `done`, `failed`, `denied` — told apart in every client; a finished
call shows **how long it took** (`0.4s`, `1m 05s`, `2h 03m`), a denied one never; an edit shows
**`+added −removed`**, counted from the diff **by its hunks** (a header without `a/` `b/` is
still a header; a removed line beginning `-- ` is still a line); a command its non-zero
`exit N`; a search its hits.
- **The blocks** every client distinguishes: `shell`, `edit`, `read`, `search`, `web`, `task`,
`tool`; `plan` and `hidden` are not drawn.
- **`stopped` and `failed` stay on the finished reply**: the progress text alone (`Stopped: by
you`, `Stopped: budget`, `Failed: …`) at the end of that reply, in every client, and again
wherever the reply is shown from what was stored. Nothing else says it twice.
- **The cards**: an approval offers Allow once / Always allow (where the request offers it) /
Deny / Deny, and say why; a question its options and always "Something else"; a plan Approve
with the mode to continue in, and Revise (`loop.json` `display.actions`).
- **Numbers in the client's locale format**; durations, ids, exit codes and line numbers never.
Conformance texts are in the plain format.
- **`python` says why it could not run** (`tools/python.json`): one text used to answer three
situations. `unavailable` is now only *no page of this chat is open* and says where to open
it; `texts.no_answer` — a page is open but did not answer; `texts.timeout` — the run passed
its `{{seconds}}`. Conformance area **`python`** (the server's).
- **The approval card keeps its own title** (`acp.md` `session/request_permission`): the whole
command, or the tool's name — not the short title — and `_meta.lembas.tool` names the tool.
- Conformance area **`display`** (titles, durations, hunk counts, facts, the end line, drawn
blocks); `progress` gains the `budget` stop.
## 3.6.0
- **Phone actions** (`phone.md`, `tools/phone_action.json`, `loop.json` `phone`): a chat's model
may do something on the person's phone when they write from the LLeMbas app on it — an alarm or a
timer, a calendar event, an SMS or email draft, the dialer, a route (`navigate`, `add_stop`,
`search_nearby`, `stop_navigation`), an app or an address, media, the torch, a settings panel,
an automation. The app declares the capability `phone_actions` with each message; the person
confirms every call on the phone (`confirm: always`); the result is `done`, `declined` or
`failed` with what the phone said. The server's alone (`scope: llembas`, `sessions: chat`); new
requirement `phone`, offered once a message came from the phone and kept, answering
`unavailable` when the message being answered did not. Conformance area **`phone`** (the checks
and the result texts).
## 3.5.0
Written ahead of both implementations; the server vendors it as written, both carry it in the same
+1 -1
View File
@@ -1 +1 @@
3.5.0
3.7.0
+17 -2
View File
@@ -219,7 +219,18 @@ Params: `{ sessionId }`. Stops the running turn.
`{ sessionId, update }` with `sessionUpdate` one of `agent_message_chunk`, `agent_thought_chunk`,
`tool_call`, `tool_call_update`, `plan` (below), `current_mode_update`, and
`available_commands_update` (capability `commands`):
`available_commands_update` (capability `commands`).
From spec 3.7.0 a `tool_call`'s `title` is **the call's short title** (`display.md` §1) — the
tool's name where the call has none — and no `tool_call_update` changes it: `completed` is the
state `done`, `failed` is `failed`, and a call that was refused — it never started, so nothing
announced it — is one `tool_call` with status `failed`, `_meta.lembas.denied: true` and the reason
as its content (the state `denied`). The same title is
`title` on the `tool_start` event of `_lembas/event` and `what` of `running_tool`; `tool_end`
carries `ms`, the call's duration, and `tool_denied` its `reason`. A client of `_lembas/event`
that is given no `title` (a device before 3.7.0) makes it from `args` by the same rule.
`available_commands_update`:
```json
{ "sessionUpdate": "available_commands_update",
@@ -247,7 +258,11 @@ named like any TUI command is not a command (the built-in wins in the TUI).
An approval card. Params: ACP's `{ sessionId, toolCall: { toolCallId, title, kind, status: "pending", rawInput, content? }, options }`
with options `once` (allow_once), `session` (allow_always, absent where "always" is never offered)
and `deny` (reject_once), and `_meta.lembas: { reason, purpose?, always?, patient?, job? }`. `patient`: a
and `deny` (reject_once), and `_meta.lembas: { tool, reason, purpose?, always?, patient?, job? }`. `tool`
(spec 3.7.0): the tool's name — `toolCall.title` here is **the whole command, or the tool's name where
the call has no command**, as before 3.7.0 (a card is read before it is answered; the call's short
title of `display.md` §1 is `tool_call`'s, not the card's), so a client that titles a card by the
command still has the tool to name. `patient`: a
person may also answer at the terminal (a shared session), so the client does not time it out.
`job` (capability `jobs`): `{ id, agent, description }` when a subagent running as a background job asks, so the card
can say which — a background subagent may ask while the session itself is idle. `subagent` (capability `tree`, spec 3.4.0):
+684
View File
@@ -0,0 +1,684 @@
{
"about": "Display (display.md, spec 3.7.0), in the plain number format. `show` says what is asked. `title`: a call's `args` (and its `tool`, for the reader) — expect `title`, the one short title (display.md §1), or null where the call has none. `duration`: a call's `state` and `ms` — expect `duration` as drawn beside the title (§2), or null. `change`: a unified `diff` — expect `added`, `removed` counted by its hunks, and `text` (loop.json display.change). `facts`: a finished call's `block` with its `diff`, `exit` or `hits` — expect `facts`, the texts after the title in order. `end`: a turn's last `progress` (or null) — expect `line`, the line that stays on the finished reply (§4), or null. `drawn`: a `block` — whether it is drawn as a call (§3). LLeMbas: services/display.py; CLI: session/display.ts.",
"cases": [
{
"about": "A command is its own title.",
"show": "title",
"tool": "bash",
"args": {
"command": "bun test",
"description": "Run the tests"
},
"expect": {
"title": "bun test"
}
},
{
"about": "Only the first line of a command.",
"show": "title",
"tool": "bash",
"args": {
"command": " cd src &&\n make "
},
"expect": {
"title": "cd src &&"
}
},
{
"about": "A search is titled by its pattern, not where it looks.",
"show": "title",
"tool": "grep",
"args": {
"pattern": "TODO\\(",
"path": "src"
},
"expect": {
"title": "TODO\\("
}
},
{
"about": "A file search likewise.",
"show": "title",
"tool": "glob",
"args": {
"pattern": "**/*.ts",
"path": "src/tui"
},
"expect": {
"title": "**/*.ts"
}
},
{
"about": "A read by its path.",
"show": "title",
"tool": "read",
"args": {
"path": "src/app.ts",
"offset": 120
},
"expect": {
"title": "src/app.ts"
}
},
{
"about": "A listing with no path has no title.",
"show": "title",
"tool": "list",
"args": {
"depth": 2
},
"expect": {
"title": null
}
},
{
"about": "An edit by its path.",
"show": "title",
"tool": "edit",
"args": {
"path": "README.md",
"old": "a",
"new": "b"
},
"expect": {
"title": "README.md"
}
},
{
"about": "A web search by its query.",
"show": "title",
"tool": "web_search",
"args": {
"query": "opentui extmarks",
"max_results": 5
},
"expect": {
"title": "opentui extmarks"
}
},
{
"about": "A fetch by its address.",
"show": "title",
"tool": "web_fetch",
"args": {
"url": "https://example.org/docs"
},
"expect": {
"title": "https://example.org/docs"
}
},
{
"about": "A task by its description, not its prompt.",
"show": "title",
"tool": "task",
"args": {
"description": "Find the callers",
"prompt": "Look through src/ for every caller of load() and list them."
},
"expect": {
"title": "Find the callers"
}
},
{
"about": "A subagent by its name.",
"show": "title",
"tool": "team_add",
"args": {
"name": "Reviewer",
"role": "reviews the change",
"task": "Read the diff."
},
"expect": {
"title": "Reviewer"
}
},
{
"about": "A phone action by its summary, whatever else it carries.",
"show": "title",
"tool": "phone_action",
"args": {
"action": "open_url",
"summary": "Open the timetable",
"url": "https://example.org/t"
},
"expect": {
"title": "Open the timetable"
}
},
{
"about": "Python by the first line of its code.",
"show": "title",
"tool": "python",
"args": {
"code": "import math\nprint(math.pi)"
},
"expect": {
"title": "import math"
}
},
{
"about": "A question by its headers.",
"show": "title",
"tool": "ask_user",
"args": {
"why": "The schema is open.",
"questions": [
{
"header": "Database",
"question": "Which one?",
"options": []
},
{
"header": "Cache",
"question": "Which cache?",
"options": []
}
]
},
"expect": {
"title": "Database · Cache"
}
},
{
"about": "A patch by the files it names.",
"show": "title",
"tool": "apply_patch",
"args": {
"patch": "*** Begin Patch\n*** Update File: src/a.ts\n@@\n-x\n+y\n*** Add File: docs/b.md\n+hello\n*** Delete File: old.txt\n*** End Patch"
},
"expect": {
"title": "src/a.ts, docs/b.md, old.txt"
}
},
{
"about": "A unified diff as a patch: the +++ paths, without b/ and without /dev/null.",
"show": "title",
"tool": "apply_patch",
"args": {
"patch": "--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1 +1 @@\n-x\n+y\n--- a/gone.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-bye\n"
},
"expect": {
"title": "src/a.ts"
}
},
{
"about": "A patch that names nothing falls back to its path.",
"show": "title",
"tool": "apply_patch",
"args": {
"patch": "@@ -1 +1 @@\n-x\n+y\n",
"path": "src/a.ts"
},
"expect": {
"title": "src/a.ts"
}
},
{
"about": "Cut to 80 characters: 79 and an ellipsis.",
"show": "title",
"tool": "bash",
"args": {
"command": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
"expect": {
"title": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…"
}
},
{
"about": "Exactly 80 is not cut.",
"show": "title",
"tool": "bash",
"args": {
"command": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
},
"expect": {
"title": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
}
},
{
"about": "Counted in code points, not UTF-16 units.",
"show": "title",
"tool": "bash",
"args": {
"command": "echo 🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂"
},
"expect": {
"title": "echo 🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂…"
}
},
{
"about": "A blank argument is passed over.",
"show": "title",
"tool": "grep",
"args": {
"pattern": " ",
"path": "src"
},
"expect": {
"title": "src"
}
},
{
"about": "An argument that is not a string is passed over.",
"show": "title",
"tool": "job_output",
"args": {
"id": "job3",
"wait": 30
},
"expect": {
"title": "job3"
}
},
{
"about": "A setting by its key.",
"show": "title",
"tool": "settings",
"args": {
"action": "set",
"key": "theme",
"value": "moria"
},
"expect": {
"title": "theme"
}
},
{
"about": "Only an action.",
"show": "title",
"tool": "tasks",
"args": {
"action": "list"
},
"expect": {
"title": "list"
}
},
{
"about": "No arguments, no title.",
"show": "title",
"tool": "job_list",
"args": {},
"expect": {
"title": null
}
},
{
"about": "Arguments that are not an object, no title.",
"show": "title",
"tool": "read",
"args": "src/app.ts",
"expect": {
"title": null
}
},
{
"about": "A finished call: tenths under a minute.",
"show": "duration",
"state": "done",
"ms": 412,
"expect": {
"duration": "0.4s"
}
},
{
"about": "Seconds.",
"show": "duration",
"state": "done",
"ms": 8449,
"expect": {
"duration": "8.4s"
}
},
{
"about": "Just under a minute.",
"show": "duration",
"state": "failed",
"ms": 59940,
"expect": {
"duration": "59.9s"
}
},
{
"about": "What would round to 60.0s is a minute.",
"show": "duration",
"state": "done",
"ms": 59960,
"expect": {
"duration": "1m 00s"
}
},
{
"about": "The last tenth under a minute.",
"show": "duration",
"state": "done",
"ms": 59949,
"expect": {
"duration": "59.9s"
}
},
{
"about": "From a minute: minutes and whole seconds.",
"show": "duration",
"state": "done",
"ms": 65000,
"expect": {
"duration": "1m 05s"
}
},
{
"about": "From an hour: hours and minutes.",
"show": "duration",
"state": "done",
"ms": 7380000,
"expect": {
"duration": "2h 03m"
}
},
{
"about": "A failed call shows how long it took.",
"show": "duration",
"state": "failed",
"ms": 1200,
"expect": {
"duration": "1.2s"
}
},
{
"about": "A denied call shows none.",
"show": "duration",
"state": "denied",
"ms": 3,
"expect": {
"duration": null
}
},
{
"about": "A running call shows none.",
"show": "duration",
"state": "running",
"ms": 5000,
"expect": {
"duration": null
}
},
{
"about": "A stored call whose time was not kept shows none.",
"show": "duration",
"state": "done",
"expect": {
"duration": null
}
},
{
"about": "One line changed.",
"show": "change",
"diff": "--- a/a.txt\n+++ b/a.txt\n@@ -1,3 +1,3 @@\n one\n-two\n+2\n three\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "Headers without a/ and b/ are still headers.",
"show": "change",
"diff": "Index: a.txt\n===================================================================\n--- a.txt\n+++ a.txt\n@@ -1,2 +1,3 @@\n one\n+one and a half\n two\n",
"expect": {
"added": 1,
"removed": 0,
"text": "+1 −0"
}
},
{
"about": "A removed line that begins with `-- ` and an added one that begins with `++ ` are lines, not headers.",
"show": "change",
"diff": "--- a/q.sql\n+++ b/q.sql\n@@ -1,3 +1,3 @@\n select 1;\n--- the old comment\n+++ the new one\n select 2;\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "A new file.",
"show": "change",
"diff": "--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n",
"expect": {
"added": 2,
"removed": 0,
"text": "+2 −0"
}
},
{
"about": "A hunk header without counts means one line each.",
"show": "change",
"diff": "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "No newline at end of file counts for nothing.",
"show": "change",
"diff": "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n\\ No newline at end of file\n+b\n\\ No newline at end of file\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "Two files add up.",
"show": "change",
"diff": "diff --git a/a b/a\n--- a/a\n+++ b/a\n@@ -1 +1,2 @@\n a\n+b\ndiff --git a/c b/c\n--- a/c\n+++ b/c\n@@ -1,2 +1 @@\n c\n-d\n",
"expect": {
"added": 1,
"removed": 1,
"text": "+1 −1"
}
},
{
"about": "No diff, nothing changed.",
"show": "change",
"diff": "",
"expect": {
"added": 0,
"removed": 0,
"text": "+0 −0"
}
},
{
"about": "An edit shows its change.",
"show": "facts",
"block": "edit",
"diff": "--- a/x\n+++ b/x\n@@ -1 +1,2 @@\n-a\n+b\n+c\n",
"expect": {
"facts": [
"+2 −1"
]
}
},
{
"about": "A command that failed shows its exit code.",
"show": "facts",
"block": "shell",
"exit": 2,
"expect": {
"facts": [
"exit 2"
]
}
},
{
"about": "A command that succeeded shows none.",
"show": "facts",
"block": "shell",
"exit": 0,
"expect": {
"facts": []
}
},
{
"about": "A search shows its hits.",
"show": "facts",
"block": "search",
"hits": 14,
"expect": {
"facts": [
"14 hits"
]
}
},
{
"about": "One hit.",
"show": "facts",
"block": "search",
"hits": 1,
"expect": {
"facts": [
"1 hit"
]
}
},
{
"about": "No hits is a fact too.",
"show": "facts",
"block": "search",
"hits": 0,
"expect": {
"facts": [
"0 hits"
]
}
},
{
"about": "A read has none of these.",
"show": "facts",
"block": "read",
"hits": 3,
"exit": 1,
"expect": {
"facts": []
}
},
{
"about": "Stopped by the person: the line stays on the reply.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "person"
},
"now": 1762790460000,
"expect": {
"line": "Stopped: by you"
}
},
{
"about": "The budget ran out.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "budget"
},
"now": 1762790460000,
"expect": {
"line": "Stopped: budget"
}
},
{
"about": "The step limit.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "steps"
},
"now": 1762790460000,
"expect": {
"line": "Stopped: step limit"
}
},
{
"about": "Stopped, no reason known.",
"show": "end",
"progress": {
"phase": "stopped",
"since": 1762790400000
},
"now": 1762790460000,
"expect": {
"line": "Stopped"
}
},
{
"about": "Failed, with the error.",
"show": "end",
"progress": {
"phase": "failed",
"since": 1762790400000,
"reason": "502 Bad Gateway"
},
"now": 1762790460000,
"expect": {
"line": "Failed: 502 Bad Gateway"
}
},
{
"about": "A reply that finished shows nothing.",
"show": "end",
"progress": null,
"now": 1762790460000,
"expect": {
"line": null
}
},
{
"about": "A phase that is not an end shows nothing on the reply.",
"show": "end",
"progress": {
"phase": "writing",
"since": 1762790400000
},
"now": 1762790460000,
"expect": {
"line": null
}
},
{
"about": "A plan change is not drawn as a call.",
"show": "drawn",
"block": "plan",
"expect": {
"drawn": false
}
},
{
"about": "Nor a hidden tool.",
"show": "drawn",
"block": "hidden",
"expect": {
"drawn": false
}
},
{
"about": "A command is.",
"show": "drawn",
"block": "shell",
"expect": {
"drawn": true
}
},
{
"about": "A tool nobody knows is the generic block.",
"show": "drawn",
"expect": {
"drawn": true
}
}
]
}
+595
View File
@@ -0,0 +1,595 @@
{
"about": "Spec 3.6.0 (phone.md §2-§3): `check` — a phone_action call's arguments, and either the action the phone is sent (`action`: its own fields only, strings trimmed, `summary` the action's name when empty) or the call's refusal (`refused`, loop.json phone.texts); `result` — the phone's answer (`status`, `message`; `status` null is no answer in time) as the text the model is told. LLeMbas only: the CLI has no runner for this area.",
"cases": [
{
"about": "A known action, its fields only: a stray field is dropped and strings are trimmed.",
"kind": "check",
"args": {
"action": "alarm",
"summary": " Alarm at 7:00 on weekdays ",
"time": "07:00",
"days": [
"mon",
"tue",
"wed",
"thu",
"fri"
],
"label": " Work ",
"seconds": 60
},
"expect": {
"action": {
"action": "alarm",
"summary": "Alarm at 7:00 on weekdays",
"time": "07:00",
"days": [
"mon",
"tue",
"wed",
"thu",
"fri"
],
"label": "Work"
}
}
},
{
"about": "No summary: the action's name stands in.",
"kind": "check",
"args": {
"action": "torch",
"on": false
},
"expect": {
"action": {
"action": "torch",
"summary": "torch",
"on": false
}
}
},
{
"about": "An action that is not one.",
"kind": "check",
"args": {
"action": "call",
"summary": "Call mum",
"number": "+421 900 123 456"
},
"expect": {
"refused": "\"call\" is not an action. Use one of: alarm, timer, calendar_event, sms_draft, email_draft, dial, navigate, add_stop, search_nearby, stop_navigation, open_app, open_url, media, torch, settings_panel, automation_intent. Nothing was sent to the phone."
}
},
{
"about": "A required field missing.",
"kind": "check",
"args": {
"action": "timer",
"summary": "Tea"
},
"expect": {
"refused": "timer needs seconds. Nothing was sent to the phone."
}
},
{
"about": "Both of add_stop's missing: all of them, in order, in one sentence.",
"kind": "check",
"args": {
"action": "add_stop",
"summary": "Add a stop"
},
"expect": {
"refused": "add_stop needs stop and destination. Nothing was sent to the phone."
}
},
{
"about": "A group: an SMS draft needs a recipient or a text.",
"kind": "check",
"args": {
"action": "sms_draft",
"summary": "Text"
},
"expect": {
"refused": "sms_draft needs to or body. Nothing was sent to the phone."
}
},
{
"about": "A group met by one of its fields.",
"kind": "check",
"args": {
"action": "sms_draft",
"summary": "Text Jana",
"to": [
"Jana"
]
},
"expect": {
"action": {
"action": "sms_draft",
"summary": "Text Jana",
"to": [
"Jana"
]
}
}
},
{
"about": "An empty string is missing, whitespace included.",
"kind": "check",
"args": {
"action": "open_app",
"summary": "Open",
"app": " "
},
"expect": {
"refused": "open_app needs app. Nothing was sent to the phone."
}
},
{
"about": "A time out of range.",
"kind": "check",
"args": {
"action": "alarm",
"summary": "Alarm",
"time": "24:00"
},
"expect": {
"refused": "time is not a time as HH:MM (24-hour). Nothing was sent to the phone."
}
},
{
"about": "A timer of zero seconds.",
"kind": "check",
"args": {
"action": "timer",
"summary": "Timer",
"seconds": 0
},
"expect": {
"refused": "seconds is not a whole number of seconds from 1 to 86400. Nothing was sent to the phone."
}
},
{
"about": "A boolean is not a number of seconds.",
"kind": "check",
"args": {
"action": "timer",
"summary": "Timer",
"seconds": true
},
"expect": {
"refused": "seconds is not a whole number of seconds from 1 to 86400. Nothing was sent to the phone."
}
},
{
"about": "A calendar event with a date for a whole day.",
"kind": "check",
"args": {
"action": "calendar_event",
"summary": "Holiday",
"title": "Holiday",
"start": "2026-12-24",
"all_day": true
},
"expect": {
"action": {
"action": "calendar_event",
"summary": "Holiday",
"title": "Holiday",
"start": "2026-12-24",
"all_day": true
}
}
},
{
"about": "A start that is not a date.",
"kind": "check",
"args": {
"action": "calendar_event",
"summary": "Meet",
"title": "Meet",
"start": "tomorrow at 3"
},
"expect": {
"refused": "start is not a date and time as YYYY-MM-DDTHH:MM, or a date as YYYY-MM-DD for a whole day. Nothing was sent to the phone."
}
},
{
"about": "A number with too few digits.",
"kind": "check",
"args": {
"action": "dial",
"summary": "Dial",
"number": "12"
},
"expect": {
"refused": "number is not a phone number. Nothing was sent to the phone."
}
},
{
"about": "A number with letters in it.",
"kind": "check",
"args": {
"action": "dial",
"summary": "Dial",
"number": "0900 ABC"
},
"expect": {
"refused": "number is not a phone number. Nothing was sent to the phone."
}
},
{
"about": "A web address that is not http or https.",
"kind": "check",
"args": {
"action": "open_url",
"summary": "Open",
"url": "javascript:alert(1)"
},
"expect": {
"refused": "url is not an http or https address. Nothing was sent to the phone."
}
},
{
"about": "A web address in capitals is still one.",
"kind": "check",
"args": {
"action": "open_url",
"summary": "Open",
"url": "HTTPS://example.org/"
},
"expect": {
"action": {
"action": "open_url",
"summary": "Open",
"url": "HTTPS://example.org/"
}
}
},
{
"about": "A route: a destination, stops in order, a mode.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Drive home via the shop",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Shop",
"lat": 48.89,
"lon": 18.04
}
],
"mode": "drive"
},
"expect": {
"action": {
"action": "navigate",
"summary": "Drive home via the shop",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Shop",
"lat": 48.89,
"lon": 18.04
}
],
"mode": "drive"
}
}
},
{
"about": "A destination with coordinates out of range and nothing else is not a place.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Go",
"destination": {
"lat": 95,
"lon": 18
}
},
"expect": {
"refused": "destination is not a place: lat and lon together, or a query, or a name. Nothing was sent to the phone."
}
},
{
"about": "A stop that is not a place, inside the list.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Go",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Shop"
},
{}
]
},
"expect": {
"refused": "stops is not a list of places, each lat and lon together, or a query, or a name. Nothing was sent to the phone."
}
},
{
"about": "add_stop with its destination, as the person told it.",
"kind": "check",
"args": {
"action": "add_stop",
"summary": "Add the petrol station",
"stop": {
"query": "Fuel station, Bywater"
},
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
}
},
"expect": {
"action": {
"action": "add_stop",
"summary": "Add the petrol station",
"stop": {
"query": "Fuel station, Bywater"
},
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
}
}
}
},
{
"about": "A mode the schema does not have.",
"kind": "check",
"args": {
"action": "navigate",
"summary": "Go",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"mode": "fly"
},
"expect": {
"refused": "mode is not one of drive, walk, bike, transit. Nothing was sent to the phone."
}
},
{
"about": "search_nearby along the route.",
"kind": "check",
"args": {
"action": "search_nearby",
"summary": "Petrol on the way",
"query": "petrol station",
"near": "route"
},
"expect": {
"action": {
"action": "search_nearby",
"summary": "Petrol on the way",
"query": "petrol station",
"near": "route"
}
}
},
{
"about": "stop_navigation needs nothing.",
"kind": "check",
"args": {
"action": "stop_navigation",
"summary": "Stop the route"
},
"expect": {
"action": {
"action": "stop_navigation",
"summary": "Stop the route"
}
}
},
{
"about": "The checks run in the spec's order: time is reported before days.",
"kind": "check",
"args": {
"action": "alarm",
"summary": "Alarm",
"time": "7",
"days": [
"monday"
]
},
"expect": {
"refused": "time is not a time as HH:MM (24-hour). Nothing was sent to the phone."
}
},
{
"about": "A field another action reads is not checked here.",
"kind": "check",
"args": {
"action": "media",
"summary": "Pause",
"command": "pause",
"url": "nope"
},
"expect": {
"action": {
"action": "media",
"summary": "Pause",
"command": "pause"
}
}
},
{
"about": "An automation with its values.",
"kind": "check",
"args": {
"action": "automation_intent",
"summary": "Run Arrive home",
"task": "Arrive home",
"values": {
"lights": "on"
}
},
"expect": {
"action": {
"action": "automation_intent",
"summary": "Run Arrive home",
"task": "Arrive home",
"values": {
"lights": "on"
}
}
}
},
{
"about": "Values must be text.",
"kind": "check",
"args": {
"action": "automation_intent",
"summary": "Run",
"task": "x",
"values": {
"n": 1
}
},
"expect": {
"refused": "values is not named text values. Nothing was sent to the phone."
}
},
{
"about": "An email draft with a list of recipients.",
"kind": "check",
"args": {
"action": "email_draft",
"summary": "Email",
"to": [
"a@example.org"
],
"subject": "Hi"
},
"expect": {
"action": {
"action": "email_draft",
"summary": "Email",
"to": [
"a@example.org"
],
"subject": "Hi"
}
}
},
{
"about": "A recipient list holding an empty name.",
"kind": "check",
"args": {
"action": "email_draft",
"summary": "Email",
"to": [
"a@example.org",
""
],
"subject": "Hi"
},
"expect": {
"refused": "to is not a list of recipients. Nothing was sent to the phone."
}
},
{
"about": "torch: on must be a boolean.",
"kind": "check",
"args": {
"action": "torch",
"summary": "Torch",
"on": "yes"
},
"expect": {
"refused": "on is not true or false. Nothing was sent to the phone."
}
},
{
"about": "A panel the schema does not have.",
"kind": "check",
"args": {
"action": "settings_panel",
"summary": "Open",
"panel": "battery"
},
"expect": {
"refused": "panel is not one of wifi, bluetooth, internet, volume, nfc, location, do_not_disturb. Nothing was sent to the phone."
}
},
{
"about": "Done, with nothing said.",
"kind": "result",
"status": "done",
"message": "",
"expect": "Done on the phone."
},
{
"about": "Done, with what the phone said.",
"kind": "result",
"status": "done",
"message": "Alarm set for 07:00, weekdays.",
"expect": "Done on the phone.\n\nThe phone says: Alarm set for 07:00, weekdays."
},
{
"about": "Declined.",
"kind": "result",
"status": "declined",
"message": "",
"expect": "The person declined it on the phone: nothing was done. Do not try again unless they ask."
},
{
"about": "Declined, with the person's words.",
"kind": "result",
"status": "declined",
"message": "Not now.",
"expect": "The person declined it on the phone: nothing was done. Do not try again unless they ask.\n\nThe phone says: Not now."
},
{
"about": "Failed, with why.",
"kind": "result",
"status": "failed",
"message": "OsmAnd is not installed.",
"expect": "The phone could not do it: nothing was done.\n\nThe phone says: OsmAnd is not installed."
},
{
"about": "A status the phone does not know is failed.",
"kind": "result",
"status": "maybe",
"message": "?",
"expect": "The phone could not do it: nothing was done.\n\nThe phone says: ?"
},
{
"about": "A message is trimmed.",
"kind": "result",
"status": "done",
"message": " Torch on. \n",
"expect": "Done on the phone.\n\nThe phone says: Torch on."
},
{
"about": "No answer in time.",
"kind": "result",
"status": null,
"message": "",
"expect": "The phone did not answer in time: nothing was done."
},
{
"about": "A message is cut at message_max_chars.",
"kind": "result",
"status": "failed",
"message": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"expect": "The phone could not do it: nothing was done.\n\nThe phone says: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
]
}
+13
View File
@@ -316,6 +316,19 @@
"line": "Stopped: step limit"
}
},
{
"about": "Stopped when the budget ran out.",
"progress": {
"phase": "stopped",
"since": 1762790400000,
"reason": "budget"
},
"now": 1762790400000,
"expect": {
"text": "Stopped: budget",
"line": "Stopped: budget"
}
},
{
"about": "Failed.",
"progress": {
+27
View File
@@ -0,0 +1,27 @@
{
"about": "Spec 3.7.0: what a `python` call answers when it could not run, word for word (tools/python.json). `situation`: `no_page` — no page of this chat is open in the web or desktop app (the tool's `unavailable`); `no_answer` — a page is open and attached but did not answer the run request; `timeout` — the run began and passed the call's limit of `seconds` (texts.timeout, `{{seconds}}` filled). Three situations, three texts: never one for another. The server's alone (scope llembas).",
"cases": [
{
"about": "No page of this chat is open anywhere.",
"situation": "no_page",
"expect": {
"text": "Python cannot run now: no page of this chat is open. Python runs in the person's browser — ask them to open this chat in the LLeMbas web or desktop app and keep it open, then call python again."
}
},
{
"about": "A page is attached but does not answer.",
"situation": "no_answer",
"expect": {
"text": "Python did not run: a page of this chat is open, but it did not answer. It may still be loading Python, or be asleep in a background tab — ask the person to bring this chat to the front (or reload it), then call python again."
}
},
{
"about": "The run passed its time limit.",
"situation": "timeout",
"seconds": 30,
"expect": {
"text": "Python stopped: the run took longer than 30 seconds, and nothing it wrote was saved. Do less in one call, or split the work over several calls."
}
}
]
}
+171
View File
@@ -0,0 +1,171 @@
# Display
Spec 3.7.0. **One display in every client** — the web UI, Desktop, the CLI, Android — for the
things every one of them draws: a tool call, the end of a reply that did not finish, the card that
waits for the person, and a number. `progress.md` says what a session is doing *now*; this says
what stays on the screen afterwards. The data is `loop.json` `display`; the cases
`conformance/display.json`.
Each client keeps its own look — a terminal row, a card, a chip — and its own translation of the
fixed words. What is the same is **what is said, from which data, in which state**.
## 1. A tool call's title
One rule, and one title per call: **the call's short title** — the same string in the transcript,
as `what` of `running_tool` (`progress.md` §2) and as `title` of the link's `tool_call`
(`acp.md`). It is made from the call's arguments alone, so it is known the moment the call starts
and never changes afterwards:
1. `questions` (a list, `ask_user`): its `header`s, joined with ` · `.
2. `patch` (a string, `apply_patch`): the files it names — every `*** Add File: `,
`*** Update File: ` and `*** Delete File: ` line's path, else every `+++ ` line's path without
a leading `b/` (`/dev/null` left out) — joined with `, `.
3. Otherwise the first of these arguments that is a string with anything but white space in it,
in this order (`display.title.keys`): `summary`, `command`, `code`, `pattern`, `query`, `url`,
`path`, `file_path`, `from`, `description`, `name`, `id`, `title`, `key`, `target`, `to`,
`action`.
4. Then: trimmed, **its first line only**, trimmed again, and cut to **80 characters**
(`progress.what_max`) — 79 and `…` — counted in code points.
A call with none of these has **no title**: the client draws the tool's name alone, and
`running_tool` goes without `what`.
The order puts what a call *does* before where: a `grep` is titled by its pattern, not its
directory; a `bash` by its command, not its description; `phone_action` by its `summary`. The
tool's own name (or the client's label for it — `Bash`, `Search files`; a client's own table) is
drawn beside the title and is not part of it.
The short title is for a call **as it is listed**. The approval card (§5) is not titled by it: a
card shows what is asked in full — the whole command, the change — and names the tool
(`acp.md` `session/request_permission`: `toolCall.title` the whole command or the tool's name,
`_meta.lembas.tool` the tool).
A tool the spec marks `block: plan` or `block: hidden` is not drawn as a call at all (§3).
## 2. A call's states
A drawn call is in exactly one of four states (`display.states`), and every client tells the four
apart at a glance — by a mark, a colour or a word of its own; never by the title, which is the
same in all four:
| State | When | What is shown beside the title |
|---|---|---|
| `running` | from the call's start until its result | a mark that it is running (a spinner, `…`); no duration is required — a client that shows one counts it from the call's start, as `progress.md` §3 writes elapsed time |
| `done` | its result came and is not an error | **how long it took** (below) |
| `failed` | its result is an error — the tool's own failure, a non-zero exit a tool reports as one, a timeout | how long it took, and the **first line of the error** where there is room |
| `denied` | it was not run: the person, a rule, the mode or the hardline refused it | **no duration**; the first line of the reason where there is room |
A call that was `running` when its turn was stopped, or whose result never came (the session
ended, the device went away), is drawn `failed` once that is known — never left spinning.
**The duration** of a finished call is the time from its start to its result, as the
implementation that ran it measured it, written the one way (`display.duration`): under a minute
in seconds with one decimal (`0.4s`, `8.4s`) — a time that would round to `60.0s` is a minute,
`1m 00s`; from a minute `1m 05s`; from an hour `2h 03m` —
`progress.md`'s elapsed form with tenths under a minute. A duration is not a locale number (§6):
it is written with `.` everywhere. A stored call whose duration was not kept shows none.
**Facts from the result** (`display.facts`) go after the title, never in its place:
- **an edit** (`block: edit`) shows **`+{{added}} −{{removed}}`** (`display.change`; the minus is
U+2212) once its change is known: the lines its diff adds and removes. Counted from the unified
diff by its hunks — after each `@@ -a,b +c,d @@` header, the next lines that begin with `+`, `-`
or a space until `b` old lines and `d` new lines are used up (`\ No newline at end of file` counts
for nothing; a missing `,b` or `,d` is 1); a `+` there is one added, a `-` one removed. Nothing
outside a hunk is counted, so a file header never is and a removed line that itself begins with
`-- ` always is. Several files in one diff add up.
- **a command** (`block: shell`) shows **`exit {{code}}`** (`display.exit`) when its exit code is
known and not 0.
- **a search** (`block: search`) shows **`{{count}} hits`** (`display.hits`, `display.hit` for 1)
where the implementation knows the count.
Anything else an implementation knows (the lines read, a job's id) it may add the same way.
## 3. The kinds of block
A tool's `block` (`tools/<name>.json`; `display.blocks`) says how its call is read, and every
client distinguishes these — at least by what it shows collapsed and what it opens to:
| `block` | Collapsed | Opened |
|---|---|---|
| `shell` | the command (the title), `exit N` | the output |
| `edit` | the path, `+N −M` | the change as a diff — a client may show the first of it without a click |
| `read` | the path (or the id) that was read | the text that came back, where the client keeps it |
| `search` | the pattern or the query, the hits | the hits |
| `web` | the query or the address | the results or the page's text |
| `task` | the task handed to a subagent | what the subagent did — its own calls, its progress (`subagents.md` §12) — and its report |
| `tool` | the tool's name and the title | the result |
| `plan` | **not drawn**: the plan card refreshes instead | |
| `hidden` | **not drawn** | |
A tool the client does not know (an MCP tool, a custom tool) is `tool`.
## 4. How `stopped` and `failed` end a reply
A turn that did not finish ends with the progress `stopped` or `failed` (`progress.md` §4). That
progress is not only the last thing on the progress line: **its line stays on the finished
reply** — the text alone, no elapsed time (`progress.md` §3):
- `Stopped: by you` · `Stopped: step limit` · `Stopped: budget` · `Stopped` (no reason known)
- `Failed: {{reason}}` — the error, one line
Every client draws it **at the end of that reply**, in the transcript, where it remains when the
next turn begins and the progress line has moved on — `failed` in the client's error colour,
`stopped` in its muted one. Nothing else says the same thing beside it: a client does not also
print the raw error or a second "cancelled" notice of its own wording. A reply with no text at all
(stopped before the first token) still gets the line, on its own.
Where the reply is shown again from what was stored — a reload, a resumed session, another client
— it is drawn again from the stored end; an implementation that stores a reply stores how it
ended (`stopped` with its reason, `failed` with its reason). A turn that finished normally shows
nothing.
## 5. What the card offers
When a session waits for the person (`waiting_for_person`), every client offers the same actions
(`display.actions`), under these words or their translation:
**An approval** (`what: approval`; `acp.md` `session/request_permission`):
| Action | Words | Answer |
|---|---|---|
| `once` | Allow once | the call runs; nothing is remembered |
| `always` | Always allow | the call runs and the offered pattern is allowed from now on — **offered only where the request offers it** (`always` absent: `permission/arity.json` `exact_only`, a `confirm: always` tool). A client with more than one place to remember it (this session, this project) may offer each |
| `deny` | Deny | the call is not run |
| `deny_reason` | Deny, and say why | the call is not run and the person's words go to the model as the reason (`feedback`) |
A client may also let the person **correct a command before allowing it once** (the answer's
`command`); what is written is judged again. Closing the card without choosing is `deny`.
The card shows what is asked about itself — the command, or the change as a diff — and the call's
`purpose` where one was given.
**A question** (`what: question`; `ask_user`, `acp.md` `_lembas/question`): the options as given,
the recommended one first and marked; several may be chosen where `multiple`; and **always a row
of the person's own — "Something else"** (`something_else`) — that takes free text and answers
`custom`. A client may offer asking back (`back`) and skipping one of several questions
(`skipped`). Closing the card is `dismissed`.
**A plan** (`what: plan`; `plan_submit`, `acp.md` `_lembas/plan`): **Approve** — together with
**the mode the work continues in** (`approve_edit`: Approve, continue in Edit; `approve_manual`:
Approve, continue in Manual; never a mode beyond what the session may have) — and **Revise**
(`revise`), which takes the person's words as feedback. Closing the card is `dismissed`: nothing
is decided.
A client that cannot offer one of these (a notification with two buttons) offers what fits and
opens the full card for the rest; it never answers for the person.
## 6. Numbers
A number a person reads is written **in the client's own locale format** — its grouping and its
decimal mark, from the platform's number formatter and the locale the client runs in (the
browser's, the phone's, a terminal's `LC_NUMERIC` / `LC_ALL` / `LANG`), not from a rule here. That is every count and
measure: tokens (`12,480` · `12 480` · `12.480`), the rate (`12.5` · `12,5`), `done` / `total` and
`percent`, hits, lines, `+added −removed`, costs and credits.
Not numbers in this sense, and written as they are everywhere: durations (§2, `progress.md` §3),
ids (`s1`, `job7`, `#12`), an exit code, a line number in a path (`a.ts:120`), a version, a port.
The texts in `conformance/` are written in the **plain format** — no grouping, `.` for the
decimal mark — which is what an implementation's text function produces when it is given no
locale; a client passes its locale's formatter to the same function. Nothing sent between
implementations is ever formatted: `progress` carries numbers, and each client formats its own.
+290
View File
@@ -483,5 +483,295 @@
"monitor_denied": "The watch command is refused here: {{reason}}.",
"no_reply": "The run ended without a reply."
}
},
"phone": {
"about": "Spec 3.6.0 (phone.md): `phone_action`, carried out by the LLeMbas app on the person's phone and confirmed there. `capability` is what the app declares with each message it sends; `fields` what each action reads (anything else in a call is dropped before the phone sees it); `required` the fields each action needs (a list inside the list: any one of them); `check` the order the fields' values are checked in; `wait_seconds` how long a call waits for the phone's answer; `texts` what the model is told, `what` what a bad field should have been. conformance/phone.json.",
"capability": "phone_actions",
"actions": [
"alarm",
"timer",
"calendar_event",
"sms_draft",
"email_draft",
"dial",
"navigate",
"add_stop",
"search_nearby",
"stop_navigation",
"open_app",
"open_url",
"media",
"torch",
"settings_panel",
"automation_intent"
],
"fields": {
"alarm": [
"time",
"days",
"label"
],
"timer": [
"seconds",
"label"
],
"calendar_event": [
"title",
"start",
"end",
"all_day",
"location",
"notes"
],
"sms_draft": [
"to",
"body"
],
"email_draft": [
"to",
"cc",
"subject",
"body"
],
"dial": [
"number"
],
"navigate": [
"destination",
"stops",
"mode",
"replace_route"
],
"add_stop": [
"stop",
"destination"
],
"search_nearby": [
"query",
"near"
],
"stop_navigation": [],
"open_app": [
"app"
],
"open_url": [
"url"
],
"media": [
"command"
],
"torch": [
"on"
],
"settings_panel": [
"panel"
],
"automation_intent": [
"task",
"app",
"values"
]
},
"required": {
"alarm": [
"time"
],
"timer": [
"seconds"
],
"calendar_event": [
"title",
"start"
],
"sms_draft": [
[
"to",
"body"
]
],
"email_draft": [
[
"to",
"subject",
"body"
]
],
"dial": [
"number"
],
"navigate": [
"destination"
],
"add_stop": [
"stop",
"destination"
],
"search_nearby": [
"query"
],
"stop_navigation": [],
"open_app": [
"app"
],
"open_url": [
"url"
],
"media": [
"command"
],
"torch": [
"on"
],
"settings_panel": [
"panel"
],
"automation_intent": [
"task"
]
},
"statuses": [
"done",
"declined",
"failed"
],
"wait_seconds": 300,
"message_max_chars": 1000,
"texts": {
"done": "Done on the phone.",
"declined": "The person declined it on the phone: nothing was done. Do not try again unless they ask.",
"failed": "The phone could not do it: nothing was done.",
"no_answer": "The phone did not answer in time: nothing was done.",
"says": "The phone says: {{message}}",
"unknown_action": "\"{{action}}\" is not an action. Use one of: {{actions}}. Nothing was sent to the phone.",
"missing": "{{action}} needs {{fields}}. Nothing was sent to the phone.",
"bad": "{{field}} is not {{what}}. Nothing was sent to the phone."
},
"what": {
"time": "a time as HH:MM (24-hour)",
"days": "a list of days from mon, tue, wed, thu, fri, sat, sun",
"seconds": "a whole number of seconds from 1 to 86400",
"start": "a date and time as YYYY-MM-DDTHH:MM, or a date as YYYY-MM-DD for a whole day",
"end": "a date and time as YYYY-MM-DDTHH:MM, or a date as YYYY-MM-DD for a whole day",
"to": "a list of recipients",
"cc": "a list of recipients",
"number": "a phone number",
"destination": "a place: lat and lon together, or a query, or a name",
"stop": "a place: lat and lon together, or a query, or a name",
"stops": "a list of places, each lat and lon together, or a query, or a name",
"mode": "one of drive, walk, bike, transit",
"near": "one of me, route",
"url": "an http or https address",
"command": "one of play, pause, toggle, next, previous",
"on": "true or false",
"panel": "one of wifi, bluetooth, internet, volume, nfc, location, do_not_disturb",
"values": "named text values"
},
"check": [
"time",
"days",
"seconds",
"start",
"end",
"to",
"cc",
"number",
"destination",
"stop",
"stops",
"mode",
"near",
"url",
"command",
"on",
"panel",
"values"
]
},
"display": {
"about": "Spec 3.7.0 (display.md): one display in every client. `title`: how a tool call's one short title is made from its arguments (the same string in the transcript, as running_tool's `what` and as the link's tool_call title) — `questions` and `patch` first, then the first non-blank string among `keys`; first line, cut to progress.what_max. `states`: the four states of a drawn call; `no_duration`: the states that show none. `duration`: a finished call's time (tenths under a minute). `change`, `exit`, `hits`/`hit`: the facts after the title. `blocks`: the kinds of block every client distinguishes; `not_drawn`: those that are no call in the transcript. `end`: the phases whose line stays on the finished reply. `actions`: what each card offers, with its English words (shared i18n keys display.actions.<card>.<action>). `plain`: the number format of the conformance texts. conformance/display.json.",
"title": {
"questions_join": " · ",
"patch_files": [
"*** Add File: ",
"*** Update File: ",
"*** Delete File: "
],
"patch_join": ", ",
"keys": [
"summary",
"command",
"code",
"pattern",
"query",
"url",
"path",
"file_path",
"from",
"description",
"name",
"id",
"title",
"key",
"target",
"to",
"action"
]
},
"states": [
"running",
"done",
"failed",
"denied"
],
"no_duration": [
"running",
"denied"
],
"duration": {
"tenths_under_seconds": 60
},
"change": "+{{added}} −{{removed}}",
"exit": "exit {{code}}",
"hits": "{{count}} hits",
"hit": "{{count}} hit",
"blocks": [
"shell",
"edit",
"read",
"search",
"web",
"task",
"tool",
"plan",
"hidden"
],
"not_drawn": [
"plan",
"hidden"
],
"end": [
"stopped",
"failed"
],
"actions": {
"approval": {
"once": "Allow once",
"always": "Always allow",
"deny": "Deny",
"deny_reason": "Deny, and say why"
},
"question": {
"something_else": "Something else"
},
"plan": {
"approve_edit": "Approve, continue in Edit",
"approve_manual": "Approve, continue in Manual",
"revise": "Revise"
}
},
"plain": {
"group": "",
"decimal": "."
}
}
}
+99
View File
@@ -0,0 +1,99 @@
# Phone actions
Spec 3.6.0. `phone_action` (`tools/phone_action.json`) lets a chat's model do something on the
person's phone — set an alarm, start a route, draft a message — when the person is writing from the
LLeMbas app on that phone. The model proposes; **the app shows the person a card and does nothing
until they confirm it there**; the app carries it out with the phone's own apps and answers what
happened, which is the call's result. The texts and numbers are `loop.json` `phone`.
It is the server's tool alone (`scope: llembas`, `sessions: chat`). The CLI never offers it: a
terminal has no phone behind it.
## 1. Who offers it
- **The capability.** The app declares `phone_actions` (`loop.json` `phone.capability`) with each
message it sends. A message sent from anywhere else — the web, Desktop, another app — declares
nothing.
- **`requires: phone`.** The tool is offered in a chat once a message has been sent to it with the
capability, and stays offered for the rest of the chat (the tool list is the session's,
`context.md` §10): a chat started on the phone and continued on the web keeps the tool, and a web
chat continued on the phone gains it from that message on (the list changes once, so the prompt
is made again once).
- **Unavailable.** A call answers the tool's `unavailable` text, word for word, when the message
being answered was not sent with the capability (there is no phone to confirm on), and in a chat
nobody attends (a schedule's, a subagent's). Nothing reaches any phone then.
- **Confirm: always.** Every call is put to the person, in every mode; nothing remembers an answer.
The card is the phone's own: the server never asks a second time on another screen. Its risk is
`interact`: no mode refuses it, Plan mode included, because nothing on disk changes and the
person decides on the phone.
## 2. A call
`action` is one of `phone.actions`; `summary` is the line the phone shows. Each action reads only
its `phone.fields`; anything else in the call is dropped before the phone sees it. The call is
checked before anything is sent, in this order, and the first problem is the call's result:
1. `action` not one of the actions: `texts.unknown_action` (`{{actions}}` the list, joined with
`, `).
2. The action's `phone.required`, each entry in turn: a field is present when it is not null, not
an empty string (after trimming) and not an empty list or object; a list inside the list is
present when any one of its fields is. Every entry that is missing, in order, goes in one
`texts.missing`: a field by its name, a group as its names joined with ` or `, the entries
joined with ` and ` (`add_stop needs stop and destination.`).
3. The fields present, in `phone.check` order (only those the action reads): one that is not what
it should be is `texts.bad` with `{{field}}` its name and `{{what}}` from `phone.what`:
- `time`: `HH:MM`, hours 00–23, minutes 00–59.
- `days`: a list, each one of `mon` … `sun`.
- `seconds`: an integer (never a boolean) from 1 to 86400.
- `start`, `end`: `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM` (not checked as a calendar date).
- `to`, `cc`: a list of strings, each non-empty after trimming.
- `number`: at least three digits, and nothing but digits, spaces and `+ ( ) - . / # *`.
- `destination`, `stop`: an object with numeric `lat` and `lon` together (each in its range),
or a non-empty `query`, or a non-empty `name`. `stops`: a list of such places.
- `mode`, `near`, `command`, `panel`: one of the schema's values.
- `url`: begins `http://` or `https://` (any case) and has something after it.
- `on`: a boolean.
- `values`: an object of strings.
A call that passes is the **action** the phone receives: `action`, `summary` (trimmed; the action's
name when empty) and the action's fields that are present, as the model gave them, strings trimmed.
## 3. The answer
The server waits up to `phone.wait_seconds` for the phone's answer: `status` (`done`, `declined`
or `failed`) and an optional `message`, at most `phone.message_max_chars` characters (cut there).
The call's result is the status's text — `texts.done`, `texts.declined`, `texts.failed` — and,
when there is a message, a blank line and `texts.says` with it. A status the phone does not know is
`failed`. No answer in time is `texts.no_answer`, with no message; the card goes away.
What the person pressed is theirs: **declined** means they said no, and the model is told not to
try again unless asked. **Failed** is the phone's: an app missing, a permission refused, a map app
that cannot do what was asked.
## 4. Navigation
Map apps differ, and the phone says when one cannot: the model is not told which app the person
uses.
- `navigate` starts a route to `destination` through `stops`, in order; `mode` is how the person
travels (`drive` when not said). `replace_route` replaces a route already running without the
phone asking first.
- `add_stop`: **no map app adds a stop to a running route**, so the phone plans again — from where
the person is, to `stop`, then to `destination`. The model gives `destination` as the person told
it when the route began: the tool's description tells it to keep it.
- `search_nearby` looks for `query` around the person (`near: me`) or along the running route
(`near: route`).
- `stop_navigation` ends the route where the map app allows it; one that does not answers
`failed` with why.
## 5. The other actions
- `alarm` and `timer` are the phone's clock app; `days` repeats an alarm.
- `calendar_event` opens the calendar's new-event screen filled in; the person saves it.
- `sms_draft` and `email_draft` are **drafts**: the messaging or mail app opens with them, and the
person sends. `dial` opens the dialer with the number; the person places the call.
- `open_app` names an app as the person does; `open_url` opens an address in the browser.
- `media` controls what is playing; `torch` switches the torch.
- `settings_panel` opens the phone's quick panel or page for a setting; the person changes it.
- `automation_intent` runs an automation the person made in an automation app (Tasker when `app`
is not said), by its name, with `values` as its inputs.
+3 -2
View File
@@ -35,7 +35,7 @@ In the order a turn usually meets them. `{{x}}` in a text is the field `x`; the
| `reading_prompt` | `done: int`, `total: int` — prompt tokens processed of all | `Reading the prompt: {{done}} / {{total}} tokens ({{percent}}%)` · without `total`: `Reading the prompt` |
| `thinking` | — | `Thinking` |
| `writing` | `rate?: number` — tokens a second, as measured over this reply | `Writing: {{rate}} tok/s` · without `rate`: `Writing` |
| `running_tool` | `tool: string` (the tool's name); `what?: string` — the call's short title (the command, the path, the query), one line, at most 80 characters | `Running {{tool}}: {{what}}` · without `what`: `Running {{tool}}` |
| `running_tool` | `tool: string` (the tool's name); `what?: string` — the call's short title (the command, the path, the query; from 3.7.0 exactly `display.md` §1), one line, at most 80 characters | `Running {{tool}}: {{what}}` · without `what`: `Running {{tool}}` |
| `waiting_for_person` | `what: "approval" \| "question" \| "plan"`; `tool?: string` (approval: the tool asked about) | `Waiting for you: {{what}}` |
| `waiting_for_subagents` | `running: int` — subagents working or waiting now | `Waiting for subagents: {{running}} running` |
| `compacting` | — | `Compacting the conversation` |
@@ -88,7 +88,8 @@ What decides the phase, so that two implementations agree on the same moment:
- `compacting` — a compaction runs. `retrying` — a failed request will be sent again after a wait.
- `stopped` / `failed` — the turn ended other than by finishing: stopped by the person, a step limit
or a budget; failed with an error. They are the last progress of that turn and stay until the
next one begins; a turn that finished normally ends with `null`.
next one begins; a turn that finished normally ends with `null`. From 3.7.0 their line also stays on
the finished reply itself (`display.md` §4).
## 5. Where it is sent
+289
View File
@@ -0,0 +1,289 @@
{
"name": "phone_action",
"scope": "llembas",
"sessions": "chat",
"risk": "interact",
"exclusive": true,
"block": "tool",
"purpose": false,
"requires": [
"phone"
],
"unavailable": "This needs the LLeMbas app on the person's phone, and this message did not come from it: nothing was done on any phone. Say what you would have done, and that they can ask again from the app.",
"confirm": "always",
"aliases": {
"cli": [],
"llembas": []
},
"description": "Do something on the person's phone: they are writing to you from the LLeMbas app on it, and the app carries it out with the phone's own apps. The person confirms every call on the phone before anything happens; the result says done, declined or failed, with what the phone said.\n\nUse it only for what the person asked for, one action per call. `summary` is the one line the phone shows them: say what will happen, in their language.\n\n- alarm: `time` (HH:MM, 24-hour); `days` to repeat it; `label`.\n- timer: `seconds`; `label`.\n- calendar_event: `title`, `start` (YYYY-MM-DDTHH:MM, the phone's local time; YYYY-MM-DD with all_day); `end`, `all_day`, `location`, `notes`.\n- sms_draft: `to` (numbers, or names as the person said them), `body`. A draft: the person sends it.\n- email_draft: `to`, `cc`, `subject`, `body`. A draft: the person sends it.\n- dial: `number`. Opens the dialer with it; the person places the call.\n- navigate: `destination`; `stops` on the way, in order; `mode` (drive, walk, bike, transit); `replace_route` to start over rather than ask.\n- add_stop: `stop`, and `destination` — the route's destination as the person told you. Keep the destination of a route you started: no map app can add to a running route, so the phone plans again to the stop and then the destination.\n- search_nearby: `query` (\"petrol station\"), `near` me or the route.\n- stop_navigation: ends the route. Not every map app can; the phone says so if not.\n- open_app: `app`, as the person names it.\n- open_url: `url` (http or https).\n- media: `command` (play, pause, toggle, next, previous) for what is playing.\n- torch: `on`.\n- settings_panel: `panel` — the phone's quick panel or page for it; the person flips the switch.\n- automation_intent: `task`, the name of an automation the person made (Tasker by default, or `app`); `values` it is given.\n\nA place is lat and lon when you know them, else a `query` the map app searches; `name` is what the person calls it.\n\nDeclined means they said no on the phone: do not try again unless they ask. Failed says why; nothing was done.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"alarm",
"timer",
"calendar_event",
"sms_draft",
"email_draft",
"dial",
"navigate",
"add_stop",
"search_nearby",
"stop_navigation",
"open_app",
"open_url",
"media",
"torch",
"settings_panel",
"automation_intent"
],
"description": "What to do"
},
"summary": {
"type": "string",
"description": "One line the phone shows the person: what will happen"
},
"time": {
"type": "string",
"description": "alarm: HH:MM, 24-hour"
},
"days": {
"type": "array",
"items": {
"type": "string",
"enum": [
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
"sun"
]
},
"description": "alarm: the days it repeats on; none for once"
},
"label": {
"type": "string",
"description": "alarm, timer: its name on the phone"
},
"seconds": {
"type": "integer",
"minimum": 1,
"maximum": 86400,
"description": "timer: how long"
},
"title": {
"type": "string",
"description": "calendar_event: the event's title"
},
"start": {
"type": "string",
"description": "calendar_event: YYYY-MM-DDTHH:MM, local; YYYY-MM-DD with all_day"
},
"end": {
"type": "string",
"description": "calendar_event: as start"
},
"all_day": {
"type": "boolean",
"description": "calendar_event: a whole day"
},
"location": {
"type": "string",
"description": "calendar_event: where"
},
"notes": {
"type": "string",
"description": "calendar_event: its description"
},
"to": {
"type": "array",
"items": {
"type": "string"
},
"description": "sms_draft: numbers or names; email_draft: addresses"
},
"cc": {
"type": "array",
"items": {
"type": "string"
},
"description": "email_draft: addresses"
},
"subject": {
"type": "string",
"description": "email_draft"
},
"body": {
"type": "string",
"description": "sms_draft, email_draft: the text"
},
"number": {
"type": "string",
"description": "dial: the phone number"
},
"destination": {
"type": "object",
"description": "navigate, add_stop: where the route ends",
"properties": {
"name": {
"type": "string",
"description": "What the person calls it: \"Home\", \"Lidl on Main Street\""
},
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude, when known"
},
"lon": {
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude, when known"
},
"query": {
"type": "string",
"description": "What the map app searches when there are no coordinates"
}
}
},
"stops": {
"type": "array",
"items": {
"type": "object",
"description": "A place: lat and lon when you know them, else a query the map app searches (an address, or a name and a town); name is what the person calls it",
"properties": {
"name": {
"type": "string",
"description": "What the person calls it: \"Home\", \"Lidl on Main Street\""
},
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude, when known"
},
"lon": {
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude, when known"
},
"query": {
"type": "string",
"description": "What the map app searches when there are no coordinates"
}
}
},
"description": "navigate: places on the way, in order"
},
"stop": {
"type": "object",
"description": "add_stop: the place to add",
"properties": {
"name": {
"type": "string",
"description": "What the person calls it: \"Home\", \"Lidl on Main Street\""
},
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude, when known"
},
"lon": {
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude, when known"
},
"query": {
"type": "string",
"description": "What the map app searches when there are no coordinates"
}
}
},
"mode": {
"type": "string",
"enum": [
"drive",
"walk",
"bike",
"transit"
],
"description": "navigate: how the person travels (drive when not said)"
},
"replace_route": {
"type": "boolean",
"description": "navigate: replace a route already running without asking"
},
"query": {
"type": "string",
"description": "search_nearby: what to look for"
},
"near": {
"type": "string",
"enum": [
"me",
"route"
],
"description": "search_nearby: around the person, or along the running route"
},
"app": {
"type": "string",
"description": "open_app: the app, as the person names it; automation_intent: the automation app (Tasker when not said)"
},
"url": {
"type": "string",
"description": "open_url: an http or https address"
},
"command": {
"type": "string",
"enum": [
"play",
"pause",
"toggle",
"next",
"previous"
],
"description": "media"
},
"on": {
"type": "boolean",
"description": "torch: on or off"
},
"panel": {
"type": "string",
"enum": [
"wifi",
"bluetooth",
"internet",
"volume",
"nfc",
"location",
"do_not_disturb"
],
"description": "settings_panel"
},
"task": {
"type": "string",
"description": "automation_intent: the automation's name"
},
"values": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "automation_intent: named values it is given"
}
},
"required": [
"action",
"summary"
]
}
}
+5 -1
View File
@@ -9,7 +9,11 @@
"requires": [
"page"
],
"unavailable": "Python cannot run now: no open browser page is attached to this chat.",
"unavailable": "Python cannot run now: no page of this chat is open. Python runs in the person's browser — ask them to open this chat in the LLeMbas web or desktop app and keep it open, then call python again.",
"texts": {
"no_answer": "Python did not run: a page of this chat is open, but it did not answer. It may still be loading Python, or be asleep in a background tab — ask the person to bring this chat to the front (or reload it), then call python again.",
"timeout": "Python stopped: the run took longer than {{seconds}} seconds, and nothing it wrote was saved. Do less in one call, or split the work over several calls."
},
"aliases": {
"cli": [],
"llembas": []
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "lembas-cli",
"version": "2.0.0-beta.7",
"version": "2.0.0-beta.9",
"description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.",
"license": "MIT",
"private": true,
+12
View File
@@ -60,6 +60,18 @@
"description": "When a reply finishes, or the agent waits for you, while the terminal is not focused: ring the bell and ask the terminal for a desktop notification (OSC 9) naming the session — never what the reply says. Default true; false: neither.",
"type": "boolean"
},
"paste": {
"description": "A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path.",
"type": "string",
"enum": [
"placeholder",
"full"
]
},
"kitty_clipboard": {
"description": "true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in.",
"type": "boolean"
},
"icons": {
"description": "emoji (default), or plain: one-column symbols for a terminal font that has no emoji.",
"type": "string",
+44 -19
View File
@@ -30,7 +30,8 @@ import { PLAN_META } from "../session/engine.ts"
import { ToolError } from "../tool/tool.ts"
import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts"
import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts"
import { shellLaunch } from "./shellrc.ts"
import { pickShell, shellLaunch } from "./shellrc.ts"
import { callTitle } from "../session/display.ts"
import { sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts"
import { expandHome } from "../config/paths.ts"
import { asMode, MODES, type Mode } from "../config/schema.ts"
@@ -82,7 +83,7 @@ export function refusalFor(L: Limits | undefined, dir: string): string | undefin
if (L.sharedOnly) return "remote work is off on this machine (remote.enabled); only the sessions its terminal shares (/remote) can be reached"
if (L.enabled === false) return "remote work is off on this machine — lembas remote enable there (remote.enabled)"
if (!L.roots.length) return "this device allows no folders for remote work yet — lembas remote add <dir> there (remote.roots)"
if (!underRoots(dir, L.roots)) return `${dir} is outside the directories this device accepts remote work in (remote.roots)`
if (!underRoots(dir, L.roots)) return `${dir} is outside the directories this device accepts remote work in — to allow it, run lembas remote add <dir> there (remote.roots)`
if (L.requireTrust && trustOf(findProject(dir).root) !== "trusted" && !trustedWithin(realPath(dir)))
return `${dir} is not in a trusted project on this device — trust it there first (lembas trust)`
return undefined
@@ -303,6 +304,8 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien
sessionId,
toolCall: {
toolCallId: o.toolCallId ?? crypto.randomUUID(),
// The card's title is the whole command, or the tool's name: a card is read before it is
// answered. The call's short title (display.md §1) belongs on tool_call, not here.
title: req.request.command ?? req.tool,
kind: toolKind(req.tool),
status: "pending",
@@ -316,6 +319,7 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien
],
_meta: {
lembas: {
tool: req.tool,
reason: req.decision.reason,
purpose: req.purpose,
always: req.decision.always ?? req.request.always,
@@ -1342,27 +1346,35 @@ export class AcpAgent {
* model's, so the hardline and the modes do not apply, exactly as in a terminal opened here. */
private terminalOpen(p: any) {
const L = this.limits
if (!L?.terminal) throw new RpcError(INVALID_PARAMS, "this device does not open terminals for the web UI (remote.terminal is off)")
if (!L?.terminal) throw new RpcError(INVALID_PARAMS, "Terminals are switched off on this computer. To allow them, run `lembas remote terminal on` there (remote.terminal).")
const cwd = typeof p?.cwd === "string" && p.cwd.trim() ? resolve(expandHome(p.cwd.trim())) : resolve(expandHome(L.roots[0] ?? "~"))
const refused = this.refusal(cwd)
if (refused) throw new RpcError(INVALID_PARAMS, refused)
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a directory on this machine`)
if (this.terminals.size >= MAX_TERMINALS) throw new RpcError(INVALID_PARAMS, `this device already has ${MAX_TERMINALS} terminals open for the web UI`)
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a folder on this computer — choose one that exists`)
if (this.terminals.size >= MAX_TERMINALS) throw new RpcError(INVALID_PARAMS, `This computer already has ${MAX_TERMINALS} terminals open — close one, then open another.`)
const id = crypto.randomUUID()
const cols = Math.max(20, Math.min(500, Number(p?.cols) || 80))
const rows = Math.max(5, Math.min(300, Number(p?.rows) || 24))
const shell = process.env.SHELL || "/bin/bash"
const picked = pickShell()
if (!picked) throw new RpcError(INVALID_PARAMS, "No shell was found on this computer to open a terminal with — set SHELL to one (on Windows: install PowerShell).")
// Marks for the web UI's terminal: the user's own startup files first, then OSC 133/7.
const launch = shellLaunch(shell, id, L.terminalIntegration !== false)
const proc = Bun.spawn(launch.argv, {
cwd,
env: { ...process.env, TERM: "xterm-256color", ...launch.env },
terminal: {
cols,
rows,
data: (_t: unknown, d: Uint8Array) => this.peer.notify("_lembas/terminal/output", { terminalId: id, data: Buffer.from(d).toString("base64") }),
},
} as Parameters<typeof Bun.spawn>[1])
const launch = shellLaunch(picked.shell, id, L.terminalIntegration !== false, process.env, picked.args)
let proc: ReturnType<typeof Bun.spawn>
try {
proc = Bun.spawn(launch.argv, {
cwd,
env: { ...process.env, TERM: "xterm-256color", ...launch.env },
terminal: {
cols,
rows,
data: (_t: unknown, d: Uint8Array) => this.peer.notify("_lembas/terminal/output", { terminalId: id, data: Buffer.from(d).toString("base64") }),
},
} as Parameters<typeof Bun.spawn>[1])
} catch (e) {
// The runtime's pseudo-terminal is POSIX's: where it has none (Windows), say so plainly.
launch.cleanup()
throw new RpcError(INVALID_PARAMS, `A terminal could not be opened on this computer (${basename(picked.shell)}): ${(e as Error).message.split("\n")[0]}`)
}
const pty = (proc as unknown as { terminal: Terminal["pty"] }).terminal
this.terminals.set(id, { proc, pty, cleanup: launch.cleanup })
void proc.exited.then((code) => {
@@ -1434,17 +1446,30 @@ export class AcpAgent {
case "reasoning":
return this.update(s, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: e.text } })
case "tool_start":
return this.update(s, { sessionUpdate: "tool_call", toolCallId: e.id, title: e.name, kind: toolKind(e.name), status: "in_progress", rawInput: e.args })
// One title for a call (display.md §1): the same as the transcript's and the progress line's.
return this.update(s, { sessionUpdate: "tool_call", toolCallId: e.id, title: e.title ?? callTitle(e.args) ?? e.name, kind: toolKind(e.name), status: "in_progress", rawInput: e.args })
case "tool_end":
return this.update(s, {
sessionUpdate: "tool_call_update",
toolCallId: e.id,
status: e.result.isError ? "failed" : "completed",
...(e.result.title ? { title: e.result.title } : {}),
content: [{ type: "content", content: { type: "text", text: e.result.output.slice(0, 20_000) } }],
})
case "tool_denied":
return this.update(s, { sessionUpdate: "tool_call_update", toolCallId: e.id, status: "failed", content: [{ type: "content", content: { type: "text", text: e.reason } }] })
// Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas.
// A refused call never started, so no tool_call announced it (the approval card, if one
// was shown, has an id of its own): this is the call's first and only update, and an
// update of an id nobody knows would be dropped.
return this.update(s, {
sessionUpdate: "tool_call",
toolCallId: e.id,
title: e.title ?? e.name,
kind: toolKind(e.name),
status: "failed",
...(e.args !== undefined ? { rawInput: e.args } : {}),
content: [{ type: "content", content: { type: "text", text: e.reason } }],
_meta: { lembas: { denied: true } },
})
case "plan":
return this.update(s, planUpdate(e.plan))
case "mode":
+27 -4
View File
@@ -9,7 +9,7 @@
// files (which it sources), zsh a ZDOTDIR whose files source the user's own and hand ZDOTDIR back,
// fish a command run after its config. Any other shell starts as it did before, without marks.
// `remote.terminal_integration: false` turns it off.
import { mkdirSync, rmSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"
import { basename, join } from "node:path"
import { paths } from "../config/paths.ts"
@@ -167,11 +167,34 @@ export interface ShellLaunch {
cleanup(): void
}
/** The shell a terminal opened from the web UI runs, and how it is started without the marks.
* POSIX: `$SHELL` when it is there, else the first of bash, zsh and sh that is — as a login
* shell (`-l`). Windows: PowerShell 7 (`pwsh`), then Windows PowerShell, then `%ComSpec%` /
* `cmd.exe` — none of which takes `-l`. Undefined when the machine has none of them. */
export function pickShell(
os: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
has: (path: string) => boolean = existsSync,
which: (cmd: string) => string | null = Bun.which,
): { shell: string; args: string[] } | undefined {
if (os === "win32") {
for (const name of ["pwsh.exe", "powershell.exe"]) {
const found = which(name)
if (found) return { shell: found, args: ["-NoLogo"] }
}
const cmd = (env.ComSpec && has(env.ComSpec) ? env.ComSpec : undefined) ?? which("cmd.exe")
return cmd ? { shell: cmd, args: [] } : undefined
}
const shell = [env.SHELL, "/bin/bash", "/bin/zsh", "/bin/sh"].find((s): s is string => !!s && has(s))
return shell ? { shell, args: ["-l"] } : undefined
}
/** How to start `shell` for terminal `id`: with the marks when it is bash, zsh or fish and
* `integration` is on; as `$SHELL -l` otherwise. */
export function shellLaunch(shell: string, id: string, integration: boolean, env: NodeJS.ProcessEnv = process.env): ShellLaunch {
* `integration` is on; as `$SHELL -l` (or with `plainArgs`, for a shell that takes no `-l`)
* otherwise. */
export function shellLaunch(shell: string, id: string, integration: boolean, env: NodeJS.ProcessEnv = process.env, plainArgs: string[] = ["-l"]): ShellLaunch {
const kind = shellKind(shell)
const plain: ShellLaunch = { kind, integration: false, argv: [shell, "-l"], env: {}, cleanup: () => {} }
const plain: ShellLaunch = { kind, integration: false, argv: [shell, ...plainArgs], env: {}, cleanup: () => {} }
if (!integration || kind === "other") return plain
const dir = join(paths.state, "terminal", id.replace(/[^\w-]/g, "_"))
const cleanup = () => rmSync(dir, { recursive: true, force: true })
+3 -2
View File
@@ -26,9 +26,10 @@ export type Event =
| { type: "tool_call_delta"; index: number; name?: string; argsDelta: string }
/** The server reading the prompt, before the reply (llama.cpp): tokens in all, from its cache, read so far. */
| { type: "progress"; total: number; cache: number; processed: number; ms: number }
| { type: "tool_start"; id: string; name: string; args: unknown }
/** `title`: the call's one short title (harness display.md §1), made from `args` when it starts. */
| { type: "tool_start"; id: string; name: string; args: unknown; title?: string }
| { type: "tool_end"; id: string; name: string; result: ToolResult; ms: number }
| { type: "tool_denied"; id: string; name: string; reason: string }
| { type: "tool_denied"; id: string; name: string; reason: string; args?: unknown; title?: string }
| {
type: "usage"
usage: Usage
+2
View File
@@ -242,6 +242,8 @@ export const Config = z.strictObject({
busy_input: z.enum(["steer", "queue"]).optional().describe("A message sent while the agent works: steer (default) — it goes in at the next step, after the running tools finish, and the agent carries on with it; queue — it is sent as the next prompt once the task is done."),
mouse: z.boolean().optional().describe("false: leave the mouse to the terminal — its own selection and Ctrl+Shift+C work without Shift, and the wheel no longer scrolls the transcript (pgup/pgdn do). Default true."),
notify: z.boolean().optional().describe("When a reply finishes, or the agent waits for you, while the terminal is not focused: ring the bell and ask the terminal for a desktop notification (OSC 9) naming the session — never what the reply says. Default true; false: neither."),
paste: z.enum(["placeholder", "full"]).optional().describe("A long paste into the prompt box (3 lines or more, or over 150 characters) and a pasted image: placeholder (default) — shown as [Pasted text 40 lines] or [Image 1], sent in full; full — the text itself, and an image as its @path."),
kitty_clipboard: z.boolean().optional().describe("true: over SSH in the kitty terminal, ctrl+v asks the terminal itself for the image on its clipboard (kitty's clipboard protocol, OSC 5522; kitty asks you to allow it). Default false: on a connection that stalls the image may not arrive whole — it is then refused, never saved broken — so it is opt-in."),
icons: z.enum(["emoji", "plain"]).optional().describe("emoji (default), or plain: one-column symbols for a terminal font that has no emoji."),
personality: z
.enum(PERSONALITIES)
+2
View File
@@ -59,6 +59,8 @@ export const SETTINGS: SettingDef[] = [
{ key: "theme", kind: "string", agent: true, scopes: USER, fallback: "moria" },
{ key: "theme_background", kind: "enum", values: ["theme", "terminal"], agent: true, scopes: USER, fallback: "theme" },
{ key: "busy_input", kind: "enum", values: ["steer", "queue"], agent: true, scopes: USER, fallback: "steer" },
{ key: "paste", kind: "enum", values: ["placeholder", "full"], agent: true, scopes: USER, fallback: "placeholder", hint: "a long paste or a pasted image in the prompt box: a placeholder, or shown in full" },
{ key: "kitty_clipboard", kind: "boolean", agent: false, scopes: USER, fallback: "false", hint: "over SSH in kitty, ctrl+v asks the terminal for the image on its clipboard" },
{ key: "icons", kind: "enum", values: ["emoji", "plain"], agent: true, scopes: USER, fallback: "emoji" },
{ key: "notify", kind: "boolean", agent: true, scopes: USER, fallback: "true", hint: "bell and desktop notification when a reply finishes or the agent waits for you while the terminal is not focused" },
{ key: "mouse", kind: "boolean", agent: true, scopes: ["global"], reload: true, fallback: "true" },
+3 -1
View File
@@ -1,7 +1,9 @@
/** Time as the eye reads it: 8.4s, 1m 05s, 2h 03m. `whole`: no tenths under a minute (8s) — for a
* clock that ticks while you watch. */
export function duration(ms: number, whole = false): string {
const s = Math.max(0, ms) / 1000
let s = Math.max(0, ms) / 1000
// 59.96 s is a minute, not "60.0s": tenths are only written where they stay under one.
if (!whole && s >= 59.95 && s < 60) s = 60
if (s < 60) return whole ? `${Math.floor(s)}s` : `${s.toFixed(1)}s`
const m = Math.floor(s / 60)
if (m < 60) return `${m}m ${String(Math.floor(s % 60)).padStart(2, "0")}s`
+29 -3
View File
@@ -28,6 +28,7 @@ import t_mv from "../harness/tools/mv.json"
import t_note_manage from "../harness/tools/note_manage.json"
import t_note_view from "../harness/tools/note_view.json"
import t_notes_search from "../harness/tools/notes_search.json"
import t_phone_action from "../harness/tools/phone_action.json"
import t_plan_submit from "../harness/tools/plan_submit.json"
import t_plan_update from "../harness/tools/plan_update.json"
import t_plan_write from "../harness/tools/plan_write.json"
@@ -91,10 +92,14 @@ export interface ToolSpecDef {
* can be opened: over the link, to a client that offers `show`), `page`, `forge` (the chat's);
* `plan` (3.1.0): plan mode. From 3.1.0 one that can come and go during a session does not
* leave the tool out: it is offered and answers `unavailable` while unmet (context.md §10).
* `team` (3.2.0): the team setting allows more than one agent (harness/team.md §2). */
requires?: ("display" | "page" | "forge" | "plan" | "team")[]
* `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")[]
/** What a call answers, word for word, when a requirement went away after the offer. */
unavailable?: string
/** Spec 3.7.0: a tool's other fixed answers, by key (python: no_answer, timeout). */
texts?: Record<string, string>
/** `always`: put to the person in every mode, auto included; never remembered. */
confirm?: "always"
/** `{{name}}` in the description: a fact the projects differ in, filled in by each (fillDescription). */
@@ -183,6 +188,27 @@ export const LOOP: {
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>
}
/** Display (spec 3.7.0, harness/display.md): a tool call's title, states and facts, the blocks,
* the phases that end a reply, what each card offers. */
display: {
title: { questions_join: string; patch_files: string[]; patch_join: string; keys: string[] }
states: string[]
no_duration: string[]
duration: { tenths_under_seconds: number }
change: string
exit: string
hits: string
hit: string
blocks: string[]
not_drawn: string[]
end: string[]
actions: {
approval: Record<"once" | "always" | "deny" | "deny_reason", string>
question: Record<"something_else", string>
plan: Record<"approve_edit" | "approve_manual" | "revise", string>
}
plain: { group: string; decimal: string }
}
/** Progress (spec 3.4.0, harness/progress.md): the phases, their texts, the line. */
progress: {
phases: string[]
@@ -313,7 +339,7 @@ export function narrowParameters(parameters: Record<string, unknown>, narrow: Na
}
export const TOOL_SPECS: Record<string, ToolSpecDef> = Object.fromEntries(
([t_apply_patch, t_ask_user, t_bash, t_branch, t_commit, t_decisions, t_edit, t_glob, t_grep, t_job_list, t_job_output, t_job_send, t_job_stop, t_knowledge_get, t_knowledge_search, t_list, t_memory, t_merge, t_mkdir, t_multiedit, t_mv, t_note_manage, t_note_view, t_notes_search, t_plan_submit, t_plan_update, t_plan_write, t_pr, t_python, t_read, t_recall, t_release, t_report, t_rm, t_search, t_session_search, t_settings, t_show, t_skill_manage, t_skill_view, t_skills_list, t_tag, t_task, t_tasks, t_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_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
+28 -6
View File
@@ -7,6 +7,9 @@ import type { PlanReply, PlanRequest } from "./tool/plan_submit.ts"
import type { IconSet } from "./tui/icons.ts"
import { loadTheme, type Theme } from "./tui/palette.ts"
import { duration } from "./duration.ts"
import { blockOf, callTitle, resultFacts } from "./session/display.ts"
import { endLine, endOf, type Progress } from "./session/progress.ts"
import { num } from "./tui/locale.ts"
/** The theme's colours as 24-bit escapes — the same theme the TUI uses (`theme` in config.yaml). */
function escapes(theme: Theme) {
@@ -26,6 +29,8 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
let inReasoning = false
let atLineStart = true
let started = false
const titles = new Map<string, string | undefined>()
let failure: string | undefined
const out = (s: string) => {
if (!s) return
process.stdout.write(s)
@@ -53,11 +58,20 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
inReasoning = true
out(c(C.think, e.text))
break
case "tool_start":
titles.set(e.id, e.title ?? callTitle(e.args))
break
case "tool_end": {
// A call as every client shows it (harness display.md): its one title, what the result
// adds, how long it took.
const verb = e.name.padEnd(6)
const mark = e.result.isError ? c(C.err, "✗") : ""
const title = e.result.title ?? (e.result.isError ? e.result.output.split("\n")[0]!.slice(0, 120) : "")
line(`${c(C.dim, "┊")} ${icon(e.name)} ${c(C.label, verb)} ${title} ${c(C.dim, duration(e.ms))} ${mark}`)
const title = titles.get(e.id)
titles.delete(e.id)
const facts = resultFacts(blockOf(e.name), title, e.result, num)
if (e.result.isError && !facts.length) facts.push(e.result.output.trim().split("\n")[0]!.slice(0, 120))
const after = [...facts, duration(e.ms)].join(" · ")
line(`${c(C.dim, "┊")} ${icon(e.name)} ${c(C.label, verb)} ${title ? `${title} ${c(C.dim, `· ${after}`)}` : c(C.dim, after)} ${mark}`)
break
}
case "sub_tool":
@@ -72,7 +86,7 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
else if (e.state === "end") line(`${c(C.dim, "┊")} ${c(C.label, e.job.id)} ${e.job.state}${e.job.exit !== undefined ? ` (${e.job.exit === null ? "stopped" : `exit ${e.job.exit}`})` : ""} · ${e.job.description}`)
break
case "tool_denied":
line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.reason.split("\n")[0]!.slice(0, 140)}`)
line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.title ? `${e.title} ${c(C.dim, "·")} ` : ""}${e.reason.split("\n")[0]!.slice(0, 140)}`)
break
case "retract":
if (!atLineStart) out("\n")
@@ -82,12 +96,20 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
line(c(C.warn, `⚠ ${e.message}`))
break
case "error":
line(c(C.err, `✗ ${e.message}`))
// Said once, as the line that ends the reply.
failure = e.message
break
case "done":
case "done": {
if (!atLineStart) out("\n")
if (e.reason === "steps") line(c(C.warn, "⚠ stopped at the step limit"))
// How a reply that did not finish ended: the spec's line (display.md §4).
const end = endOf(e.reason, failure)
const text = end && endLine({ ...end, since: 0 } as Progress, 0, num)
if (text) line(end!.phase === "failed" ? c(C.err, `✗ ${text}`) : c(C.warn, `■ ${text}`))
const more = end?.phase === "failed" ? failure?.trim().split("\n").slice(1).join("\n").trim() : ""
if (more) line(c(C.err, more))
failure = undefined
break
}
}
})
}
+1 -1
View File
@@ -466,7 +466,7 @@ export class JobRegistry {
case "tool_end":
case "tool_denied": {
job.tools = (job.tools ?? 0) + 1
const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `denied — ${e.reason.split("\n")[0]!.slice(0, 80)}`
const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `${e.title ? `${e.title} · ` : ""}denied — ${e.reason.split("\n")[0]!.slice(0, 80)}`
const isError = e.type === "tool_denied" || e.result.isError === true
this.append(job, `\n[${e.name}] ${title}${isError && e.type === "tool_end" ? " (error)" : ""}\n`)
if (job.ownerCallId) owner?.bus.emit({ type: "sub_tool", callId: job.ownerCallId, jobId: job.id, name: e.name, title, ...(isError ? { isError } : {}) })
+171 -16
View File
@@ -1,6 +1,6 @@
// Images for vision models: read, size-checked, downscaled when ImageMagick is there.
import { readFileSync, statSync } from "node:fs"
import { extname } from "node:path"
import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { extname, join } from "node:path"
import { imageSize } from "../provider/tokens.ts"
import type { ImagePart } from "../provider/types.ts"
@@ -43,19 +43,174 @@ export function loadImage(path: string): ImagePart | string {
return { type: "image", mime: "image/jpeg", data: Buffer.from(r.stdout).toString("base64") }
}
/** An image on the clipboard (Wayland or X11), saved to `dest`; undefined when there is none. */
export function clipboardImage(dest: string): string | undefined {
const tries: string[][] = []
if (Bun.which("wl-paste")) tries.push(["wl-paste", "--no-newline", "--type", "image/png"])
if (Bun.which("xclip")) tries.push(["xclip", "-selection", "clipboard", "-t", "image/png", "-o"])
for (const cmd of tries) {
const r = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "ignore" })
const out = r.stdout
// A PNG starts with \x89PNG; anything else is text or nothing.
if (r.exitCode === 0 && out.length > 8 && out[0] === 0x89 && out[1] === 0x50) {
Bun.write(dest, out)
return dest
}
}
/** What a pasted or clipboard image may be, in the order asked for. */
export const CLIPBOARD_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const
const EXT_OF: Record<string, string> = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif" }
/** The most a pasted image may be before it is saved (loadImage shrinks, or refuses, when it is sent). */
export const MAX_PASTE_BYTES = 20_000_000
/** What kind of image these bytes are, by their signature — never by what they were called. */
export function sniffImage(b: Uint8Array): (typeof CLIPBOARD_TYPES)[number] | undefined {
if (b.length < 12) return undefined
if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) return "image/png"
if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "image/jpeg"
if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38) return "image/gif"
if (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) return "image/webp"
return undefined
}
/** Whether these bytes are the whole of an image of this kind, by its own structure: a PNG's
* chunks run exactly to its IEND, a JPEG ends with its end marker, a GIF with its trailer, a
* WebP is as long as its header says. Bytes lost on the way (a transfer cut or missing a piece)
* fail it. */
export function imageWhole(b: Uint8Array, mime: string): boolean {
const n = b.length
if (mime === "image/png") {
let at = 8
let last = ""
while (at + 12 <= n) {
const len = ((b[at]! << 24) | (b[at + 1]! << 16) | (b[at + 2]! << 8) | b[at + 3]!) >>> 0
last = String.fromCharCode(b[at + 4]!, b[at + 5]!, b[at + 6]!, b[at + 7]!)
at += 12 + len
}
return at === n && last === "IEND"
}
if (mime === "image/jpeg") return n >= 4 && b[n - 2] === 0xff && b[n - 1] === 0xd9
if (mime === "image/gif") return n >= 14 && b[n - 1] === 0x3b
if (mime === "image/webp") {
const size = (b[4]! | (b[5]! << 8) | (b[6]! << 16) | (b[7]! << 24)) >>> 0
return size + 8 === n || size + 9 === n
}
return false
}
let saved = 0
/** Save pasted image bytes under `dir` (made if missing), named by time and kind. */
export function savePastedImage(dir: string, bytes: Uint8Array, mime: string): string {
mkdirSync(dir, { recursive: true, mode: 0o700 })
const path = join(dir, `paste-${Date.now()}-${++saved}${EXT_OF[mime] ?? ".png"}`)
writeFileSync(path, bytes, { mode: 0o600 })
return path
}
/** Pasted text that is an image: a `data:image/(png|jpeg|webp|gif);base64,…` URL, or bare base64
* that decodes to an image's signature — the way an image gets through a terminal that cannot
* hand over a clipboard image (over SSH). The bytes; a reason it is refused (too large); or
* undefined when the text does not decode to an image — it is then ordinary pasted text. */
export function imageFromText(text: string): { mime: string; bytes: Uint8Array } | { error: string } | undefined {
let t = text.trim()
if (t.length < 24) return undefined
const url = /^data:image\/(?:png|jpeg|webp|gif);base64,/i.exec(t.slice(0, 40))
if (url) t = t.slice(url[0].length)
// Bare base64 is looked at only when it starts as an image would: PNG, JPEG, GIF, WebP.
else if (!/^(?:iVBORw0KGgo|\/9j\/|R0lGOD|UklGR)/.test(t)) return undefined
// Line breaks are a terminal's or a mail program's; anything else is not base64.
if (/[^A-Za-z0-9+/=\s]/.test(t)) return undefined
t = t.replace(/\s+/g, "")
if (Math.floor((t.length * 3) / 4) > MAX_PASTE_BYTES) return { error: `the pasted image is over ${MAX_PASTE_BYTES / 1e6} MB — copy the file over and use @path` }
const bytes = new Uint8Array(Buffer.from(t, "base64"))
const mime = sniffImage(bytes)
// Not an image after all (a data URL of something else, base64 that only began like one): it
// is text, and is pasted as text.
if (!mime) return undefined
return { mime, bytes }
}
export type ClipboardImage = { status: "read"; mime: string; bytes: Uint8Array } | { status: "empty" | "unsupported" | "too-large" }
type Env = Record<string, string | undefined>
/** The clipboard programs that can hand over an image here, in order: Wayland's, then X11's (the
* local display, or the one `ssh -X` forwards). */
export function clipboardCommands(env: Env = process.env, which: (cmd: string) => string | null = Bun.which): ((type: string) => string[])[] {
const out: ((type: string) => string[])[] = []
if (env.WAYLAND_DISPLAY && which("wl-paste")) out.push((type) => ["wl-paste", "--no-newline", "--type", type])
if (env.DISPLAY && which("xclip")) out.push((type) => ["xclip", "-selection", "clipboard", "-t", type, "-o"])
return out
}
async function runFor(cmd: string[], timeoutMs: number): Promise<Uint8Array | undefined> {
try {
const p = Bun.spawn(cmd, { stdin: "ignore", stdout: "pipe", stderr: "ignore", env: process.env })
const timer = setTimeout(() => p.kill(), timeoutMs)
try {
const out = new Uint8Array(await new Response(p.stdout).arrayBuffer())
return (await p.exited) === 0 ? out : undefined
} finally {
clearTimeout(timer)
}
} catch {
return undefined
}
}
/** The fallback: ask wl-paste or xclip for each kind of image in turn. */
async function clipboardImageByProgram(o: { env?: Env; which?: (cmd: string) => string | null; timeoutMs: number }): Promise<ClipboardImage> {
const commands = clipboardCommands(o.env, o.which)
if (!commands.length) return { status: "unsupported" }
for (const command of commands) {
for (const type of CLIPBOARD_TYPES) {
const out = await runFor(command(type), o.timeoutMs)
if (!out || !sniffImage(out)) continue
if (out.length > MAX_PASTE_BYTES) return { status: "too-large" }
return { status: "read", mime: sniffImage(out)!, bytes: out }
}
}
return { status: "empty" }
}
export interface HostClipboardLike {
read(o: { preferredTypes: readonly [string, ...string[]] }): Promise<{ status: string; representation?: { mimeType: string; bytes: Uint8Array } }>
dispose(): Promise<void>
}
/** An image on this machine's clipboard — PNG, JPEG, WebP or GIF; Linux (Wayland, X11), macOS and
* Windows through OpenTUI's host clipboard, with wl-paste / xclip where that is not available.
* Never blocks: everything is awaited. `host`: the clipboard to ask (tests); by default OpenTUI's. */
export async function clipboardImage(o: { env?: Env; which?: (cmd: string) => string | null; timeoutMs?: number; host?: () => HostClipboardLike | Promise<HostClipboardLike> } = {}): Promise<ClipboardImage> {
const timeoutMs = o.timeoutMs ?? 3000
let host: HostClipboardLike | undefined
let hostEmpty = false
try {
host = await (o.host ?? (async () => (await import("@opentui/core")).createHostClipboard({ timeoutMs, maxReadBytes: MAX_PASTE_BYTES }) as unknown as HostClipboardLike))()
const r = await host.read({ preferredTypes: CLIPBOARD_TYPES })
if (r.status === "read" && r.representation) {
// Believed by its bytes: a clipboard may call anything image/png.
const mime = sniffImage(r.representation.bytes)
if (mime) return { status: "read", mime, bytes: r.representation.bytes }
}
if (r.status === "limit-exceeded") return { status: "too-large" }
// Something that is not an image (text called image/png) is no image on the clipboard.
hostEmpty = r.status === "empty" || r.status === "read"
} catch {
// No host clipboard in this build or on this machine: the programs below.
} finally {
void host?.dispose().catch(() => {})
}
// The programs are asked as well when the host clipboard found nothing: over `ssh -X` the
// clipboard that matters is the forwarded X display's.
const byProgram = await clipboardImageByProgram({ env: o.env, which: o.which, timeoutMs })
return byProgram.status === "unsupported" && hostEmpty ? { status: "empty" } : byProgram
}
/** Pasted images are copies: those older than `days` go when the TUI starts. */
export function cleanPastedImages(dir: string, days = 7, now = Date.now()): number {
let gone = 0
let names: string[]
try {
names = readdirSync(dir)
} catch {
return 0
}
for (const name of names) {
if (!/^paste-[\w-]+\.(png|jpe?g|webp|gif)$/.test(name)) continue
const path = join(dir, name)
try {
if (now - statSync(path).mtimeMs > days * 86_400_000) {
rmSync(path)
gone++
}
} catch {}
}
return gone
}
+175
View File
@@ -0,0 +1,175 @@
// Display (harness spec 3.7.0, harness/display.md): what every client says about a tool call, the
// end of a reply and a number — the title, the states, the facts after the title. Pure: the TUI,
// the progress tracker and the ACP agent all read these.
import { LOOP, TOOL_SPECS } from "../harness.ts"
import { resolveCall } from "../tool/names.ts"
import { fillPrompt } from "../prompt/fill.ts"
import { duration } from "../duration.ts"
const D = LOOP.display
/** How a number is written: the plain format (no grouping, `.`) unless a client passes its own. */
export type NumberFormat = (n: number, decimals?: number) => string
export const plainNumber: NumberFormat = (n, decimals) => (decimals === undefined ? String(n) : n.toFixed(decimals))
/** A formatter for a locale (display.md §6): the platform's grouping and decimal mark. An unknown
* locale is the plain format. */
export function localeNumber(locale: string | undefined): NumberFormat {
if (!locale) return plainNumber
try {
const whole = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 })
const cache = new Map<number, Intl.NumberFormat>()
return (n, decimals) => {
if (decimals === undefined) return (Number.isInteger(n) ? whole : new Intl.NumberFormat(locale)).format(n)
let f = cache.get(decimals)
if (!f) cache.set(decimals, (f = new Intl.NumberFormat(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals })))
return f.format(n)
}
} catch {
return plainNumber
}
}
/** The locale a terminal runs in, as a BCP 47 tag: LC_ALL, then LC_NUMERIC, then LANG
* (`sk_SK.UTF-8` → `sk-SK`). `C`, `POSIX` and nothing at all are no locale: the plain format. */
export function terminalLocale(env: Record<string, string | undefined> = process.env): string | undefined {
const raw = env.LC_ALL || env.LC_NUMERIC || env.LANG
if (!raw) return undefined
const name = raw.split(/[.@]/)[0]!
if (!name || name === "C" || name === "POSIX") return undefined
const tag = name.replace(/_/g, "-")
try {
return Intl.getCanonicalLocales(tag)[0]
} catch {
return undefined
}
}
/** One line, cut to the title's length in code points (79 and an ellipsis). */
export function shortTitle(s: string | undefined): string | undefined {
if (!s) return undefined
const line = s.trim().split("\n")[0]!.trim()
if (!line) return undefined
const max = LOOP.progress.what_max
const points = [...line]
return points.length > max ? `${points.slice(0, max - 1).join("")}…` : line
}
/** The files a patch names: its `*** Add/Update/Delete File:` lines, else its `+++ ` lines. */
function patchFiles(patch: string): string[] {
const lines = patch.split("\n")
const named = lines.flatMap((l) => {
const head = D.title.patch_files.find((h) => l.startsWith(h))
return head ? [l.slice(head.length).trim()] : []
})
if (named.length) return named.filter(Boolean)
return lines
.filter((l) => l.startsWith("+++ "))
.map((l) => l.slice(4).split("\t")[0]!.trim().replace(/^b\//, ""))
.filter((f) => f && f !== "/dev/null")
}
/** A tool call's one short title (display.md §1), from its arguments alone: the same string in the
* transcript, as `what` of running_tool and as the link's tool_call title. */
export function callTitle(args: unknown): string | undefined {
if (!args || typeof args !== "object") return undefined
const a = args as Record<string, unknown>
if (Array.isArray(a.questions)) {
const headers = (a.questions as unknown[]).map((q) => (q && typeof q === "object" ? (q as { header?: unknown }).header : undefined)).filter((h): h is string => typeof h === "string" && h.trim() !== "")
const t = shortTitle(headers.map((h) => h.trim()).join(D.title.questions_join))
if (t) return t
}
if (typeof a.patch === "string") {
const t = shortTitle(patchFiles(a.patch).join(D.title.patch_join))
if (t) return t
}
for (const k of D.title.keys) {
const v = a[k]
if (typeof v === "string" && v.trim()) return shortTitle(v)
}
return undefined
}
export type CallState = "running" | "done" | "failed" | "denied"
/** A finished call's duration (display.md §2): tenths under a minute, then 1m 05s, 2h 03m. None
* for a call that is running or was denied, or whose time was not kept. */
export function callDuration(state: CallState, ms: number | undefined): string | undefined {
if (D.no_duration.includes(state) || ms === undefined || !Number.isFinite(ms)) return undefined
return duration(ms)
}
/** The lines a unified diff adds and removes, counted by its hunks (display.md §2): nothing
* outside a hunk counts, so a file header never does and a removed `-- x` line always does. */
export function diffCounts(diff: string): { added: number; removed: number } {
let added = 0
let removed = 0
let old = 0
let fresh = 0
for (const l of diff.split("\n")) {
if (old <= 0 && fresh <= 0) {
const m = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(l)
if (m) {
old = m[1] === undefined ? 1 : Number(m[1])
fresh = m[2] === undefined ? 1 : Number(m[2])
}
continue
}
if (l.startsWith("+")) {
added++
fresh--
} else if (l.startsWith("-")) {
removed++
old--
} else if (l.startsWith("\\")) continue
else {
old--
fresh--
}
}
return { added, removed }
}
const fill = (t: string, v: Record<string, string>) => fillPrompt(t, v)
/** `+3 −1` for an edit. */
export function changeText(c: { added: number; removed: number }, num: NumberFormat = plainNumber): string {
return fill(D.change, { added: num(c.added), removed: num(c.removed) })
}
/** The facts after a finished call's title (display.md §2): an edit's change, a command's exit
* code when it is not 0, a search's hits. */
export function callFacts(f: { block?: string; diff?: string; exit?: number | null; hits?: number }, num: NumberFormat = plainNumber): string[] {
const out: string[] = []
if (f.block === "edit" && f.diff) out.push(changeText(diffCounts(f.diff), num))
if (f.block === "shell" && typeof f.exit === "number" && f.exit !== 0) out.push(fill(D.exit, { code: String(f.exit) }))
if (f.block === "search" && typeof f.hits === "number") out.push(fill(f.hits === 1 ? D.hit : D.hits, { count: num(f.hits) }))
return out
}
/** Whether a tool's block is drawn as a call at all (display.md §3). */
export const drawnBlock = (block: string | undefined) => !D.not_drawn.includes(block ?? "tool")
/** What a finished call's result adds after its title in this client's transcript: the spec's
* facts where the block has them (display.md §2), else what the tool's own summary says beyond
* the title ("anything else an implementation knows"): the lines read, a job's state. */
export function resultFacts(block: string | undefined, title: string | undefined, result: { title?: string; meta?: Record<string, unknown> }, num: NumberFormat = plainNumber): string[] {
const meta = result.meta ?? {}
const facts = callFacts(
{ block, diff: typeof meta.diff === "string" ? meta.diff : undefined, exit: typeof meta.exit === "number" ? meta.exit : undefined, hits: typeof meta.hits === "number" ? meta.hits : undefined },
num,
)
// An edit says its change and a command that exited says its code (none for 0): nothing more.
if (facts.length || block === "edit" || (block === "shell" && typeof meta.exit === "number")) return facts
const said = result.title?.trim()
if (!said || said === title) return []
const cut = said.lastIndexOf(" · ")
if (cut >= 0) return [said.slice(cut + 3)]
if (title && said.startsWith(title)) return [said.slice(title.length).trim()].filter(Boolean)
return [said]
}
/** How a tool's call is read (its `block` in the spec), under its former names too; a tool the
* spec does not know (an MCP tool) is the generic block. */
export const blockOf = (name: string): string => TOOL_SPECS[resolveCall(name, {}).name]?.block ?? "tool"
+53 -2
View File
@@ -24,6 +24,7 @@ import { memoryResults, presentIds, ResultContext } from "./results.ts"
import { render } from "../plan/plan.ts"
import { personTexts } from "../team/subagents.ts"
import { ProgressTracker } from "./progress.ts"
import { callTitle } from "./display.ts"
import type { Verdict } from "../team/delegation.ts"
import { compactAsk, isNote, NO_CHANGING, noteFor, offeredFor, PREFIX_META, summaryOf, today, toldAt, unavailable, type Changing, type Kept, type Now, type Requirement, type Told } from "./prefix.ts"
@@ -137,6 +138,8 @@ const MAX_NUDGES = LOOP.nudges.max
const wrapUpText = (limit: string) => fillPrompt(LOOP.wrap_up.message, { limit })
/** The session_meta key the plan is kept under. */
export const PLAN_META = "plan"
/** How the session's last turn ended when it did not finish (display.md §4): `{ reason, error? }`. */
export const END_META = "ended"
export class Engine {
messages: Message[] = []
@@ -205,6 +208,24 @@ export class Engine {
constructor(readonly o: EngineOptions) {
this.progress = new ProgressTracker(o.bus)
// How a turn ended is kept with the session, so a reply that was stopped or failed says so
// again when the session is shown from the store (display.md §4).
let failure: string | undefined
o.bus.on((e) => {
if (e.type === "error") failure = e.message
if (e.type !== "done") return
const said = failure
failure = undefined
const id = this.sessionId
if (!this.o.store || !id) return
if (e.reason === "stop") return this.o.store.setMeta(id, END_META, null)
// Written once the turn's last message is in: `at` ties the end to the conversation as it
// stood, so an /undo, a rewind or a compaction that takes the turn away takes its end too
// (and a /redo that brings the turn back brings it back).
queueMicrotask(() => {
if (this.sessionId === id) this.o.store?.setMeta(id, END_META, { reason: e.reason, at: this.messages.length, ...(e.reason === "error" && said ? { error: said } : {}) })
})
})
this.mode = o.mode
this._effort = o.effort
this.model = o.model
@@ -353,6 +374,35 @@ export class Engine {
return new ResultContext(this.o.store && sessionId ? this.o.store.results(sessionId) : memoryResults(), () => presentIds(this.messages))
}
/** A refused call's arguments and title, for those who draw it: the arguments as a call that
* runs gets them — the tool found under its former names, `purpose` taken off, parsed by the
* tool's schema (its defaults and conversions) — and as the model wrote them only when they do
* not parse. */
private deniedTitle(call: ToolCallPart, toolMap: Map<string, Tool>): { args?: unknown; title?: string } {
let args: unknown
try {
const written: unknown = call.args.trim() ? JSON.parse(call.args) : {}
const resolved = resolveCall(call.name, written)
const tool = toolMap.get(resolved.name) ?? toolMap.get(call.name)
const own = tool ? splitPurpose(tool, resolved.raw).args : resolved.raw
const parsed = tool?.schema.safeParse(own)
args = parsed?.success ? parsed.data : own
} catch {
return {}
}
const title = callTitle(args)
return { args, ...(title ? { title } : {}) }
}
/** How this session's last turn ended, when it did not finish — from the store. */
storedEnd(): { reason: string; error?: string } | undefined {
if (!this.o.store || !this.sessionId) return undefined
const e = this.o.store.meta<{ reason?: unknown; error?: unknown; at?: unknown } | null>(this.sessionId, END_META)
// Only while the conversation still ends where that turn ended.
if (!e || typeof e.reason !== "string" || e.at !== this.messages.length) return undefined
return { reason: e.reason, ...(typeof e.error === "string" ? { error: e.error } : {}) }
}
/** The plan the store holds for this session, if any. */
private storedPlan(): Plan | undefined {
if (!this.o.store || !this.sessionId) return undefined
@@ -843,7 +893,7 @@ export class Engine {
const decided = await this.decide(call, toolMap, cut)
if ("result" in decided) {
results.set(call.id, decided.result)
if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output })
if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output, ...this.deniedTitle(call, toolMap) })
} else {
runnable.push({ call, ...decided })
argsOf.set(call.id, decided.args)
@@ -883,7 +933,8 @@ export class Engine {
for (const group of groups) {
await Promise.all(
group.map(async ({ call, tool, args, edited }) => {
bus.emit({ type: "tool_start", id: call.id, name: call.name, args })
const title = callTitle(args)
bus.emit({ type: "tool_start", id: call.id, name: call.name, args, ...(title ? { title } : {}) })
const t0 = performance.now()
let result: ToolResult
try {
+57 -27
View File
@@ -3,6 +3,7 @@
import { LOOP } from "../harness.ts"
import { fillPrompt } from "../prompt/fill.ts"
import { duration } from "../duration.ts"
import { callTitle, plainNumber, type NumberFormat } from "./display.ts"
const P = LOOP.progress
@@ -40,29 +41,28 @@ export const PHASES = P.phases as readonly Phase[]
const fill = (t: string, v: Record<string, string | number>) => fillPrompt(t, Object.fromEntries(Object.entries(v).map(([k, x]) => [k, String(x)])))
/** A call's short title as `what`: one line, at most what_max characters. */
export function shortWhat(s: string | undefined): string | undefined {
if (!s) return undefined
const line = s.split("\n")[0]!.trim()
if (!line) return undefined
return line.length > P.what_max ? `${line.slice(0, P.what_max - 1)}…` : line
/** An error or a reason as one line (progress.md §2: "one line"). */
export function oneLine(s: string | undefined): string | undefined {
const line = s?.trim().split("\n")[0]?.trim()
return line || undefined
}
/** The phase's text (progress.md §2), its fields filled; `now` for retrying's countdown. */
export function progressText(p: Progress, now = Date.now()): string {
/** The phase's text (progress.md §2), its fields filled; `now` for retrying's countdown; `num`
* how numbers are written — plain unless the client passes its locale's (display.md §6). */
export function progressText(p: Progress, now = Date.now(), num: NumberFormat = plainNumber): string {
const T = P.texts as Record<string, string>
switch (p.phase) {
case "queued":
return p.ahead !== undefined ? fill(T["queued.ahead"]!, { ahead: p.ahead }) : T.queued!
return p.ahead !== undefined ? fill(T["queued.ahead"]!, { ahead: num(p.ahead) }) : T.queued!
case "waiting_for_model":
return fill(T.waiting_for_model!, { model: p.model ?? "", reason: (P.reason as Record<string, string>)[p.reason ?? ""] ?? p.reason ?? "" })
case "loading_model":
return fill(T.loading_model!, { model: p.model ?? "" })
case "reading_prompt":
if (p.total === undefined || p.done === undefined || p.total <= 0) return T["reading_prompt.bare"]!
return fill(T.reading_prompt!, { done: p.done, total: p.total, percent: Math.floor((p.done * 100) / p.total) })
return fill(T.reading_prompt!, { done: num(p.done), total: num(p.total), percent: num(Math.floor((p.done * 100) / p.total)) })
case "writing":
return p.rate !== undefined && Number.isFinite(p.rate) ? fill(T.writing!, { rate: p.rate.toFixed(1) }) : T["writing.bare"]!
return p.rate !== undefined && Number.isFinite(p.rate) ? fill(T.writing!, { rate: num(p.rate, 1) }) : T["writing.bare"]!
case "running_tool":
return p.what ? fill(T.running_tool!, { tool: p.tool ?? "", what: p.what }) : fill(T["running_tool.bare"]!, { tool: p.tool ?? "" })
case "waiting_for_person": {
@@ -71,7 +71,7 @@ export function progressText(p: Progress, now = Date.now()): string {
return fill(T.waiting_for_person!, { what })
}
case "waiting_for_subagents":
return fill(T.waiting_for_subagents!, { running: p.running ?? 0 })
return fill(T.waiting_for_subagents!, { running: num(p.running ?? 0) })
case "retrying": {
const left = Math.max(0, (p.in ?? 0) - Math.floor((now - p.since) / 1000))
return fill(T.retrying!, { in: left, reason: p.reason ?? "" })
@@ -87,12 +87,27 @@ export function progressText(p: Progress, now = Date.now()): string {
/** The line a client draws (progress.md §3): the text and the time since it began, or the text
* alone for stopped and failed. */
export function progressLine(p: Progress, now = Date.now()): string {
const text = progressText(p, now)
export function progressLine(p: Progress, now = Date.now(), num: NumberFormat = plainNumber): string {
const text = progressText(p, now, num)
if ((P.no_elapsed as string[]).includes(p.phase)) return text
return fill(P.line, { text, elapsed: duration(now - p.since, true) })
}
/** The line that stays on a reply that did not finish (display.md §4): the text of `stopped` or
* `failed`, alone; nothing for a reply that finished, or a phase that is not an end. */
export function endLine(p: Progress | null | undefined, now = Date.now(), num: NumberFormat = plainNumber): string | undefined {
if (!p || !LOOP.display.end.includes(p.phase)) return undefined
return progressLine(p, now, num)
}
/** How a turn that did not finish ended, from the engine's `done` reason (and the error said
* before it): the progress whose line stays on the reply (display.md §4). */
export function endOf(reason: string, error?: string): Pick<Progress, "phase" | "reason"> | undefined {
if (reason === "stop") return undefined
if (reason === "error") return { phase: "failed", reason: oneLine(error) ?? "error" }
return { phase: "stopped", reason: reason === "cancelled" ? "person" : reason }
}
/** Whether two objects are the same phase for the same thing (so `since` is kept). */
export function samePhase(a: Progress | null | undefined, b: Omit<Progress, "since">): boolean {
if (!a || a.phase !== b.phase) return false
@@ -103,14 +118,6 @@ export function samePhase(a: Progress | null | undefined, b: Omit<Progress, "sin
return true
}
/** What a tool call does, in a line (`what` of running_tool): the command, the path, the query. */
export function callWhat(args: unknown): string | undefined {
if (!args || typeof args !== "object") return undefined
const a = args as Record<string, unknown>
for (const k of ["command", "path", "file_path", "pattern", "query", "url", "description", "name"]) if (typeof a[k] === "string" && a[k]) return shortWhat(a[k] as string)
return undefined
}
type BusLike = { on(fn: (e: any) => void): () => void; emit(e: any): void }
/** The progress of one engine, derived from the events it emits (progress.md §4), and said on its
@@ -121,6 +128,7 @@ export class ProgressTracker {
current: Progress | null = null
private rate: number | undefined
private running = new Map<string, Omit<Progress, "since">>()
private subagents = new Set<string>()
private lastEmit = 0
private pendingTimer: ReturnType<typeof setTimeout> | undefined
private error: string | undefined
@@ -189,6 +197,19 @@ export class ProgressTracker {
this.bus.emit({ type: "phase", progress: this.current ? { ...this.current } : null })
}
/** waiting_for_subagents with the count as it is now: the foreground task calls of this step,
* or every subagent of the session that is running, whichever is more. */
private counted(p: Omit<Progress, "since">): Omit<Progress, "since"> {
if (p.phase !== "waiting_for_subagents") return p
const calls = [...this.running.values()].filter((x) => x.phase === "waiting_for_subagents").length
return { ...p, running: Math.max(1, calls, this.subagents.size) }
}
/** The count changed while the phase holds: the same phase, its data anew (`since` kept). */
private recount() {
if (this.current?.phase === "waiting_for_subagents") this.set(this.counted({ phase: "waiting_for_subagents" }))
}
private on(e: any) {
switch (e.type) {
case "task":
@@ -213,22 +234,31 @@ export class ProgressTracker {
return
case "tool_start": {
const a = (e.args ?? {}) as Record<string, unknown>
const p: Omit<Progress, "since"> = e.name === "task" && a.background !== true ? { phase: "waiting_for_subagents", running: 1 } : { phase: "running_tool", tool: e.name, ...(callWhat(e.args) ? { what: callWhat(e.args) } : {}) }
// One title for a call (display.md §1): the event's, made when the call started.
const what: string | undefined = e.title ?? callTitle(e.args)
const p: Omit<Progress, "since"> = e.name === "task" && a.background !== true ? { phase: "waiting_for_subagents", running: 1 } : { phase: "running_tool", tool: e.name, ...(what ? { what } : {}) }
this.running.set(e.id, p)
if (this.running.size === 1) this.set(p)
if (this.running.size === 1) this.set(this.counted(p))
else this.recount()
return
}
case "tool_end": {
this.running.delete(e.id)
const next = this.running.values().next()
if (!next.done) this.set(next.value)
if (!next.done) this.set(this.counted(next.value))
return
}
case "job":
// The subagents working now, for waiting_for_subagents' count: this session's jobs.
if (e.job?.kind !== "subagent") return
if (e.state !== "end" && e.job.state === "running") this.subagents.add(e.job.id)
else this.subagents.delete(e.job.id)
return this.recount()
case "notice":
if (e.retry) this.set({ phase: "retrying", reason: shortWhat(e.retry.reason) ?? "", in: e.retry.in, ...(e.retry.attempt ? { attempt: e.retry.attempt } : {}) })
if (e.retry) this.set({ phase: "retrying", reason: oneLine(e.retry.reason) ?? "", in: e.retry.in, ...(e.retry.attempt ? { attempt: e.retry.attempt } : {}) })
return
case "error":
this.error = shortWhat(String(e.message ?? "")) ?? "error"
this.error = oneLine(String(e.message ?? "")) ?? "error"
return
case "done":
this.running.clear()
+33 -16
View File
@@ -10,7 +10,7 @@ import { COMMANDS, findCommand, type CommandCtx } from "./commands.ts"
import { Dialog, type DialogSpec } from "./components/dialog.tsx"
import { Messages } from "./components/messages.tsx"
import { PermissionPrompt } from "./components/permission.tsx"
import { copiedMessage, copyText } from "./clipboard.ts"
import { copiedMessage, copyText, isRemote } from "./clipboard.ts"
import { QuestionCard } from "./components/question.tsx"
import { PlanCard } from "./components/plancard.tsx"
import { PlanPanel } from "./components/plan.tsx"
@@ -18,7 +18,7 @@ import { JobView } from "./components/jobview.tsx"
import { SubagentView } from "./components/subagent.tsx"
import { Bus } from "../bus/index.ts"
import { FocusWatch, noticeSequence, noticeText } from "./notify.ts"
import { Prompt, type PaletteEntry } from "./components/prompt.tsx"
import { Prompt, type PaletteEntry, type PromptHandle } from "./components/prompt.tsx"
import { FileIndex } from "../project/files.ts"
import { attachmentsFor } from "../project/attach.ts"
import { customCommands, expandCommand, type CustomCommand } from "../project/commands.ts"
@@ -83,15 +83,20 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
// The finished-reply notice (notify.ts): a reply that ends, or an answer the agent waits for,
// while the terminal is not focused — the bell and a desktop notification naming the session.
const focus = new FocusWatch((ev, fn) => renderer.on(ev, fn))
/** Raw sequences to the terminal, and the OSC replies it sends back. */
const writeRaw = (seq: string) => {
const r = renderer as unknown as { writeOut?: (s: string) => void }
if (r.writeOut) r.writeOut(seq)
else process.stdout.write(seq)
}
const terminal = { write: writeRaw, subscribeOsc: (h: (sequence: string) => void) => renderer.subscribeOsc(h) }
const notice = (what: "finished" | "waiting" | "failed") => {
if (focus.focused || app.loaded.config.notify === false) return
const id = app.engine.sessionId
const title = id ? app.store?.session(id)?.title : undefined
const seq = noticeSequence(noticeText(title, what))
const r = renderer as unknown as { writeOut?: (s: string) => void }
try {
if (r.writeOut) r.writeOut(seq)
else process.stdout.write(seq)
writeRaw(seq)
} catch {}
}
app.bus.on((e) => e.type === "done" && e.reason !== "cancelled" && notice(e.reason === "error" ? "failed" : "finished"))
@@ -112,6 +117,10 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
})
let scroll: ScrollBoxRenderable | undefined
let input: TextareaRenderable | undefined
let box: PromptHandle | undefined
/** What is selected, as it is copied: a selection in the prompt box in full (a paste placeholder
* as what it stands for), anything else as it reads. */
const selectedText = (visible: string) => (visible && input?.hasSelection() && input.getSelectedText() === visible ? (box?.expandedSelection() ?? visible) : visible)
let quitArmed = 0
const dims = useTerminalDimensions()
@@ -208,9 +217,12 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
// Sent as words, never as a command: a transcript that starts with "/" or "!" is still speech.
if (voiceCfg?.submit === "send" && app.turns.steer(text)) return
if (voiceCfg?.submit === "send" && !busy()) return void send(text)
const now = input?.plainText ?? ""
input?.setText(now.trim() ? `${now.replace(/\s+$/, "")} ${text}` : text)
input?.gotoBufferEnd()
if (!input) return
// Added at the end, not by setting the whole text: that would turn a paste placeholder in
// the box into its bare label and lose what it stands for.
const now = input.plainText
input.gotoBufferEnd()
input.insertText(now.trim() && !/\s$/.test(now) ? ` ${text}` : text)
},
notice: (m, warn) => view.info(m, warn ? "warn" : undefined),
})
@@ -312,11 +324,14 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
* `attachFrom`: where @references are read from, when not all of `text` is the user's — an MCP
* server's prompt or a skill must not attach ~/.ssh/… by naming it. `given`: a prompt from the web
* UI, its attachments read already and its turn id its own. */
const send = (text: string, shown = text, attachFrom = text, given?: Pick<SharedPrompt, "extra" | "attachments" | "turnId">): Promise<string> => {
const send = (text: string, shown = text, attachFrom = text, given?: Pick<SharedPrompt, "extra" | "attachments" | "turnId">, drawn = shown): Promise<string> => {
voice.stopSpeaking()
const atts = given ? [] : attachmentsFor(attachFrom, app.engine.o.toolCtx, app.engine.model.spec.vision === true)
for (const a of atts) files.used(a.path)
view.user(shown)
// `drawn`: what this transcript shows — the box as it looked, a paste placeholder in place of
// its text. Only here: the session's title, the `prompt` event and everything a server
// mirrors get `shown`, which holds the words themselves.
view.user(drawn)
if (atts.length) view.info(`attached ${atts.map((a) => (a.image ? `${a.path} (image)` : a.text.includes("not attached") ? `${a.path} (not attached: ${/not attached: ([^)]*)/.exec(a.text)?.[1]})` : a.path)).join(", ")}`)
if (given?.attachments.length) view.info(`attached ${given.attachments.map((a) => a.name).join(", ")}`)
scroll?.scrollTo(scroll.scrollHeight)
@@ -334,7 +349,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
if (!left.length) return reason
const joined = left.join("\n\n")
if (reason === "cancelled") {
const now = input?.plainText.trim() ?? ""
const now = (box?.expanded() ?? input?.plainText ?? "").trim()
input?.setText(now ? `${joined}\n\n${now}` : joined)
input?.gotoBufferEnd()
view.info("stopped — what you sent meanwhile is back in the box")
@@ -435,7 +450,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
}
/** false: refused — the text stays in the box. */
const submit = (text: string): boolean | void => {
const submit = (text: string, shown?: string): boolean | void => {
const t = text.trim()
// Inside a subagent, what is typed is for it; commands are still the session's.
if (entered() && !t.startsWith("/")) return void sendToJob(t)
@@ -467,7 +482,9 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
// While a task runs, a message joins it: at the next step, or after it (queue).
if (app.turns.steer(t)) return
if (busy()) return (view.info("still working — esc stops the current reply", "warn"), false)
void send(t)
// `shown`: the box as it looked, paste placeholders in place of what they stand for — for
// this transcript alone.
void send(t, t, t, undefined, shown?.trim() || t)
}
/** The messages waiting to go in, for ↑ in the box. */
@@ -563,7 +580,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
key.preventDefault()
} else if (key.ctrl && key.name === "c" && (key.shift || renderer.hasSelection)) {
// Ctrl+Shift+C (where the terminal passes it on), or Ctrl+C over a selection: copy it.
const sel = renderer.getSelection()?.getSelectedText() ?? ""
const sel = selectedText(renderer.getSelection()?.getSelectedText() ?? "")
if (sel) copy(sel)
else flash("nothing selected — drag over text, or /copy the last reply")
renderer.clearSelection()
@@ -620,7 +637,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
else flash(m.text)
}
const onSelection = (sel: { getSelectedText(): string } | null) => {
const text = sel?.getSelectedText() ?? ""
const text = selectedText(sel?.getSelectedText() ?? "")
if (text.trim()) copy(text)
}
renderer.on("selection", onSelection)
@@ -663,7 +680,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
<Spinner />
</Show>
<Queued />
<Prompt focused={() => !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} />
<Prompt focused={() => !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} handle={(h) => (box = h)} remote={() => isRemote(renderer as never)} terminal={terminal} note={(text, warn) => (warn ? view.info(text, "warn") : text.length > 60 ? view.info(text) : flash(text))} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} />
<StatusBar mode={mode} model={model} effort={effort} branch={branch()} voice={voiceStatus} flash={flashText} remote={() => (rev(), share.label())} spend={spend} team={teamWord} />
</box>
<Show when={dialog()}>
+3 -1
View File
@@ -5,6 +5,8 @@
// machine itself, the system clipboard through wl-copy / xclip / xsel / pbcopy. VTE terminals
// (GNOME Terminal, LXTerminal, Tilix) take neither OSC 52 nor synchronized output.
import { num } from "./locale.ts"
export interface ClipboardRenderer {
readonly capabilities: { readonly remote: boolean; readonly osc52_support: "supported" | "unsupported" | "unknown" } | null
copyToClipboardOSC52(text: string): boolean
@@ -55,7 +57,7 @@ export function copyText(r: ClipboardRenderer, text: string, env: Env = process.
* here (its probe often answers "unknown" and copies anyway — LXTerminal does), so a copy that
* went out is not second-guessed. Only one that could go nowhere says how to copy instead. */
export function copiedMessage(n: number, c: Copied): { text: string; warn: boolean } {
const what = `${n.toLocaleString("en")} character${n === 1 ? "" : "s"}`
const what = `${num(n)} character${n === 1 ? "" : "s"}`
if (c.via.length) return { text: `copied ${what}`, warn: false }
return { text: `could not copy ${what}: hold Shift while you drag to select with the terminal itself, then Ctrl+Shift+C (or set mouse: false in config.yaml)`, warn: true }
}
+1 -1
View File
@@ -562,7 +562,7 @@ export const COMMANDS: Command[] = [
if (other(id)) return c.view.info(`that session is in ${store.session(id)?.root} — resume it there (lembas -c, /sessions)`, "warn")
const why = await (c.share?.release(id) ?? Promise.resolve(undefined))
if (why) return c.view.info(`not resumed: ${why}`, "warn")
c.view.load(c.app.resume(id))
c.view.load(c.app.resume(id), c.app.engine.storedEnd())
c.view.info(`resumed ${id}`)
},
})
+39 -22
View File
@@ -5,31 +5,17 @@ import { estimateTokens } from "../../provider/tokens.ts"
import { useTui } from "../context.ts"
import type { Item } from "../state.ts"
import { clipDiff } from "../diffclip.ts"
import { TOOL_SPECS } from "../../harness.ts"
import { resolveCall } from "../../tool/names.ts"
import { blockOf, callDuration, callTitle, drawnBlock, type CallState } from "../../session/display.ts"
import { num } from "../locale.ts"
import { splitPrototypes } from "../../prototype/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`). */
const undrawn = (name: string) => {
const block = TOOL_SPECS[resolveCall(name, {}).name]?.block
return block === "plan" || block === "hidden"
}
const undrawn = (name: string) => !drawnBlock(blockOf(name))
const FILETYPES: Record<string, string> = { ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript", mjs: "javascript", md: "markdown", zig: "zig" }
export const filetypeOf = (diff: string) => FILETYPES[/^\+\+\+ \S*\.(\w+)/m.exec(diff)?.[1] ?? ""]
/** The one-line summary of a call before its result says more, e.g. the command or the path. */
function argSummary(args: unknown): string {
if (!args || typeof args !== "object") return ""
const a = args as Record<string, unknown>
if (Array.isArray(a.questions)) return (a.questions as { header?: string }[]).map((q) => q.header).filter(Boolean).join(" · ") || "asking"
if (Array.isArray(a.phases)) return String(a.title ?? "").slice(0, 120)
if (typeof a.patch === "string") return [...a.patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1]).join(", ")
const v = a.description ?? a.command ?? a.path ?? a.pattern ?? a.id ?? ""
return String(v).split("\n")[0]!.slice(0, 120)
}
function UserMessage(p: { item: Extract<Item, { kind: "user" }> }) {
const { theme } = useTui()
return (
@@ -95,7 +81,7 @@ function Reasoning(p: { item: Extract<Item, { kind: "reasoning" }> }) {
})
const tokens = () => {
const n = p.item.tokens ?? estimateTokens(p.item.text)
return `${p.item.tokens === undefined ? "~" : ""}${n.toLocaleString("en")} token${n === 1 ? "" : "s"}`
return `${p.item.tokens === undefined ? "~" : ""}${num(n)} token${n === 1 ? "" : "s"}`
}
const dots = () => ".".repeat(1 + (Math.floor((now() - p.item.started) / 400) % 3))
const line = () => (p.item.streaming ? `Thinking${dots()}` : p.item.ms !== undefined ? `Thought for ${duration(p.item.ms)} · ${tokens()}` : `Thought · ${tokens()}`)
@@ -124,8 +110,15 @@ function ToolLine(p: { item: Extract<Item, { kind: "tool" }> }) {
const { theme, view } = useTui()
const c = () => theme().colors
const emoji = () => (p.item.status === "denied" ? theme().icons.denied : (theme().toolEmoji[p.item.name] ?? (p.item.name.startsWith("mcp__") ? theme().icons.mcp : theme().icons.other)))
const title = () => p.item.title ?? argSummary(p.item.args)
const time = () => (p.item.status === "running" ? "…" : p.item.ms !== undefined ? duration(p.item.ms) : "")
// One title for a call, in every state (display.md §1); what its result adds comes after it.
const title = () => p.item.title ?? callTitle(p.item.args) ?? ""
const state = (): CallState => (p.item.status === "error" ? "failed" : p.item.status)
/** After the title: the facts, a failure's or a refusal's first line, and how long it took —
* never for a call that is running (a mark) or was denied (it did not run). */
const after = () => {
if (state() === "running") return "…"
return [...(p.item.facts ?? []), ...(p.item.note ? [p.item.note] : []), ...[callDuration(state(), p.item.ms)].filter((x): x is string => !!x)].join(" · ")
}
const tail = () => (p.item.output ?? "").trimEnd().split("\n").slice(-12).join("\n")
// Short in the transcript, whole with ctrl+o; always a diff the renderer can parse.
const shown = () => (view.state.expandTools ? { diff: p.item.diff ?? "", hidden: 0 } : clipDiff(p.item.diff ?? "", 24))
@@ -135,8 +128,8 @@ function ToolLine(p: { item: Extract<Item, { kind: "tool" }> }) {
<span style={{ fg: c().dim }}>{theme().branding.toolPrefix} </span>
{emoji()}{" "}
<span style={{ fg: p.item.status === "denied" ? c().warn : c().label, attributes: p.item.status === "denied" ? TextAttributes.STRIKETHROUGH : 0 }}>{p.item.name.padEnd(6)}</span>{" "}
<span style={{ fg: p.item.status === "error" ? c().error : p.item.status === "denied" ? c().warn : c().text }}>{title()}</span>{" "}
<span style={{ fg: c().dim }}>{time()}</span>
<span style={{ fg: p.item.status === "error" ? c().error : p.item.status === "denied" ? c().warn : c().text }}>{title()}</span>
<span style={{ fg: c().dim }}>{after() ? `${title() && after() !== "…" ? " · " : " "}${after()}` : ""}</span>
<Show when={p.item.status === "error"}>
<span style={{ fg: c().error }}> ✗</span>
</Show>
@@ -261,6 +254,27 @@ function ErrorLine(p: { item: Extract<Item, { kind: "error" }> }) {
)
}
/** How a reply that did not finish ended: the spec's line, kept on the reply (display.md §4). */
function EndLine(p: { item: Extract<Item, { kind: "end" }> }) {
const { theme } = useTui()
const fg = () => (p.item.failed ? theme().colors.error : theme().colors.muted)
return (
<box paddingLeft={1} marginTop={p.item.failed ? 1 : 0} flexDirection="column">
<text fg={fg()} wrapMode="word">
{p.item.failed ? "✗ " : "■ "}
{p.item.line}
</text>
<Show when={p.item.more}>
<box paddingLeft={2}>
<text fg={fg()} wrapMode="word">
{p.item.more}
</text>
</box>
</Show>
</box>
)
}
export function Messages() {
const { view } = useTui()
return (
@@ -285,6 +299,9 @@ export function Messages() {
<Match when={item.kind === "diff"}>
<DiffBlock item={item as Extract<Item, { kind: "diff" }>} />
</Match>
<Match when={item.kind === "end"}>
<EndLine item={item as Extract<Item, { kind: "end" }>} />
</Match>
<Match when={item.kind === "error"}>
<ErrorLine item={item as Extract<Item, { kind: "error" }>} />
</Match>
+179 -40
View File
@@ -1,14 +1,16 @@
import type { PasteEvent, TextareaRenderable } from "@opentui/core"
import { existsSync, mkdirSync } from "node:fs"
import { RGBA, SyntaxStyle, type PasteEvent, type TextareaRenderable } from "@opentui/core"
import { existsSync } from "node:fs"
import { join } from "node:path"
import { paths } from "../../config/paths.ts"
import { clipboardImage, isImage } from "../../project/image.ts"
import { cleanPastedImages, clipboardImage, CLIPBOARD_TYPES, imageFromText, imageWhole, isImage, savePastedImage, sniffImage, type ClipboardImage } from "../../project/image.ts"
import { kittyClipboardLikely, kittyReadImage, type KittyRead, type OscTerminal } from "../kitty-clipboard.ts"
import { escapeMention } from "../../project/attach.ts"
import fuzzysort from "fuzzysort"
import { createSignal, For, Show } from "solid-js"
import { createMemo, createSignal, For, onCleanup, Show } from "solid-js"
import type { FileIndex } from "../../project/files.ts"
import { useTui } from "../context.ts"
import { History } from "../history.ts"
import { imageLabel, pasteLabel, Placeholders, type BoxSnapshot } from "../paste.ts"
export interface PaletteEntry {
name: string
@@ -21,8 +23,36 @@ export interface PaletteEntry {
interface Popup {
kind: "command" | "file"
items: { label: string; detail: string; value: string }[]
/** Where the replaced token starts in the text. */
from: number
/** How many characters before the cursor the replaced token takes. */
token: number
}
/** Where pasted images are kept until they are old (cleanPastedImages). */
const CLIP_DIR = join(paths.state, "clipboard")
/** Sent with a clipboard read so a terminal that asks the person can remember the answer for
* this run of the program. */
const CLIPBOARD_PASSWORD = crypto.randomUUID()
/** Said when an image paste over SSH found nothing: the ways that do work. */
export const REMOTE_IMAGE_HINT = "no image reached this terminal over SSH — paste it as a data URL (data:image/png;base64,…), copy the file here and use @path, or attach it to this chat in the web, Desktop or Android app"
/** What the app may ask of the box beyond its text. */
export interface PromptHandle {
/** The box's text with every paste placeholder replaced by what it stands for. */
expanded(): string
/** What is selected in the box, in full; undefined when the selection is not in the box. */
expandedSelection(): string | undefined
}
/** The offset (in the textarea's columns) at which the text before it is `index` characters long. */
function offsetAt(area: TextareaRenderable, index: number): number {
let lo = 0
let hi = area.cursorOffset
while (lo < hi) {
const mid = (lo + hi) >> 1
if (area.getTextRange(0, mid).length < index) lo = mid + 1
else hi = mid
}
return lo
}
/** The input: enter sends; shift+enter / alt+enter / ctrl+j add a line; ↑↓ on the edge lines walk
@@ -33,9 +63,17 @@ export function Prompt(p: {
busy: () => boolean
commands: () => PaletteEntry[]
files?: FileIndex
/** false: refused (busy, unknown command) — the text stays in the box. */
onSubmit: (text: string) => boolean | void
/** false: refused (busy, unknown command) — the text stays in the box. `shown`: what the box
* said, when a paste placeholder made it differ from the text that is sent. */
onSubmit: (text: string, shown?: string) => boolean | void
ref?: (r: TextareaRenderable) => void
handle?: (h: PromptHandle) => void
/** Whether the terminal is on another machine (SSH): its clipboard is not this machine's. */
remote?: () => boolean
/** The terminal, for asking it for its clipboard (kitty's protocol). */
terminal?: OscTerminal
/** A short line for the person (nothing on the clipboard, why an image was not taken). */
note?: (text: string, warn?: boolean) => void
/** The messages waiting to go in: how many, take one out, put it back. */
queue?: { count(): number; take(index: number): string | undefined; putBack(index: number, text: string): void }
/** A burst of ↑/↓ that was a mouse wheel: scroll the transcript `lines` up (-1) or down (1). */
@@ -44,9 +82,21 @@ export function Prompt(p: {
* itself binds ctrl+b (move left) and would keep the key. */
onBackground?: () => void
}) {
const { theme } = useTui()
const { theme, app } = useTui()
const c = () => theme().colors
const history = new History()
// How a paste placeholder looks: the theme's label colour, on the menu's background.
const style = createMemo((prev?: SyntaxStyle) => {
prev?.destroy()
return SyntaxStyle.fromStyles({ "extmark.paste": { fg: RGBA.fromHex(c().label), bg: RGBA.fromHex(c().menu) } })
})
onCleanup(() => style().destroy())
let marks: Placeholders | undefined
// Pasted images are copies; old ones go when the box is made.
cleanPastedImages(CLIP_DIR)
/** The box's text as it is sent: placeholders replaced by what they stand for. */
const full = () => marks?.expanded() ?? area?.plainText ?? ""
const pasteWhole = () => app.loaded.config.paste === "full"
const [popup, setPopup] = createSignal<Popup>()
const [sel, setSel] = createSignal(0)
let dismissedAt: string | undefined
@@ -58,7 +108,7 @@ export function Prompt(p: {
// held down, repeats 25 ms apart or more. A burst scrolls the transcript, and what its first
// arrow did to the box is undone (otherwise the wheel walks the prompt history).
const BURST_MS = 12
let burst: { dir: "up" | "down"; at: number; undo?: { text: string; cursor: number; history: ReturnType<History["mark"]>; pulled: typeof pulled; queue?: () => void } } | undefined
let burst: { dir: "up" | "down"; at: number; undo?: { box: BoxSnapshot; history: ReturnType<History["mark"]>; pulled: typeof pulled; queue?: () => void } } | undefined
/** ↑/↓ on an edge line: the waiting messages first (↑ newest to oldest), then history. */
const walk = (dir: "up" | "down", t: string): string | undefined => {
@@ -89,21 +139,21 @@ export function Prompt(p: {
const text = area.plainText
if (text === dismissedAt) return setPopup(undefined)
dismissedAt = undefined
const before = text.slice(0, area.cursorOffset)
const before = area.getTextRange(0, area.cursorOffset)
if (/^\/[\w:-]*$/.test(text)) {
const q = text.slice(1)
const all = p.commands()
const hits = q ? fuzzysort.go(q, all, { key: "name", limit: 8 }).map((h) => h.obj) : all.slice(0, 8)
setPopup(
hits.length
? { kind: "command", from: 0, items: hits.map((cmd) => ({ label: `/${cmd.name}`, detail: `${cmd.args ? cmd.args + " " : ""}${cmd.description}${cmd.source && cmd.source !== "builtin" ? ` (${cmd.source})` : ""}`, value: cmd.name })) }
? { kind: "command", token: text.length, items: hits.map((cmd) => ({ label: `/${cmd.name}`, detail: `${cmd.args ? cmd.args + " " : ""}${cmd.description}${cmd.source && cmd.source !== "builtin" ? ` (${cmd.source})` : ""}`, value: cmd.name })) }
: undefined,
)
} else {
const m = p.files ? /(?:^|\s)@([^\s]*)$/.exec(before) : null
if (m) {
const hits = p.files!.search(m[1]!)
setPopup(hits.length ? { kind: "file", from: before.length - m[1]!.length, items: hits.map((f) => ({ label: f, detail: "", value: f })) } : undefined)
setPopup(hits.length ? { kind: "file", token: m[1]!.length, items: hits.map((f) => ({ label: f, detail: "", value: f })) } : undefined)
} else setPopup(undefined)
}
setSel(0)
@@ -122,25 +172,72 @@ export function Prompt(p: {
setPopup(undefined)
return run
}
const text = area.plainText
const cursor = area.cursorOffset
// Escaped as the expander reads it back: a space or a # in a name.
const insert = escapeMention(item.value) + (item.value.endsWith("/") ? "" : " ")
area.setText(text.slice(0, pop.from) + insert + text.slice(cursor))
area.cursorOffset = pop.from + insert.length
// The token is replaced where it stands (not by setting the whole text, which would drop
// every paste placeholder in the box).
const from = offsetAt(area, area.getTextRange(0, cursor).length - pop.token)
if (from < cursor) area.setSelection(from, cursor)
area.insertText(insert)
// A directory keeps the list open, one level down.
queueMicrotask(compute)
return false
}
/** An image on the clipboard becomes an @reference to a saved copy. */
const pasteClipboardImage = (): boolean => {
const dir = join(paths.state, "clipboard")
mkdirSync(dir, { recursive: true })
const saved = clipboardImage(join(dir, `paste-${Date.now()}.png`))
if (!saved || !area) return false
area.insertText(`@${saved} `)
return true
/** An image file goes into the box as `[Image N]`; what is sent is its @reference. */
const insertImage = (path: string) => {
if (!area || !marks) return
const ref = `@${escapeMention(path)}`
if (pasteWhole()) return area.insertText(`${ref} `)
marks.insert({ kind: "image", label: imageLabel(marks.nextImage()), content: ref })
}
/** An image on the clipboard becomes a saved copy and a placeholder for it. Awaited, never
* blocking: the box stays usable while a clipboard (or the person, asked by their terminal)
* takes its time, and the placeholder goes in where the cursor is when the image arrives.
*
* Over SSH this machine's clipboard is not the person's. What can still work: the X display
* `ssh -X` forwards, and a terminal that hands its clipboard over itself (kitty). When neither
* does, one line says what does. */
let reading = false
// While the terminal sends its clipboard, nothing typed or pasted reaches the box: what would
// arrive is a reply that came apart on the way (kitty-clipboard.ts), and it is counted.
let held: number | undefined
const holdInput = () => {
held = 0
return () => {
const n = held ?? 0
held = undefined
return n
}
}
const pasteClipboardImage = async () => {
if (reading || !area) return
reading = true
try {
const remote = p.remote?.() ?? false
let r: ClipboardImage | KittyRead = { status: "unsupported" }
if (!remote) r = await clipboardImage()
else if (process.env.DISPLAY) r = await clipboardImage({ env: { DISPLAY: process.env.DISPLAY } })
// The terminal's own clipboard (kitty), only where it was turned on: see kitty-clipboard.ts.
if (r.status !== "read" && remote && p.terminal && app.loaded.config.kitty_clipboard === true && kittyClipboardLikely()) {
p.note?.("asking the terminal for the image on its clipboard…")
r = await kittyReadImage(
{ ...p.terminal, holdInput },
{ types: CLIPBOARD_TYPES, password: CLIPBOARD_PASSWORD, name: "LLeMbas CLI", whole: (bytes) => { const mime = sniffImage(bytes); return mime && imageWhole(bytes, mime) ? mime : undefined } },
)
}
if (r.status === "read") return insertImage(savePastedImage(CLIP_DIR, r.bytes, r.mime))
if (r.status === "garbled") return p.note?.("the image did not arrive whole from the terminal (the connection stalled) — nothing was pasted; try again, or paste it as a data URL or use @path", true)
if (r.status === "too-large") return p.note?.("the image on the clipboard is too large to paste — save it and use @path", true)
if (r.status === "denied") return p.note?.("the terminal did not allow reading its clipboard", true)
p.note?.(remote ? REMOTE_IMAGE_HINT : r.status === "unsupported" ? "no clipboard to read an image from here (install wl-clipboard or xclip), or use @path" : "no image on the clipboard")
} catch (e) {
p.note?.(`the clipboard could not be read: ${(e as Error).message.split("\n")[0]}`, true)
} finally {
reading = false
}
}
/** A pasted path to an image (dragged from a file manager: quoted, escaped or file://) → @path. */
@@ -156,16 +253,37 @@ export function Prompt(p: {
const onPaste = (e: PasteEvent) => {
if (!area) return
if (held !== undefined) {
held++
return e.preventDefault()
}
const text = new TextDecoder().decode(e.bytes).replace(/\r\n/g, "\n").replace(/\r/g, "\n")
// Some terminals hand over an image-only clipboard as an empty bracketed paste.
if (!text.trim()) {
// Some terminals hand over an image-only clipboard as an empty bracketed paste. (A paste of
// white space — a newline — is a paste of white space.)
if (!text) {
e.preventDefault()
pasteClipboardImage()
void pasteClipboardImage()
return
}
if (!text.trim()) return
// An image pasted as text — a data URL, or base64 of one: the way through a terminal that
// cannot hand over a clipboard image (over SSH).
const data = imageFromText(text)
if (data) {
e.preventDefault()
if ("error" in data) return p.note?.(data.error, true)
return insertImage(savePastedImage(CLIP_DIR, data.bytes, data.mime))
}
const img = imagePath(text)
e.preventDefault()
area.insertText(img ? `@${img.includes(" ") ? img.replace(/ /g, "\\ ") : img} ` : text)
if (img) return insertImage(img)
// A long paste is a placeholder (`paste: full` shows it whole); the same paste again, right
// after its placeholder, opens it.
const content = text.replace(/\s+$/, "")
const label = pasteWhole() ? undefined : pasteLabel(content)
if (!label || !marks) return area.insertText(text)
if (marks.expandAtCursor(content)) return
marks.insert({ kind: "text", label, content })
}
/** What undoes one ↑/↓ step through the queue: the message now in the box goes back, and the one
@@ -178,16 +296,23 @@ export function Prompt(p: {
const submit = () => {
if (!area) return
const value = area.plainText
// What is sent is the text in full; what the transcript shows is what the box showed.
marks?.repair()
const value = full()
const shown = area.plainText
if (!value.trim()) return
const box = marks?.snapshot()
history.add(value)
pulled = undefined
area.setText("")
marks?.clear()
setPopup(undefined)
// Cleared first: a command may put text of its own there (/undo puts the prompt back). A
// refusal puts what was typed back, unless something else has been put there.
if (p.onSubmit(value) === false && !area.plainText) {
area.setText(value)
// refusal puts what was typed back — placeholders and all — unless something else has been
// put there.
if (p.onSubmit(value, shown !== value ? shown : undefined) === false && !area.plainText) {
if (box && marks) marks.restore(box)
else area.setText(value)
area.gotoBufferEnd()
}
}
@@ -211,13 +336,16 @@ export function Prompt(p: {
<textarea
ref={(r: TextareaRenderable) => {
area = r
marks = new Placeholders(r, () => style().getStyleId("extmark.paste") ?? undefined)
p.ref?.(r)
p.handle?.({ expanded: full, expandedSelection: () => marks?.expandedSelection() })
}}
focused={p.focused()}
flexGrow={1}
minHeight={1}
maxHeight={8}
wrapMode="word"
syntaxStyle={style()}
textColor={c().prompt}
focusedTextColor={c().prompt}
cursorColor={c().accent}
@@ -229,13 +357,24 @@ export function Prompt(p: {
{ name: "return", meta: true, action: "newline" },
{ name: "j", ctrl: true, action: "newline" },
]}
onContentChange={compute}
onContentChange={() => {
// After this change has settled: a placeholder that lost part of its label goes whole.
queueMicrotask(() => marks?.repair())
compute()
}}
onCursorChange={compute}
onSubmit={submit}
onPaste={onPaste}
onKeyDown={(e) => {
if (!area) return
if (e.ctrl && e.name === "v" && pasteClipboardImage()) return e.preventDefault()
if (held !== undefined) {
held++
return e.preventDefault()
}
if (e.ctrl && e.name === "v" && !e.shift && !e.meta) {
void pasteClipboardImage()
return e.preventDefault()
}
if (e.ctrl && e.name === "b" && p.onBackground) {
p.onBackground()
return e.preventDefault()
@@ -260,7 +399,8 @@ export function Prompt(p: {
}
}
if (e.name !== "up" && e.name !== "down") return
const t = area.plainText
// In full: a draft with a placeholder in it comes back from history as its text.
const t = full()
const now = performance.now()
if (burst && burst.dir === e.name && now - burst.at < BURST_MS && p.onWheel) {
// The second arrow of a burst: it was the wheel. Undo the first, scroll for both.
@@ -270,8 +410,7 @@ export function Prompt(p: {
u.queue?.()
pulled = u.pulled
history.restore(u.history)
area.setText(u.text)
area.cursorOffset = u.cursor
marks!.restore(u.box)
burst.undo = undefined
lines = 2
}
@@ -279,10 +418,10 @@ export function Prompt(p: {
p.onWheel(e.name === "up" ? -1 : 1, lines)
return e.preventDefault()
}
const before = { text: t, cursor: area.cursorOffset, history: history.mark(), pulled: pulled && { ...pulled } }
const before = { box: marks!.snapshot(), history: history.mark(), pulled: pulled && { ...pulled } }
burst = { dir: e.name, at: now, undo: before }
const atFirst = !t.slice(0, area.cursorOffset).includes("\n")
const atLast = !t.slice(area.cursorOffset).includes("\n")
const atFirst = !area.getTextRange(0, area.cursorOffset).includes("\n")
const atLast = !area.getTextRange(area.cursorOffset, 0x3fffffff).includes("\n")
if ((e.name === "up" && atFirst) || (e.name === "down" && atLast)) {
const countBefore = p.queue?.count()
const next = walk(e.name, t)
+14 -2
View File
@@ -3,6 +3,8 @@ import { duration } from "../../duration.ts"
import { progressLine } from "../../session/progress.ts"
import { useTui } from "../context.ts"
import { fmtTokens } from "./status.tsx"
import { LOOP } from "../../harness.ts"
import { num } from "../locale.ts"
/** "reading the prompt 64% · 90k of 140k · ~2m left": the server's own count (llama.cpp's
* return_progress). The time left is guessed from the reading so far, once there is enough of it;
@@ -34,6 +36,15 @@ export function Spinner() {
const sp = () => theme().spinner
const pick = (list: string[], every: number) => list[Math.floor(tick() / every) % list.length] ?? ""
const elapsed = () => (tick(), view.state.busySince ? duration(Date.now() - view.state.busySince, true) : "0s")
// One clock on the line. The spec's line carries the phase's own (`Thinking · 12s`,
// progress.md §3); the turn's time is said beside it only once it is another number — the turn
// has gone through more than this phase — and then as "12s of 1m 05s", not as a second clock.
const ofTurn = () => {
const s = view.state
if (!s.now || (LOOP.progress.no_elapsed as string[]).includes(s.now.phase) || !s.busySince) return ""
const turn = Date.now() - s.busySince
return Math.floor(turn / 1000) - Math.floor((Date.now() - s.now.since) / 1000) >= 2 ? ` of ${duration(turn, true)}` : ""
}
const tokens = () => {
tick()
const { n, estimated } = view.taskTokens()
@@ -49,7 +60,7 @@ export function Spinner() {
const reading = s.now.phase === "reading_prompt" && s.progress
const now = reading ? { ...s.now, done: s.progress!.done, total: s.progress!.total } : s.now
const eta = reading ? etaOf(s.progress!) : ""
return `${progressLine(now)}${eta ? ` · ${eta}` : ""}`
return `${progressLine(now, Date.now(), num)}${ofTurn()}${eta ? ` · ${eta}` : ""}`
}
if (s.preparing) return `preparing ${s.preparing}`
if (s.phase === "waiting" && s.progress) return reading(s.progress)
@@ -64,7 +75,8 @@ export function Spinner() {
<span style={{ fg: theme().colors.accent }}>{pick(sp().frames, 1)} </span>
<span style={{ fg: theme().colors.muted }}>{what()}{view.state.now ? " · " : "… "}</span>
<span style={{ fg: theme().colors.dim }}>
{view.state.now ? `turn ${elapsed()}` : elapsed()} · {tokens()} · esc to stop
{view.state.now ? "" : `${elapsed()} · `}
{tokens()} · esc to stop
</span>
</text>
</box>
+1 -1
View File
@@ -72,7 +72,7 @@ export function Boot(p: { options: TuiOptions; onQuit: () => void; onReload?: (a
else if (id)
void releaseForResume(id).then((why) => {
if (why) fresh(`not resumed: ${why}`)
else view.load(a.resume(id))
else view.load(a.resume(id), a.engine.storedEnd())
})
else fresh("no earlier session in this project to continue")
}
+175
View File
@@ -0,0 +1,175 @@
// Reading an image from the clipboard through the terminal itself: kitty's clipboard protocol
// (OSC 5522). It is the one way a clipboard image crosses an SSH connection — the terminal on the
// person's own machine reads its clipboard and sends the bytes down the same connection the
// keystrokes use. OSC 52 carries text only.
//
// → ESC ] 5522 ; type=read[:id=…:pw=…:name=…] ; base64("image/png image/jpeg") ST
// ← ESC ] 5522 ; type=read:status=OK ST
// ← ESC ] 5522 ; type=read:status=DATA:mime=base64(mime) ; base64(chunk) ST (chunks ≤ 4096 bytes)
// ← ESC ] 5522 ; type=read:status=DONE ST
// ← ESC ] 5522 ; type=read:status=EPERM | ENOSYS | EBUSY ST (instead of OK)
//
// The request "." lists the kinds on the clipboard and needs no permission; the read itself the
// terminal asks the person about (once, when it remembers the password sent with it).
//
// What can go wrong on the way, and what is done about it. OpenTUI's input parser gives up on an
// escape sequence that stops arriving for about 20 ms and hands what it has on as typed keys. A
// reply that stalls inside a packet — an SSH connection does that — therefore loses that packet,
// and its base64 would be typed into the prompt box. So while a read is under way the box's input
// is held (`holdInput`): nothing of a reply reaches it, and any input that turned up during the
// read means a packet was lost — the read fails, said in a line, and nothing is saved. What
// arrives is also checked as an image by its own structure (the caller's `whole`). A read can
// therefore fail on a slow connection, but never saves a broken image or types into the box;
// because it can fail, the whole path is off unless `kitty_clipboard: true` is set.
const OSC = "\x1b]5522;"
const ST = "\x1b\\"
export interface OscTerminal {
/** Write to the terminal. */
write(data: string): void
/** Every OSC sequence the terminal sends, whole. Returns what unsubscribes. */
subscribeOsc(handler: (sequence: string) => void): () => void
/** Hold the prompt box's input until the function returned is called; that call says how many
* inputs (keys, pastes) arrived meanwhile and were dropped. */
holdInput?(): () => number
}
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64")
/** One OSC 5522 sequence as its metadata and payload; undefined for any other sequence. */
export function parse5522(sequence: string): { meta: Record<string, string>; payload: string } | undefined {
if (!sequence.startsWith(OSC)) return undefined
const body = sequence.slice(OSC.length).replace(/(?:\x1b\\|\x07)$/, "")
const cut = body.indexOf(";")
const head = cut === -1 ? body : body.slice(0, cut)
const meta: Record<string, string> = {}
for (const pair of head.split(":")) {
const eq = pair.indexOf("=")
if (eq > 0) meta[pair.slice(0, eq)] = pair.slice(eq + 1)
}
return { meta, payload: cut === -1 ? "" : body.slice(cut + 1) }
}
/** Whether the terminal is one that speaks the protocol: kitty (also through `ssh`, which carries
* TERM), and not inside a multiplexer that would swallow the replies. */
export function kittyClipboardLikely(env: Record<string, string | undefined> = process.env): boolean {
if (env.TMUX || env.STY || env.ZELLIJ) return false
return !!env.KITTY_WINDOW_ID || /kitty/i.test(env.TERM ?? "")
}
/** `garbled`: part of the reply was lost on the way, or what arrived is not a whole image. */
export type KittyRead = { status: "read"; mime: string; bytes: Uint8Array } | { status: "unsupported" | "empty" | "denied" | "busy" | "too-large" | "timed-out" | "garbled" }
interface ReadOptions {
types: readonly string[]
/** How long the terminal has to answer the listing: one that does not know the protocol says nothing. */
listTimeoutMs?: number
/** How long the read may take — the person may be looking at the terminal's permission question. */
readTimeoutMs?: number
maxBytes?: number
/** Sent with the read so the terminal can remember the person's answer for this program. */
password?: string
name?: string
/** The kind of image these bytes are when they are a whole one (project/image.ts `sniffImage`
* and `imageWhole`); undefined when they are not. What is read is believed only by this. */
whole?: (bytes: Uint8Array) => string | undefined
}
/** One request and its replies: resolves with the data packets by kind, or how it failed. */
function request(term: OscTerminal, meta: string, payload: string, id: string, timeoutMs: number, maxBytes: number): Promise<{ status: "done"; data: Map<string, Uint8Array[]> } | { status: Exclude<KittyRead["status"], "read" | "empty"> }> {
return new Promise((resolve) => {
const data = new Map<string, Uint8Array[]>()
let total = 0
const finish = (r: Parameters<typeof resolve>[0]) => {
clearTimeout(timer)
off()
resolve(r)
}
const timer = setTimeout(() => finish({ status: "timed-out" }), timeoutMs)
const off = term.subscribeOsc((sequence) => {
const p = parse5522(sequence)
// Another request's reply (a different id) is not ours; a terminal that sends no id back is believed.
if (!p || p.meta.type !== "read" || (p.meta.id !== undefined && p.meta.id !== id)) return
switch (p.meta.status) {
case "OK":
return
case "DATA": {
const mime = Buffer.from(p.meta.mime ?? "", "base64").toString("utf8")
const chunk = new Uint8Array(Buffer.from(p.payload, "base64"))
total += chunk.length
if (total > maxBytes) return finish({ status: "too-large" })
const list = data.get(mime) ?? []
list.push(chunk)
data.set(mime, list)
return
}
case "DONE":
return finish({ status: "done", data })
case "EPERM":
return finish({ status: "denied" })
case "EBUSY":
return finish({ status: "busy" })
default:
return finish({ status: "unsupported" })
}
})
try {
term.write(`${OSC}type=read:id=${id}${meta};${b64(payload)}${ST}`)
} catch {
finish({ status: "unsupported" })
}
})
}
const join = (chunks: Uint8Array[]) => {
const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0))
let at = 0
for (const c of chunks) {
out.set(c, at)
at += c.length
}
return out
}
let serial = 0
/** An image from the clipboard of the terminal's own machine: the kinds are listed first (no
* permission needed, and a terminal that does not answer does not speak the protocol), then the
* first of `types` that is there is read. */
export async function kittyReadImage(term: OscTerminal, o: ReadOptions): Promise<KittyRead> {
const release = term.holdInput?.()
let r: KittyRead
try {
r = await read(term, o)
} finally {
// Input during the read is a reply that came apart: whatever was put together is not trusted.
if ((release?.() ?? 0) > 0) return { status: "garbled" }
}
return r
}
async function read(term: OscTerminal, o: ReadOptions): Promise<KittyRead> {
const maxBytes = o.maxBytes ?? 20_000_000
const id = `lembas${process.pid}.${++serial}`
const listed = await request(term, "", ".", id, o.listTimeoutMs ?? 1500, 65_536)
// Silence within the listing's time is a terminal that does not know OSC 5522.
if (listed.status === "timed-out") return { status: "unsupported" }
if (listed.status !== "done") return { status: listed.status }
const kinds = new Set(
[...listed.data.values()]
.flatMap((chunks) => Buffer.from(join(chunks)).toString("utf8").split(/\s+/))
.filter(Boolean),
)
const type = o.types.find((t) => kinds.has(t))
if (!type) return { status: "empty" }
const auth = o.password && o.name ? `:pw=${b64(o.password)}:name=${b64(o.name)}` : ""
const got = await request(term, auth, type, `${id}r`, o.readTimeoutMs ?? 30_000, maxBytes)
if (got.status !== "done") return { status: got.status }
const chunks = got.data.get(type) ?? [...got.data.values()][0]
if (!chunks?.length) return { status: "empty" }
const bytes = join(chunks)
if (!o.whole) return { status: "read", mime: type, bytes }
// By its bytes, not by what it was asked for or called.
const mime = o.whole(bytes)
return mime ? { status: "read", mime, bytes } : { status: "garbled" }
}
+5
View File
@@ -0,0 +1,5 @@
// Numbers as the person's locale writes them (harness display.md §6): the terminal's LC_ALL,
// LC_NUMERIC or LANG. With none of them, or the C locale, English grouping as before.
import { localeNumber, terminalLocale } from "../session/display.ts"
export const num = localeNumber(terminalLocale() ?? "en")
+189
View File
@@ -0,0 +1,189 @@
// Paste placeholders in the prompt box. A long paste is shown as `[Pasted text 40 lines]` and an
// image as `[Image 2]`; what is sent is the text itself, or the `@path` of the saved image. The
// placeholder is an OpenTUI extmark over the label (virtual: the cursor steps over it and one
// backspace removes it whole), and the content is kept here, by the extmark's id.
//
// Offsets in the textarea are display columns, not string indices (a wide character is two), so
// nothing here slices `plainText` by an offset: text is taken with `getTextRange`.
import type { TextareaRenderable } from "@opentui/core"
/** A paste at least this many lines long is shown as a placeholder… */
export const PASTE_LINES = 3
/** …or longer than this many characters. */
export const PASTE_CHARS = 150
/** The placeholder a pasted text is shown as, or undefined when it is short enough to show whole. */
export function pasteLabel(text: string): string | undefined {
const lines = text.split("\n").length
if (lines >= PASTE_LINES) return `[Pasted text ${lines} lines]`
const chars = [...text].length
return chars > PASTE_CHARS ? `[Pasted text ${chars} chars]` : undefined
}
export const imageLabel = (n: number) => `[Image ${n}]`
/** The number the next image gets: one after the highest among `labels`. */
export function nextImageNumber(labels: string[]): number {
let max = 0
for (const l of labels) {
const m = /^\[Image (\d+)\]$/.exec(l)
if (m) max = Math.max(max, Number(m[1]))
}
return max + 1
}
export interface Placeholder {
label: string
/** What is sent in its place. */
content: string
kind: "text" | "image"
}
/** The box as it can be put back: its text, and where each placeholder was. */
export interface BoxSnapshot {
text: string
cursor: number
marks: { start: number; end: number; item: Placeholder }[]
}
type Area = Pick<TextareaRenderable, "plainText" | "cursorOffset" | "insertText" | "getTextRange" | "extmarks" | "setText" | "setSelection" | "getSelection" | "hasSelection" | "deleteSelection">
/** Beyond any text a prompt box holds: `getTextRange` clamps it to the end. */
const END = 0x3fffffff
export class Placeholders {
private items = new Map<number, Placeholder>()
private repairing = false
private typeId: number
constructor(
private area: Area,
private styleId?: () => number | undefined,
) {
this.typeId = area.extmarks.registerType("lembas-paste")
}
/** The placeholders in the box now, in order. One deleted is gone from here; an undo that
* brings its label back brings it back (the extmark returns under the same id). */
live(): { start: number; end: number; item: Placeholder }[] {
return this.area.extmarks
.getAllForTypeId(this.typeId)
.flatMap((m) => {
const item = this.items.get(m.id)
// A label that was edited into something else no longer stands for its content.
return item && this.area.getTextRange(m.start, m.end) === item.label ? [{ start: m.start, end: m.end, item }] : []
})
.sort((a, b) => a.start - b.start)
}
get any(): boolean {
return this.items.size > 0 && this.live().length > 0
}
/** Put a placeholder at the cursor — in place of what is selected — with a space after it. */
insert(item: Placeholder) {
this.area.insertText(`${item.label} `)
// Where it went is read off the cursor after the insert, not before it: with a selection
// the text goes in at the selection's start, wherever the cursor was. A label is ASCII, so
// its width is its length.
const end = this.area.cursorOffset - 1
this.mark(end - item.label.length, end, item)
}
/** A placeholder is one thing: when part of its label has been deleted (a selection that cut
* into it, a kill to the end of the line), the rest of the label goes too — never a stump of
* it left as text, with what it stood for silently gone. Returns how many were removed. */
repair(): number {
if (this.repairing || !this.items.size) return 0
this.repairing = true
let removed = 0
try {
// From the end, so removing one does not move those before it.
const broken = this.area.extmarks
.getAllForTypeId(this.typeId)
.filter((m) => this.items.has(m.id) && this.area.getTextRange(m.start, m.end) !== this.items.get(m.id)!.label)
.sort((a, b) => b.start - a.start)
for (const m of broken) {
const cursor = this.area.cursorOffset
this.area.extmarks.delete(m.id)
if (m.end > m.start) {
this.area.setSelection(m.start, m.end)
this.area.deleteSelection()
this.area.cursorOffset = cursor <= m.start ? cursor : Math.max(m.start, cursor - (m.end - m.start))
}
removed++
}
} finally {
this.repairing = false
}
return removed
}
private mark(start: number, end: number, item: Placeholder) {
const id = this.area.extmarks.create({ start, end, virtual: true, typeId: this.typeId, ...(this.styleId?.() !== undefined ? { styleId: this.styleId!() } : {}) })
this.items.set(id, item)
}
/** The next image's number: after the highest in the box. */
nextImage(): number {
return nextImageNumber(this.live().map((m) => m.item.label))
}
/** The text between two offsets with every placeholder inside them replaced by its content. */
expandedRange(from: number, to: number): string {
let out = ""
let at = from
for (const m of this.live()) {
if (m.start < from || m.end > to) continue
out += this.area.getTextRange(at, m.start) + m.item.content
at = m.end
}
return out + this.area.getTextRange(at, to)
}
/** What the box says, in full: every placeholder replaced by its content. */
expanded(): string {
return this.items.size ? this.expandedRange(0, END) : this.area.plainText
}
/** What is selected in the box, in full — undefined when nothing in the box is selected. */
expandedSelection(): string | undefined {
if (!this.area.hasSelection()) return undefined
const sel = this.area.getSelection()
if (!sel || sel.start === sel.end) return undefined
return this.expandedRange(Math.min(sel.start, sel.end), Math.max(sel.start, sel.end))
}
/** The one gesture that opens a placeholder: pasting the same text again with the cursor where
* the first paste left it — directly after the placeholder, or after the one space that was
* inserted with it — and nothing selected. The placeholder (and that space) becomes the text
* itself. Anywhere else, and after anything typed in between, the same paste is a second copy. */
expandAtCursor(content: string): boolean {
if (this.area.hasSelection()) return false
const cursor = this.area.cursorOffset
const m = this.live().find((x) => x.item.kind === "text" && x.item.content === content && (x.end === cursor || (x.end + 1 === cursor && this.area.getTextRange(x.end, cursor) === " ")))
if (!m) return false
for (const e of this.area.extmarks.getAllForTypeId(this.typeId)) if (e.start === m.start && e.end === m.end) this.area.extmarks.delete(e.id)
this.area.setSelection(m.start, cursor)
this.area.insertText(content)
return true
}
snapshot(): BoxSnapshot {
return { text: this.area.plainText, cursor: this.area.cursorOffset, marks: this.live() }
}
/** Put the box back as it was, placeholders and all. (`setText` drops every extmark.) */
restore(s: BoxSnapshot) {
this.area.setText(s.text)
this.items.clear()
for (const m of s.marks) this.mark(m.start, m.end, m.item)
this.area.cursorOffset = s.cursor
}
/** The box was emptied or given other text: nothing is a placeholder any more. */
clear() {
this.items.clear()
this.area.extmarks.clear()
}
}
+55 -13
View File
@@ -17,6 +17,11 @@ import { splitPrototypes, titleFor, type PrototypeKind } from "../prototype/fenc
import { savePrototype } from "../prototype/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"
import { endLine, endOf, type Progress } from "../session/progress.ts"
import { num } from "./locale.ts"
const resultFacts = (name: string, title: string | undefined, result: { title?: string; meta?: Record<string, unknown> }) => factsOf(blockOf(name), title, result, num)
export type Item =
/** `mid`: sent while the agent worked, and given to it at a step boundary. `machine`: the harness
@@ -31,7 +36,15 @@ export type Item =
name: string
args: unknown
status: "running" | "done" | "error" | "denied"
/** The call's one short title (harness display.md §1), from its arguments: the same from
* its start to its end. */
title?: string
/** What its result adds after the title: `+3 −1`, `exit 2`, `14 hits`, the lines read. */
facts?: string[]
/** A failed call's error, or why a call was denied: its first line. */
note?: string
/** A `!` command the person ran themselves: not a call of the turn. */
own?: boolean
ms?: number
output?: string
diff?: string
@@ -45,6 +58,9 @@ export type Item =
| { kind: "notice"; id: string; text: string; level: "info" | "warn" }
| { kind: "diff"; id: string; title: string; patch: string }
| { kind: "error"; id: string; text: string }
/** How a reply that did not finish ended: the spec's line (`Stopped: by you`, `Failed: …`),
* and for an error with more than one line, the rest of it. */
| { kind: "end"; id: string; line: string; failed: boolean; more?: string }
export type Phase = "idle" | "waiting" | "thinking" | "writing" | "tools"
@@ -132,6 +148,15 @@ const byRunning = (a: JobInfo, b: JobInfo) => Number(b.state === "running") - Nu
let seq = 0
const nextId = () => `i${++seq}`
/** The item that ends a reply which did not finish; none for one that did. */
function endItem(reason: string, error?: string): Extract<Item, { kind: "end" }> | undefined {
const end = endOf(reason, error)
const line = end && endLine({ ...end, since: 0 } as Progress, 0, num)
if (!end || !line) return undefined
const more = end.phase === "failed" ? error?.trim().split("\n").slice(1).join("\n").trim() : undefined
return { kind: "end", id: nextId(), line, failed: end.phase === "failed", ...(more ? { more } : {}) }
}
export function createView(bus: Bus) {
const [state, set] = createStore<ViewState>({ items: [], phase: "idle", busySince: 0, showReasoning: false, expandTools: false, queued: { texts: [], mode: "steer" }, jobs: [] })
let stepStart = 0
@@ -139,6 +164,8 @@ export function createView(bus: Bus) {
// streaming now, counted as it arrives so the number moves before the step's usage comes in.
// Not in the store: the spinner reads them on its own tick.
let inTask = false
/** The error of the turn that is ending, until its `done` draws it. */
let failure: string | undefined
let taskTokens = 0
let liveChars = 0
const startTask = () => {
@@ -231,7 +258,7 @@ export function createView(bus: Bus) {
set(
produce((s) => {
settle(s)
s.items.push({ kind: "tool", id: e.id, name: e.name, args: e.args, status: "running" })
s.items.push({ kind: "tool", id: e.id, name: e.name, args: e.args, status: "running", title: e.title ?? callTitle(e.args) })
s.phase = "tools"
s.preparing = undefined
}),
@@ -244,7 +271,9 @@ export function createView(bus: Bus) {
produce((it) => {
if (it.kind !== "tool") return
it.status = e.result.isError ? "error" : "done"
it.title = e.result.title ?? (e.result.isError ? e.result.output.split("\n")[0] : undefined)
it.facts = resultFacts(it.name, it.title, e.result)
// A failure that says nothing beside its title says its first line.
if (e.result.isError && !it.facts.length) it.note = e.result.output.trim().split("\n")[0]
it.ms = e.ms
it.output = e.result.output
it.diff = typeof e.result.meta?.diff === "string" ? (e.result.meta.diff as string) : undefined
@@ -256,7 +285,7 @@ export function createView(bus: Bus) {
)
break
case "tool_denied":
set(produce((s) => void s.items.push({ kind: "tool", id: e.id, name: e.name, args: undefined, status: "denied", title: e.reason.split("\n")[0] })))
set(produce((s) => void s.items.push({ kind: "tool", id: e.id, name: e.name, args: e.args, status: "denied", title: e.title ?? callTitle(e.args), note: e.reason.split("\n")[0] })))
break
case "retract":
set(produce((s) => void s.items.splice(stepStart)))
@@ -323,7 +352,8 @@ export function createView(bus: Bus) {
set(produce((s) => void s.items.push({ kind: "notice", id: nextId(), text: e.message, level: "warn" })))
break
case "error":
set(produce((s) => void s.items.push({ kind: "error", id: nextId(), text: e.message })))
// Said once, as the line that ends the reply (`Failed: …`), when the turn is done.
failure = e.message
break
case "done":
set(
@@ -332,10 +362,14 @@ export function createView(bus: Bus) {
s.phase = "idle"
s.preparing = undefined
s.progress = undefined
if (e.reason === "cancelled") s.items.push({ kind: "notice", id: nextId(), text: "cancelled", level: "info" })
if (e.reason === "steps") s.items.push({ kind: "notice", id: nextId(), text: "stopped at the step limit", level: "warn" })
// A call still running when the turn ended never got its result: failed, not spinning.
// (Not the person's own `!command`, which is no part of the turn and runs on.)
for (const it of s.items) if (it.kind === "tool" && it.status === "running" && !it.jobId && !it.own) it.status = "error"
const end = endItem(e.reason, failure)
if (end) s.items.push(end)
}),
)
failure = undefined
break
}
})
@@ -432,17 +466,17 @@ export function createView(bus: Bus) {
/** A `!` command the user ran: shown like a tool call, without touching the phase. */
shellStart(command: string): string {
const id = nextId()
set(produce((s) => void s.items.push({ kind: "tool", id, name: "bash", args: { command }, status: "running", title: `! ${command.split("\n")[0]}` })))
set(produce((s) => void s.items.push({ kind: "tool", id, name: "bash", args: { command }, status: "running", title: `! ${command.split("\n")[0]}`, own: true })))
return id
},
shellEnd(id: string, r: { output: string; title?: string; isError?: boolean }, ms: number) {
shellEnd(id: string, r: { output: string; title?: string; isError?: boolean; meta?: Record<string, unknown> }, ms: number) {
set(
"items",
(it) => it.kind === "tool" && it.id === id,
produce((it) => {
if (it.kind !== "tool") return
it.status = r.isError ? "error" : "done"
it.title = `${it.title} · ${r.title?.split(" · ").pop() ?? ""}`
it.facts = resultFacts("bash", undefined, r)
it.output = r.output
it.ms = ms
}),
@@ -472,10 +506,11 @@ export function createView(bus: Bus) {
toggleTools() {
set("expandTools", (v) => !v)
},
/** Show a stored conversation. */
load(messages: Message[]) {
/** Show a stored conversation. `ended`: how its last turn ended, when it did not finish. */
load(messages: Message[], ended?: { reason: string; error?: string }) {
const items: Item[] = []
const tools = new Map<string, Extract<Item, { kind: "tool" }>>()
const answered = new Set<string>()
for (const m of messages) {
if (m.role === "user" && m.parts[0]?.type === "text" && m.parts[0].text === CONTINUE_PROMPT)
items.push({ kind: "user", id: nextId(), text: "↻ continue" })
@@ -501,20 +536,27 @@ export function createView(bus: Bus) {
try {
args = JSON.parse(p.args)
} catch {}
const t: Extract<Item, { kind: "tool" }> = { kind: "tool", id: p.id, name: p.name, args, status: "done" }
const t: Extract<Item, { kind: "tool" }> = { kind: "tool", id: p.id, name: p.name, args, status: "done", title: callTitle(args) }
tools.set(p.id, t)
items.push(t)
}
}
} else {
const t = tools.get(m.callId)
answered.add(m.callId)
if (t) {
t.status = m.isError ? "error" : "done"
t.output = m.content
t.title = m.content.split("\n")[0]!.slice(0, 100)
// A stored call keeps its title (its arguments are stored); its duration and facts were not.
if (m.isError) t.note = m.content.trim().split("\n")[0]!.slice(0, 100)
}
}
}
// A stored call whose result never came (the turn was stopped, the process ended) failed:
// it is not drawn as done (display.md §2).
for (const [id, t] of tools) if (!answered.has(id)) t.status = "error"
const end = ended ? endItem(ended.reason, ended.error) : undefined
if (end) items.push(end)
set({ items, usage: undefined, used: undefined })
},
}
+31 -3
View File
@@ -126,7 +126,7 @@ test("an approval is asked of the client, and its answer decides", async () => {
expect(done.status).toBe("completed")
expect(done.content[0].content.text).toContain("approved-run")
await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "again" }] })
const refused = updates.find((u) => u.sessionUpdate === "tool_call_update" && u.toolCallId === "t2")
const refused = updates.find((u) => u.sessionUpdate === "tool_call" && u.toolCallId === "t2")
expect(refused.status).toBe("failed")
expect(asked).toBe(2)
})
@@ -269,7 +269,7 @@ test("the terminal: a real shell through the link, only where remote.terminal sa
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"])
await expect(off.c.request("_lembas/terminal/open", { cwd: root })).rejects.toThrow("remote.terminal is off")
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 })
expect(init._meta.lembas.capabilities).toContain("terminal")
@@ -330,11 +330,39 @@ test("an approval nobody answers is a denial", async () => {
const { c, updates } = await client({ roots: [root], maxMode: "manual", approvalTimeoutMs: 50, requireTrust: true }, () => new Promise(() => {}))
const s: any = await c.request("session/new", { cwd: root })
await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "x" }] })
const u = updates.find((x) => x.sessionUpdate === "tool_call_update" && x.toolCallId === "t1")
// Refused, not run (spec 3.7.0 display.md): the call is announced once, failed and marked
// denied, under its one title — not as an update of a call no client was told about.
expect(updates.some((x) => x.sessionUpdate === "tool_call_update" && x.toolCallId === "t1")).toBe(false)
const u = updates.find((x) => x.sessionUpdate === "tool_call" && x.toolCallId === "t1")
expect(u.status).toBe("failed")
expect(u.rawInput).toEqual({ command: "echo never", description: "x" })
expect(u._meta.lembas.denied).toBe(true)
expect(u.title).toBe("echo never")
expect(fake.requests[1].messages.at(-1).content).toContain("Nobody answered")
})
test("a tool call's title over the link is the call's short title, and its result does not change it", async () => {
fake = fakeProvider([
{ chunks: [toolCall(0, "t1", "bash", JSON.stringify({ command: "echo one\necho two", description: "Say two things" })), toolCall(1, "t2", "job_list", "{}")] },
{ chunks: [delta({ content: "ok" })] },
])
config(fake.url, "mode: auto\n")
const root = project()
const { c, updates, events } = await client({ roots: [root], maxMode: "auto", approvalTimeoutMs: 50, requireTrust: true })
const s: any = await c.request("session/new", { cwd: root })
await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "x" }] })
const call = updates.find((x) => x.sessionUpdate === "tool_call" && x.toolCallId === "t1")
expect(call.title).toBe("echo one")
// A call with nothing to title it by goes by its tool's name.
expect(updates.find((x) => x.sessionUpdate === "tool_call" && x.toolCallId === "t2").title).toBe("job_list")
const done = updates.find((x) => x.sessionUpdate === "tool_call_update" && x.toolCallId === "t1")
expect(done.status).toBe("completed")
expect(done.title).toBeUndefined()
// The same title on the engine's own event, and as `what` of the progress.
expect(events.find((e: any) => e.type === "tool_start" && e.id === "t1").title).toBe("echo one")
expect(events.find((e: any) => e.type === "phase" && e.progress?.phase === "running_tool").progress.what).toBe("echo one")
})
test("the link dials out with the token, says hello, is driven, and stops when refused", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "linked reply" })] }])
const root = project()
+247
View File
@@ -0,0 +1,247 @@
// Images that reach the prompt box other than as a file: the clipboard (OpenTUI's host clipboard,
// wl-paste / xclip behind it), text that is an image (a data URL, base64), and the terminal's own
// clipboard through kitty's OSC 5522.
import { expect, test } from "bun:test"
import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { cleanPastedImages, clipboardCommands, clipboardImage, imageFromText, imageWhole, MAX_PASTE_BYTES, savePastedImage, sniffImage } from "../src/project/image.ts"
import { kittyClipboardLikely, kittyReadImage, parse5522, type OscTerminal } from "../src/tui/kitty-clipboard.ts"
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64")
const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10]), Buffer.from("JFIF\0"), Buffer.alloc(16)])
const GIF = Buffer.concat([Buffer.from("GIF89a"), Buffer.alloc(16)])
const WEBP = Buffer.concat([Buffer.from("RIFF"), Buffer.from([4, 0, 0, 0]), Buffer.from("WEBPVP8 "), Buffer.alloc(8)])
test("an image is known by its bytes", () => {
expect(sniffImage(PNG)).toBe("image/png")
expect(sniffImage(JPEG)).toBe("image/jpeg")
expect(sniffImage(GIF)).toBe("image/gif")
expect(sniffImage(WEBP)).toBe("image/webp")
expect(sniffImage(Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'/>"))).toBeUndefined()
expect(sniffImage(Buffer.from("RIFF....WAVEfmt "))).toBeUndefined()
expect(sniffImage(new Uint8Array(3))).toBeUndefined()
})
test("pasted text that is an image: a data URL, base64 with line breaks, bare base64", () => {
const b64 = PNG.toString("base64")
expect(imageFromText(`data:image/png;base64,${b64}`)).toEqual({ mime: "image/png", bytes: new Uint8Array(PNG) })
// What it is called does not decide what it is.
expect(imageFromText(` data:image/jpeg;base64,${b64}\n`)).toMatchObject({ mime: "image/png" })
expect(imageFromText(`data:image/jpeg;base64,${JPEG.toString("base64")}`)).toMatchObject({ mime: "image/jpeg" })
// Wrapped at 76 columns, as base64(1) and mail programs write it.
const wrapped = b64.replace(/(.{20})/g, "$1\n")
expect(imageFromText(wrapped)).toMatchObject({ mime: "image/png" })
expect(imageFromText(`data:image/gif;base64,${GIF.toString("base64")}`)).toMatchObject({ mime: "image/gif" })
expect(imageFromText(WEBP.toString("base64"))).toMatchObject({ mime: "image/webp" })
})
test("pasted text that is not an image stays text — a data URL of something else too; only one too large is refused", () => {
expect(imageFromText("hello there, this is a perfectly ordinary sentence")).toBeUndefined()
// Starts as a PNG would, but is prose.
expect(imageFromText("iVBORw0KGgo is how a PNG starts in base64, did you know?")).toBeUndefined()
// Base64 of something else.
expect(imageFromText(Buffer.from("just some bytes, nothing more than that").toString("base64"))).toBeUndefined()
expect(imageFromText("data:text/plain;base64,aGVsbG8gd29ybGQsIGhlbGxvIHdvcmxk")).toBeUndefined()
expect(imageFromText(`data:image/svg+xml;base64,${Buffer.from("<svg/>".repeat(8)).toString("base64")}`)).toBeUndefined()
expect(imageFromText(`data:image/png;base64,${Buffer.from("not an image at all, only text").toString("base64")}`)).toBeUndefined()
const huge = `data:image/png;base64,${"A".repeat(Math.ceil((MAX_PASTE_BYTES * 4) / 3) + 8)}`
expect(imageFromText(huge)).toMatchObject({ error: expect.stringContaining("over 20 MB") })
})
test("the clipboard: the host clipboard's image, believed by its bytes — JPEG too", async () => {
let disposed = 0
const host = (status: string, bytes?: Uint8Array, mimeType = "image/png") => () => ({
read: async (o: { preferredTypes: readonly string[] }) => {
expect(o.preferredTypes).toEqual(["image/png", "image/jpeg", "image/webp", "image/gif"])
return { status, ...(bytes ? { representation: { mimeType, bytes } } : {}) }
},
dispose: async () => void disposed++,
})
const none = { env: {}, which: () => null }
expect(await clipboardImage({ ...none, host: host("read", JPEG, "image/png") })).toEqual({ status: "read", mime: "image/jpeg", bytes: JPEG })
expect(await clipboardImage({ ...none, host: host("empty") })).toEqual({ status: "empty" })
expect(await clipboardImage({ ...none, host: host("unsupported") })).toEqual({ status: "unsupported" })
expect(await clipboardImage({ ...none, host: host("limit-exceeded") })).toEqual({ status: "too-large" })
// Text on the clipboard handed over as an "image" is not one.
expect(await clipboardImage({ ...none, host: host("read", Buffer.from("plain text, not a picture")) })).toEqual({ status: "empty" })
// A host clipboard that cannot even be made (no native library): the programs, here none.
expect(
await clipboardImage({
...none,
host: () => {
throw new Error("no native clipboard")
},
}),
).toEqual({ status: "unsupported" })
expect(disposed).toBe(5)
})
test("the clipboard: where the host clipboard has nothing, xclip on the display there is (ssh -X)", async () => {
expect(clipboardCommands({}, () => "/usr/bin/x").length).toBe(0)
expect(clipboardCommands({ DISPLAY: "localhost:10.0" }, () => "/usr/bin/x").map((c) => c("image/png")[0])).toEqual(["xclip"])
expect(clipboardCommands({ WAYLAND_DISPLAY: "wayland-0", DISPLAY: ":0" }, () => "/usr/bin/x").map((c) => c("image/png")[0])).toEqual(["wl-paste", "xclip"])
expect(clipboardCommands({ DISPLAY: ":0" }, () => null)).toEqual([])
// A stand-in xclip that has a JPEG and no PNG.
const bin = mkdtempSync(join(tmpdir(), "lembas-clip-"))
writeFileSync(join(bin, "pic.jpg"), JPEG)
writeFileSync(join(bin, "xclip"), `#!/bin/sh\ncase "$*" in *image/jpeg*) cat "${bin}/pic.jpg";; *) exit 1;; esac\n`)
chmodSync(join(bin, "xclip"), 0o755)
const path = process.env.PATH
process.env.PATH = `${bin}:${path}`
try {
const empty = () => ({ read: async () => ({ status: "empty" }), dispose: async () => {} })
const r = await clipboardImage({ env: { DISPLAY: "localhost:10.0" }, which: (c) => (c === "xclip" ? join(bin, "xclip") : null), host: empty })
expect(r).toEqual({ status: "read", mime: "image/jpeg", bytes: new Uint8Array(JPEG) })
} finally {
process.env.PATH = path
}
})
test("pasted images are saved by kind, and old ones are cleaned up — nothing else in the folder", () => {
const dir = join(mkdtempSync(join(tmpdir(), "lembas-clip-")), "clipboard")
const a = savePastedImage(dir, PNG, "image/png")
const b = savePastedImage(dir, JPEG, "image/jpeg")
expect(a).toMatch(/paste-\d+-\d+\.png$/)
expect(b).toMatch(/paste-\d+-\d+\.jpg$/)
expect(a).not.toBe(b)
expect(readFileSync(b).equals(JPEG)).toBe(true)
writeFileSync(join(dir, "notes.txt"), "mine")
const old = new Date(Date.now() - 9 * 86_400_000)
utimesSync(a, old, old)
utimesSync(join(dir, "notes.txt"), old, old)
expect(cleanPastedImages(dir)).toBe(1)
expect(readdirSync(dir).sort()).toEqual([b.split("/").pop()!, "notes.txt"].sort())
expect(existsSync(a)).toBe(false)
expect(cleanPastedImages(join(dir, "missing"))).toBe(0)
})
// A terminal that speaks kitty's clipboard protocol, as its specification describes it.
function kitty(clipboard: Record<string, Uint8Array>, o: { deny?: boolean; silent?: boolean; echoId?: boolean; bel?: boolean; busy?: boolean } = {}) {
const handlers = new Set<(s: string) => void>()
const wrote: string[] = []
const end = o.bel ? "\x07" : "\x1b\\"
const send = (meta: string, payload = "") => queueMicrotask(() => handlers.forEach((h) => h(`\x1b]5522;${meta}${payload ? `;${payload}` : ""}${end}`)))
const b64 = (s: string | Uint8Array) => Buffer.from(s as never).toString("base64")
const term: OscTerminal = {
subscribeOsc: (h) => (handlers.add(h), () => void handlers.delete(h)),
write(data) {
wrote.push(data)
if (o.silent) return
const p = parse5522(data)!
const id = o.echoId === false ? "" : `:id=${p.meta.id}`
const want = Buffer.from(p.payload, "base64").toString("utf8")
if (o.busy) return send(`type=read:status=EBUSY${id}`)
if (want === ".") {
send(`type=read:status=OK${id}`)
send(`type=read:status=DATA:mime=${b64(".")}${id}`, b64(Object.keys(clipboard).join(" ")))
return send(`type=read:status=DONE${id}`)
}
if (o.deny) return send(`type=read:status=EPERM${id}`)
send(`type=read:status=OK${id}`)
for (const mime of want.split(" ")) {
const bytes = clipboard[mime]
if (!bytes) continue
// Chunks of at most 4096 bytes, each padded on its own.
for (let at = 0; at < bytes.length; at += 4096) send(`type=read:status=DATA:mime=${b64(mime)}${id}`, b64(bytes.subarray(at, at + 4096)))
}
send(`type=read:status=DONE${id}`)
},
}
return { term, wrote, listeners: () => handlers.size }
}
const TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"]
test("kitty's clipboard protocol: the kinds are listed, the first image kind is read in chunks and put together", async () => {
// Larger than two chunks, and not a multiple of three: every chunk's padding matters.
const big = Buffer.concat([JPEG, Buffer.from(Array.from({ length: 10_001 }, (_, i) => i % 251))])
const k = kitty({ "text/plain": Buffer.from("words"), "image/jpeg": big })
const r = await kittyReadImage(k.term, { types: TYPES, password: "secret", name: "LLeMbas CLI" })
expect(r.status).toBe("read")
expect(r).toMatchObject({ mime: "image/jpeg" })
expect(Buffer.from((r as { bytes: Uint8Array }).bytes).equals(big)).toBe(true)
// The listing asks for "." and carries no password; the read names the kind and who asks.
expect(parse5522(k.wrote[0]!)).toMatchObject({ meta: { type: "read" }, payload: Buffer.from(".").toString("base64") })
expect(k.wrote[0]).not.toContain("pw=")
const read = parse5522(k.wrote[1]!)!
expect(Buffer.from(read.payload, "base64").toString()).toBe("image/jpeg")
expect(Buffer.from(read.meta.pw!, "base64").toString()).toBe("secret")
expect(Buffer.from(read.meta.name!, "base64").toString()).toBe("LLeMbas CLI")
expect(read.meta.id).toMatch(/^[a-zA-Z0-9\-_+.]+$/)
expect(k.wrote.every((w) => w.startsWith("\x1b]5522;") && w.endsWith("\x1b\\"))).toBe(true)
expect(k.listeners()).toBe(0) // nothing left listening
})
test("kitty's clipboard protocol: no image, a refusal, a busy multiplexer, BEL terminators, no id echoed", async () => {
expect(await kittyReadImage(kitty({ "text/plain": Buffer.from("words") }).term, { types: TYPES })).toEqual({ status: "empty" })
expect(await kittyReadImage(kitty({ "image/png": PNG }, { deny: true }).term, { types: TYPES })).toEqual({ status: "denied" })
expect(await kittyReadImage(kitty({ "image/png": PNG }, { busy: true }).term, { types: TYPES })).toEqual({ status: "busy" })
const r = await kittyReadImage(kitty({ "image/png": PNG }, { bel: true, echoId: false }).term, { types: TYPES })
expect(r).toMatchObject({ status: "read", mime: "image/png" })
expect(Buffer.from((r as { bytes: Uint8Array }).bytes).equals(PNG)).toBe(true)
expect(await kittyReadImage(kitty({ "image/png": Buffer.alloc(9000) }).term, { types: TYPES, maxBytes: 8000 })).toEqual({ status: "too-large" })
})
test("kitty's clipboard protocol: a terminal that says nothing does not speak it, and nobody waits long", async () => {
const k = kitty({}, { silent: true })
const t0 = performance.now()
expect(await kittyReadImage(k.term, { types: TYPES, listTimeoutMs: 80 })).toEqual({ status: "unsupported" })
expect(performance.now() - t0).toBeLessThan(1000)
expect(k.wrote.length).toBe(1) // the read was never asked
expect(k.listeners()).toBe(0)
// Another program's reply (a different id) is not taken for ours.
const handlers = new Set<(s: string) => void>()
const other: OscTerminal = { subscribeOsc: (h) => (handlers.add(h), () => void handlers.delete(h)), write: () => queueMicrotask(() => handlers.forEach((h) => h("\x1b]5522;type=read:status=DONE:id=someone-else\x1b\\"))) }
expect(await kittyReadImage(other, { types: TYPES, listTimeoutMs: 80 })).toEqual({ status: "unsupported" })
})
test("an image is whole by its own structure: a piece missing anywhere fails it", () => {
expect(imageWhole(PNG, "image/png")).toBe(true)
expect(imageWhole(PNG.subarray(0, PNG.length - 5), "image/png")).toBe(false)
// A piece lost from the middle: the chunks no longer run to IEND.
expect(imageWhole(Buffer.concat([PNG.subarray(0, 40), PNG.subarray(44)]), "image/png")).toBe(false)
expect(imageWhole(Buffer.concat([PNG, Buffer.from("x")]), "image/png")).toBe(false)
const jpeg = Buffer.concat([JPEG, Buffer.from([0xff, 0xd9])])
expect(imageWhole(jpeg, "image/jpeg")).toBe(true)
expect(imageWhole(JPEG, "image/jpeg")).toBe(false)
expect(imageWhole(Buffer.concat([GIF, Buffer.from([0x3b])]), "image/gif")).toBe(true)
expect(imageWhole(GIF, "image/gif")).toBe(false)
const webp = Buffer.concat([Buffer.from("RIFF"), Buffer.from([16, 0, 0, 0]), Buffer.from("WEBPVP8 "), Buffer.alloc(8)])
expect(imageWhole(webp, "image/webp")).toBe(true)
expect(imageWhole(webp.subarray(0, 20), "image/webp")).toBe(false)
expect(imageWhole(PNG, "text/plain")).toBe(false)
})
test("kitty's clipboard protocol: what arrives is believed by its bytes; input during the read means a lost packet", async () => {
const whole = (bytes: Uint8Array) => {
const mime = sniffImage(bytes)
return mime && imageWhole(bytes, mime) ? mime : undefined
}
// Asked for as PNG, a JPEG in fact: saved as what it is.
const jpeg = Buffer.concat([JPEG, Buffer.from([0xff, 0xd9])])
expect(await kittyReadImage(kitty({ "image/png": jpeg }).term, { types: TYPES, whole })).toMatchObject({ status: "read", mime: "image/jpeg" })
// Not an image at all, and an image missing its end: refused, never handed on.
expect(await kittyReadImage(kitty({ "image/png": Buffer.from("#!/bin/sh\necho not a picture\n") }).term, { types: TYPES, whole })).toEqual({ status: "garbled" })
expect(await kittyReadImage(kitty({ "image/png": PNG.subarray(0, PNG.length - 6) }).term, { types: TYPES, whole })).toEqual({ status: "garbled" })
// The box's input is held for the whole read and let go after it; keys that arrived meanwhile
// are a reply that came apart, so even a read that looks complete is not believed.
let holds = 0
let released = 0
const k = kitty({ "image/png": PNG })
const quiet = { ...k.term, holdInput: () => (holds++, () => (released++, 0)) }
expect(await kittyReadImage(quiet, { types: TYPES, whole })).toMatchObject({ status: "read", mime: "image/png" })
expect([holds, released]).toEqual([1, 1])
const leaky = { ...kitty({ "image/png": PNG }).term, holdInput: () => () => 37 }
expect(await kittyReadImage(leaky, { types: TYPES, whole })).toEqual({ status: "garbled" })
})
test("which terminals are asked: kitty, also through ssh; never inside a multiplexer", () => {
expect(kittyClipboardLikely({ TERM: "xterm-kitty" })).toBe(true)
expect(kittyClipboardLikely({ TERM: "xterm-256color", KITTY_WINDOW_ID: "3" })).toBe(true)
expect(kittyClipboardLikely({ TERM: "xterm-256color" })).toBe(false)
expect(kittyClipboardLikely({ TERM: "xterm-kitty", TMUX: "/tmp/tmux-1000/default,1,0" })).toBe(false)
expect(kittyClipboardLikely({})).toBe(false)
expect(parse5522("\x1b]52;c;aGk=\x07")).toBeUndefined()
expect(parse5522("\x1b]5522;type=read:status=DATA:mime=aW1hZ2UvcG5n;QUJD\x07")).toEqual({ meta: { type: "read", status: "DATA", mime: "aW1hZ2UvcG5n" }, payload: "QUJD" })
})
+23 -1
View File
@@ -31,7 +31,8 @@ import { LOOP, TOOL_SPECS } from "../src/harness.ts"
import { LEAD_TOOLS, memberTools, Team, TEAM_TOOLS, type Capacity } from "../src/team/team.ts"
import { noteBlock } from "../src/session/prefix.ts"
import { offer, subagentModel, type ModelInfo } from "../src/team/subagents.ts"
import { progressLine, progressText, type Progress } from "../src/session/progress.ts"
import { endLine, progressLine, progressText, type Progress } from "../src/session/progress.ts"
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"
@@ -355,6 +356,27 @@ export const AREAS: Record<string, (c: Case) => unknown> = {
throw new Error(`team: unknown op ${String(st.op)}`)
})
},
// Display (display.md, spec 3.7.0): a call's title, duration and facts; the line that ends a reply.
display: (c) => {
switch (c.show) {
case "title":
return { title: callTitle(c.args) ?? null }
case "duration":
return { duration: callDuration(c.state as CallState, c.ms as number | undefined) ?? null }
case "change": {
const n = diffCounts(c.diff as string)
return { ...n, text: changeText(n) }
}
case "facts":
return { facts: callFacts(c as { block?: string; diff?: string; exit?: number; hits?: number }) }
case "end":
return { line: endLine(c.progress as Progress | null, c.now as number) ?? null }
case "drawn":
return { drawn: drawnBlock(c.block as string | undefined) }
default:
throw new Error(`display: unknown show ${String(c.show)}`)
}
},
// Progress (progress.md, spec 3.4.0): the text and the line a client draws.
progress: (c) => {
const p = c.progress as Progress
+109
View File
@@ -0,0 +1,109 @@
// Display per harness spec 3.7.0 (harness/display.md): one title for a call wherever it is said,
// the real count of running subagents, numbers in the terminal's locale. The spec's own cases are
// in harness/conformance/display.json (tests/conformance.test.ts).
import { expect, test } from "bun:test"
import { Bus } from "../src/bus/index.ts"
import { callTitle, localeNumber, plainNumber, resultFacts, terminalLocale } from "../src/session/display.ts"
import { endOf, ProgressTracker, progressLine, progressText, type Progress } from "../src/session/progress.ts"
import { permissionParams } from "../src/acp/agent.ts"
const phases = (bus: Bus) => {
const seen: (Progress | null)[] = []
bus.on((e) => e.type === "phase" && seen.push(e.progress as Progress | null))
return seen
}
test("the progress line's `what` is the call's title: the event's, else made from the arguments", () => {
const bus = new Bus()
const seen = phases(bus)
const t = new ProgressTracker(bus)
bus.emit({ type: "tool_start", id: "a", name: "grep", args: { pattern: "TODO", path: "src" } })
expect(seen.at(-1)).toMatchObject({ phase: "running_tool", tool: "grep", what: "TODO" })
bus.emit({ type: "tool_end", id: "a", name: "grep", result: { output: "" }, ms: 1 })
bus.emit({ type: "tool_start", id: "b", name: "bash", args: { command: "bun test", description: "Run the tests" }, title: "bun test" })
expect(seen.at(-1)).toMatchObject({ phase: "running_tool", tool: "bash", what: "bun test" })
expect(callTitle({ command: "bun test", description: "Run the tests" })).toBe("bun test")
t.dispose()
})
test("waiting_for_subagents counts the subagents that are running, not always one", async () => {
const bus = new Bus()
const seen = phases(bus)
const t = new ProgressTracker(bus)
const job = (id: string, state: string) => ({ id, kind: "subagent", state, description: id, started: 0, unread: 0 }) as never
bus.emit({ type: "tool_start", id: "t1", name: "task", args: { description: "one", prompt: "p" } })
expect(seen.at(-1)).toMatchObject({ phase: "waiting_for_subagents", running: 1 })
const since = seen.at(-1)!.since
// Two more calls in the same step: three foreground subagents.
bus.emit({ type: "tool_start", id: "t2", name: "task", args: { description: "two", prompt: "p" } })
bus.emit({ type: "tool_start", id: "t3", name: "task", args: { description: "three", prompt: "p" } })
await Bun.sleep(300) // a change of the count is data: paced, and `since` kept
expect(seen.at(-1)).toMatchObject({ phase: "waiting_for_subagents", running: 3, since })
// The session's subagent jobs count too — one more than the calls of this step.
for (const id of ["job1", "job2", "job3", "job4"]) bus.emit({ type: "job", state: "start", job: job(id, "running") })
await Bun.sleep(300)
expect(seen.at(-1)).toMatchObject({ running: 4 })
bus.emit({ type: "job", state: "end", job: job("job4", "done") })
bus.emit({ type: "job", state: "end", job: job("job3", "done") })
bus.emit({ type: "tool_end", id: "t3", name: "task", result: { output: "" }, ms: 1 })
await Bun.sleep(300)
expect(seen.at(-1)).toMatchObject({ phase: "waiting_for_subagents", running: 2 })
// A command in the background is not a subagent.
bus.emit({ type: "job", state: "start", job: { ...(job("job9", "running") as object), kind: "command" } as never })
await Bun.sleep(300)
expect(seen.at(-1)).toMatchObject({ running: 2 })
expect(progressText(seen.at(-1)!)).toBe("Waiting for subagents: 2 running")
t.dispose()
})
test("numbers in the terminal's locale; durations and the plain format untouched", () => {
expect(terminalLocale({ LANG: "sk_SK.UTF-8" })).toBe("sk-SK")
expect(terminalLocale({ LANG: "en_US.UTF-8", LC_NUMERIC: "de_DE.UTF-8" })).toBe("de-DE")
expect(terminalLocale({ LANG: "en_US.UTF-8", LC_NUMERIC: "de_DE.UTF-8", LC_ALL: "fr_FR@euro" })).toBe("fr-FR")
expect(terminalLocale({ LANG: "C.UTF-8" })).toBeUndefined()
expect(terminalLocale({ LC_ALL: "POSIX" })).toBeUndefined()
expect(terminalLocale({})).toBeUndefined()
expect(terminalLocale({ LANG: "not a locale!" })).toBeUndefined()
const de = localeNumber("de-DE")
const en = localeNumber("en-US")
expect([de(12480), de(12.46, 1), de(7)]).toEqual(["12.480", "12,5", "7"])
expect([en(12480), en(12.46, 1), en(1234567)]).toEqual(["12,480", "12.5", "1,234,567"])
expect([plainNumber(12480), plainNumber(12.46, 1)]).toEqual(["12480", "12.5"])
expect(localeNumber(undefined)(12480)).toBe("12480")
expect(localeNumber("xx-not-a-locale-")(12480)).toBe("12480")
const reading: Progress = { phase: "reading_prompt", since: 0, done: 90000, total: 140000 }
expect(progressText(reading, 0, de)).toBe("Reading the prompt: 90.000 / 140.000 tokens (64%)")
expect(progressText(reading, 0)).toBe("Reading the prompt: 90000 / 140000 tokens (64%)")
// The clock is not a locale number.
expect(progressLine({ phase: "writing", since: 0, rate: 1234.56 }, 65_000, de)).toBe("Writing: 1.234,6 tok/s · 1m 05s")
})
test("what a finished call adds after its title", () => {
const diff = "--- a.txt\n+++ a.txt\n@@ -1,2 +1,3 @@\n one\n+two\n three\n"
expect(resultFacts("edit", "a.txt", { title: "a.txt +1 −0", meta: { diff } })).toEqual(["+1 −0"])
expect(resultFacts("shell", "bun test", { title: "bun test · exit 0", meta: { exit: 0 } })).toEqual([])
expect(resultFacts("shell", "bun test", { title: "bun test · exit 3", meta: { exit: 3 } })).toEqual(["exit 3"])
// Stopped by a signal: no exit code, so what the tool says.
expect(resultFacts("shell", "sleep 9", { title: "sleep 9 · stopped (SIGTERM)", meta: { exit: null } })).toEqual(["stopped (SIGTERM)"])
expect(resultFacts("search", "TODO", { title: "/TODO/ · 1234 matches", meta: { hits: 1234 } }, localeNumber("en-US"))).toEqual(["1,234 hits"])
expect(resultFacts("read", "src/a.ts", { title: "src/a.ts · 1–200 of 950" })).toEqual(["1–200 of 950"])
expect(resultFacts("tool", "theme", { title: "theme = moria (global)" })).toEqual(["= moria (global)"])
expect(resultFacts("tool", "job3", { title: "job3 · stopped" })).toEqual(["stopped"])
expect(resultFacts("read", "notes", { title: "notes" })).toEqual([])
expect(resultFacts("tool", undefined, {})).toEqual([])
})
test("over the link an approval card keeps the whole command as its title and names the tool; how a turn ended, as the spec's progress", () => {
const p = permissionParams("s1", { tool: "bash", args: { command: "rm -rf build\necho done", description: "Clean" }, request: { command: "rm -rf build\necho done", patterns: [] }, decision: { reason: "asks", always: [] } } as never)
// A card is read before it is answered: the whole command, not the call's short title.
expect(p.toolCall.title).toBe("rm -rf build\necho done")
expect(p._meta.lembas.tool).toBe("bash")
// No command: the tool's name, as before — and the name is in _meta.lembas either way.
const q = permissionParams("s1", { tool: "edit", args: { path: "a.txt", old: "a", new: "b" }, request: { patterns: ["a.txt"] }, decision: { reason: "asks", always: [] } } as never)
expect([q.toolCall.title, q._meta.lembas.tool]).toEqual(["edit", "edit"])
expect(endOf("stop")).toBeUndefined()
expect(endOf("cancelled")).toEqual({ phase: "stopped", reason: "person" })
expect(endOf("steps")).toEqual({ phase: "stopped", reason: "steps" })
expect(endOf("budget")).toEqual({ phase: "stopped", reason: "budget" })
expect(endOf("error", "401 Unauthorized\nrun lembas login")).toEqual({ phase: "failed", reason: "401 Unauthorized" })
})
+23 -1
View File
@@ -5,7 +5,7 @@ import { afterEach, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { shellKind, shellLaunch, type ShellLaunch } from "../src/acp/shellrc.ts"
import { pickShell, shellKind, shellLaunch, type ShellLaunch } from "../src/acp/shellrc.ts"
const launched: ShellLaunch[] = []
afterEach(() => {
@@ -17,6 +17,28 @@ const launch = (...a: Parameters<typeof shellLaunch>) => {
return l
}
test("the shell a terminal runs: $SHELL where it exists, else bash, zsh, sh; on Windows PowerShell, then cmd", () => {
const has = (...paths: string[]) => (p: string) => paths.includes(p)
const none = () => null
// POSIX: the person's own shell, as a login shell.
expect(pickShell("linux", { SHELL: "/usr/bin/fish" }, has("/usr/bin/fish", "/bin/bash"), none)).toEqual({ shell: "/usr/bin/fish", args: ["-l"] })
// A SHELL that is not there (a container, a stale variable) is passed over, not started.
expect(pickShell("linux", { SHELL: "/opt/gone/zsh" }, has("/bin/bash", "/bin/sh"), none)).toEqual({ shell: "/bin/bash", args: ["-l"] })
// No bash (a minimal image): zsh, then sh.
expect(pickShell("darwin", {}, has("/bin/zsh", "/bin/sh"), none)).toEqual({ shell: "/bin/zsh", args: ["-l"] })
expect(pickShell("linux", {}, has("/bin/sh"), none)).toEqual({ shell: "/bin/sh", args: ["-l"] })
expect(pickShell("linux", {}, has(), none)).toBeUndefined()
// Windows: no -l anywhere; PowerShell 7 before Windows PowerShell before cmd. SHELL is not read.
const which = (...found: string[]) => (c: string) => (found.includes(c) ? `C:\\bin\\${c}` : null)
expect(pickShell("win32", { SHELL: "/usr/bin/bash" }, has(), which("pwsh.exe", "powershell.exe", "cmd.exe"))).toEqual({ shell: "C:\\bin\\pwsh.exe", args: ["-NoLogo"] })
expect(pickShell("win32", {}, has(), which("powershell.exe", "cmd.exe"))).toEqual({ shell: "C:\\bin\\powershell.exe", args: ["-NoLogo"] })
expect(pickShell("win32", { ComSpec: "C:\\Windows\\System32\\cmd.exe" }, has("C:\\Windows\\System32\\cmd.exe"), which())).toEqual({ shell: "C:\\Windows\\System32\\cmd.exe", args: [] })
expect(pickShell("win32", { ComSpec: "C:\\gone.exe" }, has(), which("cmd.exe"))).toEqual({ shell: "C:\\bin\\cmd.exe", args: [] })
expect(pickShell("win32", {}, has(), which())).toBeUndefined()
// A shell that takes no -l starts without it, and without marks.
expect(shellLaunch("C:\\bin\\pwsh.exe", "t1", true, {}, ["-NoLogo"])).toMatchObject({ kind: "other", integration: false, argv: ["C:\\bin\\pwsh.exe", "-NoLogo"] })
})
test("which shells get marks: bash, zsh and fish; anything else starts as before", () => {
expect(shellKind("/usr/bin/bash")).toBe("bash")
expect(shellKind("/bin/zsh")).toBe("zsh")
+14 -6
View File
@@ -32,7 +32,8 @@ test("a prompt runs; a bash call asks; y allows it; the answer renders as markdo
const f = t.frame()
expect(f).toContain("❯ Ask") // the y that answered did not also land in the prompt
expect(f).toContain("┃ make a file")
expect(f).toContain("┊ 💻 bash Write out.txt · exit 0")
// The call's one title — the command — and, finished, how long it took (spec 3.7.0 display.md).
expect(f).toMatch(/┊ 💻 bash echo hi > out\.txt · \d+\.\ds/)
expect(f).not.toContain("## Done") // heading marker concealed
expect(f).toContain("ctx 12k/33k 37%")
expect(await Bun.file(`${t.cwd}/out.txt`).text()).toBe("hi\n")
@@ -323,11 +324,17 @@ test("thinking stops the clock when the model starts a call, even if the call th
expect(await t.until("done")).toBe(true)
})
test("pasting an image's path (quoted, as a file manager does) inserts an @reference", async () => {
test("pasting an image's path (quoted, as a file manager does): [Image 1], or its @reference with paste: full", async () => {
t = await tui([])
await Bun.write(`${t.cwd}/my shot.png`, "x")
await t.input.pasteBracketedText(`'${t.cwd}/my shot.png'`)
await t.settle()
expect(t.frame()).toContain("❯ [Image 1]")
t.stop()
t = await tui([], undefined, "paste: full\n")
await Bun.write(`${t.cwd}/my shot.png`, "x")
await t.input.pasteBracketedText(`'${t.cwd}/my shot.png'`)
await t.settle()
expect(t.frame()).toContain(`@${t.cwd}/my\\ shot.png`)
})
@@ -379,7 +386,8 @@ test("while it thinks: the thought says only Thinking…; the line at the bottom
expect(await t.until("~15 tokens")).toBe(true)
const frame = t.frame()
expect(frame).toMatch(/^\s*Thinking\.{1,3}\s*$/m)
expect(frame).toMatch(/Thinking · \d+s · turn \d+s · ~15 tokens · esc to stop/)
// One clock: the phase's own; the turn's time joins it ("of 12s") only once it differs.
expect(frame).toMatch(/Thinking · \d+s( of \d+s)? · ~15 tokens · esc to stop/)
expect(frame).not.toContain("HIDDEN-WHILE-THINKING")
expect(await t.until("Done thinking.")).toBe(true)
expect(t.frame()).toMatch(/Thought for \d\.\ds · ~15 tokens/)
@@ -397,7 +405,7 @@ test("the line at the bottom counts the whole task: the clock and the tokens go
// The spinner line redraws on its own tick, slower than the reply's text: on a slow machine the
// frame that first shows "Half" can still carry the line from before. The 1.2 s gap holds this
// state, so wait for the line within it rather than reading the first frame.
const counted = /Writing(: [\d.]+ tok\/s)? · \d+s · turn \d+s · ~4\d tokens · esc to stop/
const counted = /Writing(: [\d.]+ tok\/s)? · \d+s( of \d+s)? · ~4\d tokens · esc to stop/
for (let i = 0; i < 20 && !counted.test(t.frame()); i++) await Bun.sleep(50), await t.settle()
expect(t.frame()).toMatch(counted)
expect(await t.until("way.")).toBe(true)
@@ -875,7 +883,7 @@ test("esc mid-reply, then ctrl+g: it continues, and the model sees what it had a
t.input.pressEnter()
expect(await t.until("Step one is done.")).toBe(true)
t.input.pressEscape()
expect(await t.until("cancelled")).toBe(true)
expect(await t.until("■ Stopped: by you")).toBe(true)
await t.settle()
t.input.pressKey("g", { ctrl: true })
expect(await t.until("↻ continue")).toBe(true)
@@ -924,7 +932,7 @@ test("while the server reads a long prompt: the line at the bottom says how far
t.input.pressEnter()
// At 100 columns the line is cut in its middle; its start and its end are what is checked.
expect(await t.until("~1m 40s left")).toBe(true)
expect(t.frame()).toContain("Reading the prompt: 90000 / 140000 tokens (64%")
expect(t.frame()).toContain("Reading the prompt: 90,000 / 140,000 tokens (64%")
expect(await t.until("Read it all.")).toBe(true)
await t.settle()
expect(t.frame()).not.toContain("Reading the prompt")
+151
View File
@@ -0,0 +1,151 @@
// How the transcript draws a tool call and the end of a reply (harness spec 3.7.0, display.md).
import { afterEach, expect, test } from "bun:test"
import { delta, toolCall, usage } from "../fake-provider.ts"
import { tui } from "./harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
test("a call keeps one title; done shows its facts and how long it took, failed its exit code, denied its reason and no time", async () => {
t = await tui(
[
{
chunks: [
toolCall(0, "c1", "grep", '{"pattern":"hello","path":"."}'),
toolCall(1, "c2", "edit", '{"path":"hello.txt","old":"hello world","new":"hello there\\nworld"}'),
toolCall(2, "c3", "bash", '{"command":"exit 3","description":"Fail on purpose"}'),
toolCall(3, "c4", "bash", '{"command":"git push origin main","description":"Push"}'),
],
},
{ chunks: [delta({ content: "All done." }), usage(100, 5)] },
],
{ width: 110, height: 34 },
"mode: auto\npermission:\n bash:\n 'git push *': deny\n",
)
await t.input.typeText("@hello.txt do things")
t.input.pressEnter()
expect(await t.until("All done.")).toBe(true)
const f = t.frame()
// A search is titled by its pattern, and says its hits.
expect(f).toMatch(/grep hello · 1 hit · \d+\.\ds/)
// An edit: the path, +added −removed, the time.
expect(f).toMatch(/edit hello\.txt · \+2 −1 · \d+\.\ds/)
// A command that failed: its own line as the title (not its description), the exit code.
expect(f).toMatch(/bash exit 3 · exit 3 · \d+\.\ds ✗/)
// Denied: the same title, the reason, and no duration — it never ran.
const denied = f.split("\n").find((l) => l.includes("git push origin main"))!
expect(denied).toContain("git push origin main · ")
expect(denied).not.toMatch(/\d+\.\ds/)
expect(denied).not.toContain("✗")
})
test("a reply that fails ends with the spec's line, once; one stopped by esc says Stopped: by you", async () => {
t = await tui([
{ status: 400, body: '{"error":{"message":"the model is not loaded"}}' },
{ status: 400, body: '{"error":{"message":"the model is not loaded"}}' },
{ status: 400, body: '{"error":{"message":"the model is not loaded"}}' },
{ chunks: [delta({ content: "Slow" }), delta({ content: "er" }), delta({ content: " still" }), delta({ content: " going" })], gapMs: 400 },
])
await t.input.typeText("go")
t.input.pressEnter()
expect(await t.until("✗ Failed: ")).toBe(true)
const f = t.frame()
expect(f).toContain("the model is not loaded")
// Said once: no second, raw copy of the error beside the line.
expect(f.split("the model is not loaded").length - 1).toBe(1)
expect(f.split("Failed").length - 1).toBe(1)
await t.input.typeText("again")
t.input.pressEnter()
expect(await t.until("Slow")).toBe(true)
t.input.pressEscape()
expect(await t.until("■ Stopped: by you")).toBe(true)
// The earlier reply still says how it ended: the line stays on it.
expect(t.frame()).toContain("✗ Failed: ")
expect(t.frame()).not.toContain("cancelled")
})
test("a session shown again from the store says how its last reply ended", async () => {
t = await tui([{ chunks: [delta({ content: "Half an ans" }), delta({ content: "wer" }), delta({ content: " and" }), delta({ content: " more" })], gapMs: 400 }], undefined, "", { store: true })
await t.input.typeText("tell me")
t.input.pressEnter()
expect(await t.until("Half an ans")).toBe(true)
t.input.pressEscape()
expect(await t.until("■ Stopped: by you")).toBe(true)
const id = t.app.engine.sessionId!
expect(t.app.engine.storedEnd()).toEqual({ reason: "cancelled" })
t.view.load(t.app.resume(id), t.app.engine.storedEnd())
await t.settle()
expect(t.frame()).toContain("■ Stopped: by you")
})
// ---- found in review ----
test("the stored end belongs to its turn: /undo takes it away; a reply that finished is never drawn stopped", async () => {
t = await tui(
[{ chunks: [delta({ content: "Fine." }), usage(100, 5)] }, { chunks: [delta({ content: "Half" }), delta({ content: " more" }), delta({ content: " more" }), delta({ content: " more" })], gapMs: 400 }],
undefined,
"titles: prompt\n", // no second request for a title
{ store: true },
)
await t.input.typeText("one")
t.input.pressEnter()
expect(await t.until("Fine.")).toBe(true)
await t.input.typeText("two")
t.input.pressEnter()
expect(await t.until("Half")).toBe(true)
t.input.pressEscape()
expect(await t.until("■ Stopped: by you")).toBe(true)
await t.settle()
expect(t.app.engine.storedEnd()).toEqual({ reason: "cancelled" })
await t.input.typeText("/undo")
t.input.pressEnter()
await t.settle(300)
// The stopped turn is gone from the conversation: so is how it ended.
expect(t.app.engine.storedEnd()).toBeUndefined()
const id = t.app.engine.sessionId!
t.view.load(t.app.resume(id), t.app.engine.storedEnd())
await t.settle()
expect(t.frame()).toContain("Fine.")
expect(t.frame()).not.toContain("Stopped")
})
test("a call whose result never came is drawn failed when the session is shown again; the person's own !command is not the turn's", async () => {
t = await tui([{ chunks: [delta({ content: "Slow" }), delta({ content: "ly" }), delta({ content: " said." }), usage(100, 5)], gapMs: 300 }])
// A stored conversation that ends in a call with no result (the process went away mid-call).
t.view.load([
{ role: "user", parts: [{ type: "text", text: "run it" }] },
{ role: "assistant", parts: [{ type: "tool_call", id: "c1", name: "bash", args: '{"command":"make all"}' }, { type: "tool_call", id: "c2", name: "read", args: '{"path":"a.txt"}' }] },
{ role: "tool", callId: "c2", content: "1: hello", isError: false },
] as never)
await t.settle()
const items = t.view.state.items.filter((i) => i.kind === "tool") as { id: string; status: string; title?: string }[]
expect(items.map((i) => [i.id, i.status, i.title])).toEqual([
["c1", "error", "make all"],
["c2", "done", "a.txt"],
])
expect(t.frame()).toMatch(/bash make all.*✗/)
// A `!` command still running when a turn ends stays running: it was never part of the turn.
const own = t.view.shellStart("sleep 30")
await t.input.typeText("go")
t.input.pressEnter()
expect(await t.until("ly said.")).toBe(true)
await t.settle()
const mine = t.view.state.items.find((i) => i.kind === "tool" && i.id === own) as { status: string }
expect(mine.status).toBe("running")
})
test("a refused call is titled from its arguments as a call that runs gets them, not the model's raw JSON", async () => {
t = await tui(
[{ chunks: [toolCall(0, "c1", "bash", '{"command":"git push origin main","purpose":"Publish the branch"}')] }, { chunks: [delta({ content: "Not pushed." }), usage(100, 5)] }],
undefined,
"mode: auto\npermission:\n bash:\n 'git push *': deny\n",
)
const denied: { args?: unknown; title?: string }[] = []
t.app.bus.on((e) => void (e.type === "tool_denied" && denied.push(e)))
await t.input.typeText("push")
t.input.pressEnter()
expect(await t.until("Not pushed.")).toBe(true)
expect(denied[0]!.title).toBe("git push origin main")
// `purpose` is the harness's own argument, taken off before the tool sees the call.
expect(denied[0]!.args).toEqual({ command: "git push origin main" })
})
+1 -1
View File
@@ -244,7 +244,7 @@ test("ctrl+b moves the foreground command to the background: the call returns, t
t.input.pressEnter()
expect(await t.until("Allow once")).toBe(true)
await t.input.typeText("y")
expect(await t.until("wait a while …")).toBe(true)
expect(await t.until("echo early; sleep 20; echo late …")).toBe(true)
await Bun.sleep(300)
t.input.pressKey("b", { ctrl: true })
expect(await t.until("Moved on.")).toBe(true)
+506
View File
@@ -0,0 +1,506 @@
// Paste placeholders in the prompt box (src/tui/paste.ts, prompt.tsx): a long paste and an image
// are shown as a placeholder and sent in full.
import { afterEach, expect, test } from "bun:test"
import { TextareaRenderable } from "@opentui/core"
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"
import { join } from "node:path"
import { paths } from "../../src/config/paths.ts"
import { nextImageNumber, pasteLabel } from "../../src/tui/paste.ts"
import { delta, usage } from "../fake-provider.ts"
import { tui } from "./harness.tsx"
let t: Awaited<ReturnType<typeof tui>> | undefined
afterEach(() => t?.stop())
const box = (n: any): TextareaRenderable => (n instanceof TextareaRenderable ? n : n.getChildren?.().map(box).find(Boolean))
const LONG = ["first line", "second line", "third line", "fourth line"].join("\n")
/** The last user message of request `i`, as JSON text. */
const sent = (i = 0) => JSON.stringify((t!.fake.requests[i]!.messages as { role: string; content: unknown }[]).filter((m) => m.role === "user").at(-1)!.content)
test("which pastes get a placeholder, and what it says", () => {
expect(pasteLabel("one\ntwo")).toBeUndefined()
expect(pasteLabel("one\ntwo\nthree")).toBe("[Pasted text 3 lines]")
expect(pasteLabel("x".repeat(150))).toBeUndefined()
expect(pasteLabel("x".repeat(151))).toBe("[Pasted text 151 chars]")
// Two long lines are still one long text, counted in characters (code points).
expect(pasteLabel(`${"é".repeat(100)}\n${"é".repeat(100)}`)).toBe("[Pasted text 201 chars]")
expect(nextImageNumber([])).toBe(1)
expect(nextImageNumber(["[Image 1]", "[Pasted text 3 lines]", "[Image 4]"])).toBe(5)
})
test("a long paste shows as a placeholder; the text itself is sent, and the transcript shows the placeholder", async () => {
t = await tui([{ chunks: [delta({ content: "Read it." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("look: ")
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe("look: [Pasted text 4 lines] ")
expect(t.frame()).toContain("look: [Pasted text 4 lines]")
await t.input.typeText("thanks")
t.input.pressEnter()
expect(await t.until("Read it.")).toBe(true)
expect(sent()).toContain("look: first line\\nsecond line\\nthird line\\nfourth line thanks")
expect(sent()).not.toContain("[Pasted text")
expect(t.frame()).toContain("┃ look: [Pasted text 4 lines] thanks")
expect(a.plainText).toBe("")
})
test("a short paste goes in as it is; text after wide characters keeps the placeholder in place", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText("just\ntwo")
await t.settle()
expect(a.plainText).toBe("just\ntwo")
a.setText("")
// Offsets in the box are columns: a wide character before the placeholder must not shift it.
a.insertText("日本語 🙂 ")
await t.input.pasteBracketedText(LONG)
await t.settle()
a.insertText("end")
expect(a.plainText).toBe("日本語 🙂 [Pasted text 4 lines] end")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toContain("日本語 🙂 first line\\nsecond line\\nthird line\\nfourth line end")
})
test("deleting the placeholder removes the content; undo in the box brings both back", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("a ")
await t.input.pasteBracketedText(LONG)
await t.settle()
t.input.pressBackspace() // the space after it
t.input.pressBackspace() // the placeholder, whole
await t.settle()
expect(a.plainText).toBe("a ")
a.undo()
await t.settle()
expect(a.plainText).toContain("[Pasted text 4 lines]")
a.gotoBufferEnd()
t.input.pressBackspace()
await t.settle()
expect(a.plainText).toBe("a ")
await t.input.typeText("b")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toStartWith('"a b\\n')
expect(sent()).not.toContain("first line")
})
test("the same paste again, right after its placeholder, opens it", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe("[Pasted text 4 lines] ")
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe(LONG)
})
test("two pastes with the same label keep their own text; an @file completed beside them leaves them alone", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText("a1\na2\na3")
await t.input.pasteBracketedText("b1\nb2\nb3")
await t.settle()
expect(a.plainText).toBe("[Pasted text 3 lines] [Pasted text 3 lines] ")
await t.input.typeText("@hello")
expect(await t.until("hello.txt")).toBe(true)
t.input.pressTab()
await t.settle()
expect(a.plainText).toBe("[Pasted text 3 lines] [Pasted text 3 lines] @hello.txt ")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toContain("a1\\na2\\na3 b1\\nb2\\nb3 @hello.txt")
})
test("history and /undo give the text in full", async () => {
t = await tui([{ chunks: [delta({ content: "Answered." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("see ")
await t.input.pasteBracketedText(LONG)
await t.settle()
t.input.pressEnter()
expect(await t.until("Answered.")).toBe(true)
// History is the file other sessions read too: the text itself.
const history = readFileSync(join(paths.state, "history.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l) as string)
expect(history.at(-1)).toBe(`see ${LONG} `)
t.input.pressArrow("up")
await t.settle()
expect(a.plainText).toBe(`see ${LONG} `)
a.setText("")
await t.input.typeText("/undo")
t.input.pressEnter()
await t.settle(200)
expect(a.plainText).toContain(`see ${LONG}`)
})
test("a refused send puts the placeholder back, still standing for its text", async () => {
t = await tui([{ chunks: [delta({ content: "Slow" }), delta({ content: "ly" }), delta({ content: " done." }), usage(100, 5)], gapMs: 300 }, { chunks: [delta({ content: "Second." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("go")
t.input.pressEnter()
expect(await t.until("Slow")).toBe(true)
// Busy with a turn: a command that must wait is refused, and the box comes back whole.
await t.input.typeText("/compact ")
await t.input.pasteBracketedText(LONG)
await t.settle(20)
t.input.pressEnter()
await t.settle(20)
expect(t.frame()).toContain("wait for the reply to finish")
expect(a.plainText).toBe("/compact [Pasted text 4 lines] ")
expect(await t.until("ly done.")).toBe(true) // the notice above went in mid-reply
// Still a placeholder: sent now as a prompt, it is the text.
a.cursorOffset = 0
for (let k = 0; k < "/compact ".length; k++) a.deleteChar()
t.input.pressEnter()
expect(await t.until("Second.")).toBe(true)
expect(sent(1)).toContain("first line\\nsecond line")
})
test("copying a selection in the box copies the text in full", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
await t.input.typeText("x ")
await t.input.pasteBracketedText(LONG)
await t.settle()
const copied: string[] = []
;(t.setup.renderer as any).copyToClipboardOSC52 = (s: string) => (copied.push(s), true)
// Drag across the box's one row.
const y = t.frame().split("\n").findIndex((l) => l.includes("[Pasted text 4 lines]"))
const x = t.frame().split("\n")[y]!.indexOf("x [Pasted")
await t.setup.mockMouse.drag(x, y, x + 30, y)
await t.settle()
expect(copied.at(-1)).toBe(`x ${LONG} `)
expect(a.plainText).toBe("x [Pasted text 4 lines] ")
})
test("paste: full shows the text itself", async () => {
t = await tui([], undefined, "paste: full\n")
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe(LONG)
})
test("a pasted path to an image is [Image N], numbered after the highest in the box, and sent as its @path", async () => {
t = await tui([{ chunks: [delta({ content: "Seen." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
// A 1×1 PNG.
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64")
const one = join(t.cwd, "shot one.png")
const two = join(t.cwd, "two.png")
writeFileSync(one, png)
writeFileSync(two, png)
await t.input.pasteBracketedText(`'${one}'`)
await t.input.pasteBracketedText(two)
await t.settle()
expect(a.plainText).toBe("[Image 1] [Image 2] ")
// The first one deleted: the next is numbered after the highest still there.
a.cursorOffset = "[Image 1] ".length
t.input.pressBackspace()
t.input.pressBackspace()
await t.settle()
expect(a.plainText).toBe("[Image 2] ")
a.gotoBufferEnd()
await t.input.pasteBracketedText(`file://${one.replace(/ /g, "%20")}`)
await t.settle()
expect(a.plainText).toBe("[Image 2] [Image 3] ")
t.input.pressEnter()
expect(await t.until("Seen.")).toBe(true)
expect(t.frame()).toContain("┃ [Image 2] [Image 3]")
expect(sent()).toContain(`@${two} @${one.replace(/ /g, "\\\\ ")}`)
expect(t.frame()).toContain("attached")
})
test("an @file completed after wide characters replaces its own token, nothing else", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
a.insertText("日本語の説明 ")
await t.input.typeText("@hello")
expect(await t.until("hello.txt")).toBe(true)
t.input.pressTab()
await t.settle()
expect(a.plainText).toBe("日本語の説明 @hello.txt ")
})
const PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
/** Run with these environment variables set, then put back. */
async function withEnv(vars: Record<string, string | undefined>, fn: () => Promise<void>) {
const before = Object.fromEntries(Object.keys(vars).map((k) => [k, process.env[k]]))
for (const [k, v] of Object.entries(vars)) v === undefined ? delete process.env[k] : (process.env[k] = v)
try {
await fn()
} finally {
for (const [k, v] of Object.entries(before)) v === undefined ? delete process.env[k] : (process.env[k] = v)
}
}
const NOT_REMOTE = { SSH_CONNECTION: undefined, SSH_TTY: undefined, SSH_CLIENT: undefined }
test("an image pasted as a data URL is saved and shown as [Image 1]; a data URL that is no image is pasted as the text it is", async () => {
t = await tui([{ chunks: [delta({ content: "Seen." }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("what is this ")
await t.input.pasteBracketedText(`data:image/png;base64,${PNG_B64}`)
await t.settle()
expect(a.plainText).toBe("what is this [Image 1] ")
const notOne = `data:image/png;base64,${Buffer.from("this is certainly not a picture").toString("base64")}`
await t.input.pasteBracketedText(notOne)
await t.settle()
expect(a.plainText).toBe(`what is this [Image 1] ${notOne}`)
// A long one gets the placeholder any long text gets, and is sent as its text.
const long = `data:image/png;base64,${Buffer.from("not a picture either, ".repeat(12)).toString("base64")}`
a.insertText(" ")
await t.input.pasteBracketedText(long)
await t.settle()
expect(a.plainText).toBe(`what is this [Image 1] ${notOne} [Pasted text ${long.length} chars] `)
t.input.pressEnter()
expect(await t.until("Seen.")).toBe(true)
// Sent as the @path of the copy kept under the state directory.
const m = /@(\S+clipboard\/paste-[\w-]+\.png)/.exec(JSON.parse(sent()) as string)
expect(m).not.toBeNull()
expect(JSON.parse(sent()) as string).toContain(long)
expect(readFileSync(m![1]!).toString("base64")).toBe(PNG_B64)
expect(m![1]!.startsWith(join(paths.state, "clipboard"))).toBe(true)
})
test("ctrl+v with no image: said in a word, the box stays usable; over SSH one line names what works", async () => {
await withEnv({ ...NOT_REMOTE, DISPLAY: undefined, WAYLAND_DISPLAY: undefined }, async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
t.input.pressKey("v", { ctrl: true })
// Not waited for: typing goes on at once.
await t.input.typeText("still typing")
expect(a.plainText).toBe("still typing")
expect(await t.until("or use @path")).toBe(true)
t.stop()
})
await withEnv({ SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-256color", KITTY_WINDOW_ID: undefined, TMUX: undefined }, async () => {
t = await tui([], { width: 220, height: 30 })
t.input.pressKey("v", { ctrl: true })
expect(await t.until("no image reached this terminal over SSH")).toBe(true)
const f = t.frame()
expect(f).toContain("data:image/png;base64")
expect(f).toContain("@path")
expect(f).toContain("web, Desktop or Android app")
})
})
test("over SSH in kitty: ctrl+v asks the terminal for its clipboard, and the image arrives as [Image 1]", async () => {
await withEnv({ SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-kitty", TMUX: undefined, STY: undefined, ZELLIJ: undefined }, async () => {
t = await tui([], undefined, "kitty_clipboard: true\n")
const a = box(t.setup.renderer.root)
const r = t.setup.renderer as any
const b64 = (s: string) => Buffer.from(s).toString("base64")
const asked: string[] = []
// The terminal's half, answered through the renderer's own input: what kitty would send back.
r.writeOut = (seq: string) => {
if (!seq.startsWith("\x1b]5522;")) return
asked.push(seq)
const id = /id=([^:;]+)/.exec(seq)![1]
const want = Buffer.from(seq.slice(seq.lastIndexOf(";") + 1).replace("\x1b\\", ""), "base64").toString()
const reply = (meta: string, payload = "") => r.stdin.emit("data", Buffer.from(`\x1b]5522;type=read:status=${meta}:id=${id}${payload ? `;${payload}` : ""}\x1b\\`))
setTimeout(() => {
reply("OK")
if (want === ".") reply(`DATA:mime=${b64(".")}`, b64("text/plain image/png"))
else reply(`DATA:mime=${b64("image/png")}`, PNG_B64)
reply("DONE")
}, 5)
}
await t.input.typeText("see ")
t.input.pressKey("v", { ctrl: true })
const end = Date.now() + 4000
while (Date.now() < end && !a.plainText.includes("[Image 1]")) await t.settle(40)
expect(a.plainText).toBe("see [Image 1] ")
expect(asked.length).toBe(2)
})
})
test("what is dictated is added after a placeholder, which still stands for its text", async () => {
const stt = Bun.serve({ port: 0, fetch: () => Response.json({ text: "Explain this." }) })
const mic = join(import.meta.dir, "..", "fixtures", "voice", "mic.ts")
try {
t = await tui([{ chunks: [delta({ content: "Explained." }), usage(100, 5)] }], { width: 100, height: 30 }, `voice:\n stt: { base_url: "http://127.0.0.1:${stt.port}/v1" }\n recorder_command: ["${process.execPath}", "${mic}", "1"]\n silence_seconds: 0.4\n`)
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText(LONG)
await t.settle()
t.input.pressKey("t", { ctrl: true })
const end = Date.now() + 8000
while (Date.now() < end && !a.plainText.includes("Explain this.")) await t.settle(40)
expect(a.plainText).toBe("[Pasted text 4 lines] Explain this.")
t.input.pressEnter()
expect(await t.until("Explained.")).toBe(true)
expect(sent()).toContain("first line\\nsecond line\\nthird line\\nfourth line Explain this.")
} finally {
void stt.stop(true)
}
})
// ---- found in review ----
test("a paste over a selection: the placeholder goes where the text went, and still stands for it — text and image", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }, { chunks: [delta({ content: "ok2" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
// Shift+Right from the start: the cursor ends up after the selection, the text goes in before it.
await t.input.typeText("hello world")
a.cursorOffset = 0
for (let i = 0; i < 5; i++) t.input.pressArrow("right", { shift: true })
await t.settle()
expect(a.hasSelection()).toBe(true)
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toContain("[Pasted text 4 lines] ")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toContain("first line\\nsecond line\\nthird line\\nfourth line")
expect(sent()).not.toContain("[Pasted text")
// A mouse drag over the box, then an image pasted in its place.
const png = join(t.cwd, "pic.png")
writeFileSync(png, Buffer.from(PNG_B64, "base64"))
await t.input.typeText("hello world")
await t.settle()
const lines = t.frame().split("\n")
const y = lines.findIndex((l) => l.includes("❯ hello world"))
const x = lines[y]!.indexOf("hello world")
await t.setup.mockMouse.drag(x, y, x + 5, y)
await t.settle()
expect(a.hasSelection()).toBe(true)
await t.input.pasteBracketedText(png)
await t.settle()
expect(a.plainText).toContain("[Image 1] ")
t.input.pressEnter()
expect(await t.until("ok2")).toBe(true)
expect(sent(1)).toContain(`@${png}`)
expect(sent(1)).not.toContain("[Image 1]")
})
test("the same paste twice is two copies unless it is the opening gesture: the cursor where the first paste left it", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.pasteBracketedText(LONG)
await t.settle()
// Something typed in between — even in place of the space — and it is a second copy; the
// typed character stays.
t.input.pressBackspace()
await t.input.typeText("Q")
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe("[Pasted text 4 lines]Q[Pasted text 4 lines] ")
// Elsewhere in the box: a copy, not the gesture.
a.cursorOffset = 0
await t.input.pasteBracketedText(LONG)
await t.settle()
expect(a.plainText).toBe("[Pasted text 4 lines] [Pasted text 4 lines]Q[Pasted text 4 lines] ")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toStartWith(JSON.stringify(`${LONG} ${LONG}Q${LONG}`).slice(0, -1))
})
test("a placeholder is one thing: cutting into it removes all of it, never a stump with its text silently gone", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }])
const a = box(t.setup.renderer.root)
await t.input.typeText("pre ")
await t.input.pasteBracketedText(LONG)
await t.settle()
// A selection from inside "pre" into the middle of the label, deleted.
a.setSelection(2, 10)
await t.settle()
t.input.pressBackspace()
await t.settle()
expect(a.plainText).toBe("pr ")
// Undo brings the whole placeholder back, and it still stands for its text.
a.undo()
a.undo()
await t.settle()
if (!a.plainText.includes("[Pasted text 4 lines]")) a.undo()
await t.settle()
expect(a.plainText).toContain("[Pasted text 4 lines]")
// Kill to the end of the line from inside the text before it takes the placeholder whole.
a.setText("")
await t.input.typeText("one two ")
await t.input.pasteBracketedText(LONG)
await t.settle()
a.cursorOffset = 4
t.input.pressKey("k", { ctrl: true })
await t.settle()
expect(a.plainText).toBe("one ")
await t.input.typeText("three")
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
expect(sent()).toStartWith('"one three\\n')
})
test("a paste of white space is white space, not a clipboard read", async () => {
t = await tui([])
const a = box(t.setup.renderer.root)
await t.input.typeText("x")
await t.input.pasteBracketedText("\n")
await t.settle(300)
expect(a.plainText).toBe("x\n")
expect(t.frame()).not.toMatch(/clipboard|no image/)
})
test("a session whose first prompt is a paste is titled by its words, and the prompt event carries them; only this transcript shows the label", async () => {
t = await tui([{ chunks: [delta({ content: "ok" }), usage(100, 5)] }], undefined, "titles: prompt\n", { store: true })
const prompts: { text: string }[] = []
t.app.bus.on((e) => void (e.type === "prompt" && prompts.push(e)))
const pasted = `Please review this function carefully and say what is wrong with it, in order of importance\nfunction a() {}\nfunction b() {}\nfunction c() {}`
await t.input.pasteBracketedText(pasted)
await t.settle()
t.input.pressEnter()
expect(await t.until("ok")).toBe(true)
await t.settle(200)
expect(t.frame()).toContain("┃ [Pasted text 4 lines]")
expect(prompts[0]!.text).toBe(pasted)
const title = t.app.store!.session(t.app.engine.sessionId!)!.title
expect(title).toStartWith("Please review this function carefully")
expect(title).not.toContain("[Pasted")
expect(title).not.toContain("function a")
expect(title.length).toBeLessThanOrEqual(80)
})
test("over SSH in kitty: off unless turned on; a reply that stalls inside a packet types nothing into the box and saves nothing", async () => {
const SSH = { SSH_CONNECTION: "192.0.2.1 50000 192.0.2.2 22", DISPLAY: undefined, WAYLAND_DISPLAY: undefined, TERM: "xterm-kitty", TMUX: undefined, STY: undefined, ZELLIJ: undefined }
const b64 = (s: string) => Buffer.from(s).toString("base64")
await withEnv(SSH, async () => {
// Off by default: the terminal is never asked, and the line says what works.
t = await tui([], { width: 220, height: 30 })
let asked = 0
;(t.setup.renderer as any).writeOut = (seq: string) => void (seq.startsWith("\x1b]5522;") && asked++)
t.input.pressKey("v", { ctrl: true })
expect(await t.until("no image reached this terminal over SSH")).toBe(true)
expect(asked).toBe(0)
t.stop()
t = await tui([], { width: 220, height: 30 }, "kitty_clipboard: true\n")
const a = box(t.setup.renderer.root)
const r = t.setup.renderer as any
const before = existsSync(join(paths.state, "clipboard")) ? readdirSync(join(paths.state, "clipboard")).length : 0
r.writeOut = (seq: string) => {
if (!seq.startsWith("\x1b]5522;")) return
const id = /id=([^:;]+)/.exec(seq)![1]
const want = Buffer.from(seq.slice(seq.lastIndexOf(";") + 1).replace("\x1b\\", ""), "base64").toString()
const emit = (s: string) => r.stdin.emit("data", Buffer.from(s))
const reply = (meta: string, payload = "") => `\x1b]5522;type=read:status=${meta}:id=${id}${payload ? `;${payload}` : ""}\x1b\\`
setTimeout(async () => {
emit(reply("OK"))
if (want === ".") return void (emit(reply(`DATA:mime=${b64(".")}`, b64("text/plain image/png"))), emit(reply("DONE")))
// The packet stops arriving half-way for longer than the input parser waits.
const whole = reply(`DATA:mime=${b64("image/png")}`, PNG_B64)
emit(whole.slice(0, 60))
await Bun.sleep(80)
emit(whole.slice(60))
emit(reply("DONE"))
}, 5)
}
await t.input.typeText("see ")
t.input.pressKey("v", { ctrl: true })
expect(await t.until("did not arrive whole")).toBe(true)
expect(a.plainText).toBe("see ")
expect(existsSync(join(paths.state, "clipboard")) ? readdirSync(join(paths.state, "clipboard")).length : 0).toBe(before)
// The box takes input again once the read is over.
await t.input.typeText("now")
expect(a.plainText).toBe("see now")
})
})