Compare commits

...
Author SHA1 Message Date
HomerandClaude Fable 5.2 c2e4b7525f 2.0.0-beta.13: harness spec 3.10.0, a turn the harness starts is a turn like any other
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 07:43:54 +00:00
HomerandClaude Fable 5.2 0ea110c1d3 A steered message is given to the model once; a prompt's turn carries its late steers too
ci / check (push) Canceled after 0s
Spec (3.10.0, unreleased; part of capability harness_turns), acp.md
_lembas/steer:

- A session/prompt whose turnId is the messageId of a steered message the
  device still knows does not run. It is answered at once, stopReason
  "end_turn", with _meta.lembas.steered: "taken" (the model has been given
  it), "carried" (it waits for the next turn's first step) or "waiting" (it
  is in the running turn's queue). A client that lost the link and cannot
  tell what became of a message can send it again safely. An id handed back
  as unsent is the client's again and runs. The ids of the last 200 messages
  taken in are kept with the session, across a restart.
- A prompt's turn that ends with no link up carries its too-late steers to
  the next turn's first step, as a turn the harness started does: unsent in
  an answer nobody reads was a message lost. With a client there, unsent as
  before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 17:43:12 +00:00
HomerandClaude Fable 5.2 9f26316a49 session/cancel may name its turn: a queued prompt is taken back, the running turn left alone
ci / check (push) Canceled after 0s
A prompt can wait behind a turn its client did not start, and ACP's cancel
names no turn: a client stopping a reply whose prompt still waited stopped
whatever ran instead, and its own prompt ran later with nobody following.

Spec (3.10.0, unreleased; part of capability harness_turns): an optional
_meta.lembas.turnId on session/cancel. Running: stopped. Queued: taken out
of the queue, its session/prompt answered stopReason "cancelled" at once (a
scheduled one with scheduled.status "cancelled"), the running turn not
touched, the id still known. Neither: nothing. Without the id: the running
turn, as before. Sent as a request, the cancel is answered
{ cancelled: "running" | "queued" | "none" }. conformance/cancel.json, 7
cases (acp/turns.ts cancelOf).

Device: acp/agent.ts (a prompt that waits can be withdrawn), and for a
session a terminal runs acp/share.ts (hub/cancel as a request with the
turn; a web prompt not yet started there is withdrawn, and nothing is sent
when its place comes). A terminal of a build without that request is not
told to stop whatever runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 16:09:21 +00:00
HomerandClaude Fable 5.2 87ecaca6db Work a session still has out is not lost: subagents, jobs, notes and steers
ci / check (push) Canceled after 0s
Seven findings of a review of the wake-turn work, each with a test that
failed before (tests/acp-outstanding.test.ts).

1. A session whose subagents work, or whose background command runs, with no
   turn running was idle to the service: an update restarted it under them
   and a terminal opening the session stopped them, so no report came. It is
   occupied now (acp/agent.ts occupied, keeps; hub.busy): no restart, no
   close of the link, and a terminal is refused in words that name what runs
   — also while no link is up, when nothing judged it at all.
2. A scheduled run that used a team answered with the reply that ended the
   main agent's first turn, and the real answer came in a turn report_write
   was not offered in. The run's turn now waits for its subagents and takes
   their reports in (engine awaitReports, EngineOptions.hold): one turn, the
   answer and the report from its last reply.
3. Stop while a turn waited for a model slot lost the note that started it
   (and a person's own message, and whatever waited to go in with it): the
   message is in the conversation now, under the turn's id.
4. A steer a harness turn never took in, with no client listening, stayed in
   memory: lost by a restart, and in queue mode handed back with a later
   prompt. It is kept with the session (CARRIED_META) and taken in at the
   next turn's first step in every mode, said with its id.
5. A wake refused for an interactive-only model left the main agent marked
   working, holding its slot, and dropped the report: the session is idle
   again and the note is kept for the next message.
6. Stop on a scheduled run stops its subagents, as does any other end of the
   run's turn with subagents out. In a chat Stop stops the turn and no
   subagent, as the terminal's Esc does: pinned by a test, not changed.
7. The task end that carries unsent is said before the inbox event that
   empties the queue.

Notes left after a Stop are kept with the session too (engine.keepNote), so
a restart does not lose them. AcpAgent.holding, anyBusy and drop had no
caller left and are gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 15:26:42 +00:00
HomerandClaude Fable 5.2 1f3eb92666 spec 3.10.0, amended: a run waits for its subagents; a session with work out; Stop and steer said whole
Amended before any release carried 3.10.0, after a review of the implementation.
No capability, field or method is added.

- acp.md, Scheduled work: a scheduled turn does not end while a subagent it
  started is still out. The turn stays open (waiting_for_subagents), each
  report comes into the same turn, the answer's text and report are from the
  last reply. Background commands are not waited for. Stop on a scheduled
  turn, and any other end with subagents still out, stops them.
- acp.md, A session that still has work out: with no turn running, a working
  or waiting subagent, a report about to wake the main agent, or a background
  command makes the session not idle for the device: the link is not closed
  for a change of limits, a service does not start again for an update, and
  a terminal that opens the session is refused in words.
- acp.md, session/cancel and A turn the harness starts: Stop stops the turn
  and no subagent; a turn stopped while it waited for a slot is in the
  history like any stopped turn; undelivered notes are kept with the session.
  A steer nobody could be handed is kept with the session and taken in at the
  next turn's first step, never also handed back; the task end that carries
  unsent comes before the inbox event that empties the queue. A wake that may
  not start a turn leaves the session idle and the note kept.
- reports.md §2: the run is the schedule's turn, whole.
- conformance/outstanding.json (8 cases) and its runner,
  src/session/outstanding.ts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 15:26:31 +00:00
HomerandClaude Fable 5.2 7319ea52cb A wake turn is busy, steerable and queued behind, and the history marks it
ci / check (push) Canceled after 0s
In a session the service holds, "a turn runs" was `prompting`, which only a
session/prompt sets. A turn the harness started (a job's note waking the
session) therefore read as idle: status said not busy and named no turn, a
steer was refused, compact and rewind were let through, the session could be
let go of and the link closed under it, and a prompt that arrived meanwhile
ran into the engine, failed with "busy" and left the turn log saying the
wrong turn had finished.

The link's agent now follows every `task` event: a turn no prompt of the
client's began is kept in the session's turn log (as a terminal's turns are)
and holds the prompt queue until its end. `working()` is the one question
status, steer, compact, rewind and letting go ask. A message steered into
such a turn and not taken in goes back as `unsent` on its `task` end.
`_lembas/session/history` marks the note's user turn `machine`.

tests/acp-wake-turn.test.ts: status during the turn, the history, a steer
joining it, Stop, a prompt waiting behind it, and two notes in a row — as two
turns in order, and as one turn when the second arrives while the first runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 12:52:17 +00:00
HomerandClaude Fable 5.2 2469709dc0 spec 3.10.0: a turn the harness starts is a turn like any other over the link
A note that wakes an idle session (a finished job, a subagent's or a team's
report) already had an id of its own on its task and prompt events. The spec
did not say what a client may ask about such a turn. acp.md now does, in a
section of its own and on each method:

- capability `harness_turns`;
- status: busy, the turn named, then lastTurnId;
- steer: accepted; what the turn ended before taking in comes back as
  `unsent` on its `task` end event;
- cancel stops it; a prompt waits behind it; compact and rewind are refused;
- history: its user turn carries `machine`, its turnId and the whole note;
- the order of its events, that turns never overlap, and what two notes in a
  row are;
- the client never sends such a row to the device as a prompt.

conformance/reattach.json (9 cases) is the client's decision for a row after a
restart, for a person's turn and for the harness's; the CLI keeps that rule in
acp/turns.ts for the cases, as it keeps the client's model rule.

blocks/team_lead.md, one bullet more: a report starts the main agent's next
turn by itself; it answers the person then, unasked, and never tells the
person to ask again.

Clarified, not changed: on a machine turn's prompt event, `text` is the line a
transcript shows, not the whole note.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 12:52:17 +00:00
24 changed files with 2165 additions and 72 deletions

No files matched your search

+61 -1
View File
@@ -4,7 +4,67 @@ 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/).
## [Unreleased]
## [2.0.0-beta.13] — 2026-11-24
Harness spec 3.10.0: a turn the harness starts by itself is a turn like any other over the link.
### Added
- **Harness spec 3.10.0: a turn the harness starts** (`harness/acp.md`, capability
`harness_turns`). When a background job or a subagent finishes while the session is idle, its
note starts a turn by itself. In an agent chat driven from the web, that turn now behaves like
one you started: the chat shows it as working and can follow it after a restart or a dropped
connection, and the session's history marks the note as the harness's (`machine`) rather than
as something you typed. The server uses this from the version that carries spec 3.10.0.
### Fixed
- **A message sent while the agent answers a subagent's report is no longer refused.** It joins
that turn at its next step, as it does during a turn you started; one the turn ended before
taking in is handed back to the web UI to send next instead of being lost.
- **A prompt sent while the agent answers a finished job or a subagent's report waits its turn.**
It used to fail with `busy`, and left the session's record of which turn was running wrong.
- **Compacting or rewinding a session is refused while such a turn runs**, and the service no
longer lets go of the session, or closes the link for a change of `remote:` settings, under it.
- **A schedule that uses subagents now reports its real answer.** A scheduled run on this
computer used to answer as soon as the main agent had started its subagents ("they are on
it"), and the result arrived later in a turn that could not file a report. The run now stays
open until its subagents have reported, shows *Waiting for subagents* meanwhile, and its answer
and its report come from the last reply. Stopping the run stops its subagents too.
- **Subagents and background jobs are no longer cut off by the service.** While a session's
subagents were working and the main agent was idle, the service counted the session as idle: an
update restarted it under them, and opening the session in a terminal stopped them without a
word, so their reports never came. The service now waits for them before it restarts or
redials, and a terminal that opens such a session is told what still runs and how to stop it.
- **Stopping a turn that was waiting for a free model slot no longer loses what started it.** A
finished job's note, or your own message, stays in the conversation and the model reads it with
the next message.
- **A message sent from the web while the link drops is not lost.** If the agent was answering a
subagent's report and finished before taking your message in, with no connection to hand it
back over, the message is kept with the session — also across a restart of the service — and
the agent reads it at the start of its next turn. It used to wait in memory, and with
`busy_input: queue` came back attached to an unrelated later prompt.
- **A message is never given to the agent twice.** After a dropped connection the web UI may not
know whether a message you sent while the agent worked was read; sending it again is now safe —
the agent recognises it and says whether it was read already or is waiting for the next turn.
A message the agent had no time for when the connection was down is kept for its next turn
after any kind of turn, not only one it started by itself.
- **Stop in the web UI stops the reply you stopped.** If your message was still waiting behind a
turn the agent had started by itself (answering a finished job or a subagent), Stop used to end
that turn instead and your message ran afterwards anyway. A server that names the turn
(harness spec 3.10.0) now gets exactly that turn stopped, or taken out of the queue.
- **A job's or subagent's note that arrives after you pressed Stop survives a restart** and goes
in with your next message, as before.
- **In a schedule's chat on a model for interactive use only**, a subagent's report that may not
start a turn by itself no longer leaves the main agent marked as working: the session is idle
and the report goes in with your next message.
### Changed
- **The main agent is told plainly how reports reach it** (`blocks/team_lead.md`): it does not
wait or ask for them, each one starts its next turn, and it then answers you unasked — it never
tells you to ask again. Sessions started before this keep the prompt they began with.
## [2.0.0-beta.12] — 2026-11-18
+71 -1
View File
@@ -36,7 +36,7 @@ page *Harness-parity* in LLeMbas CLI's wiki.
| `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; scheduled work on a linked computer (3.5.0) and the two types of schedule, Chat and Agentic (3.9.0); the model last used in a directory (3.9.0) |
| `acp.md` | The link between them: ACP plus every `_lembas/*` method, field and capability; scheduled work on a linked computer (3.5.0) and the two types of schedule, Chat and Agentic (3.9.0); the model last used in a directory (3.9.0); a turn the harness starts by itself, over the link (3.10.0) |
## Vocabulary
@@ -79,6 +79,76 @@ 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.10.0
Written with the CLI's implementation, after a turn the harness started was found to be half a turn
over the link. A new capability and two fields; one prompt text made plainer; no tool.
- **A turn the harness starts is a turn like any other over the link** (`acp.md`, section of that
name; capability `harness_turns`; `conformance/reattach.json`, 9 cases). A note that wakes an idle
session — a finished job's, a subagent's or a team's report — already had an id of its own on
its `task` and `prompt` events. What is new is everything a client asks *about* it:
`_lembas/session/status` says `busy` and names it (`turnId`, then `lastTurnId`, kept across a
restart); `_lembas/steer` is accepted while it runs, and a message it ended before taking in
comes back as **`unsent` on its `task` end event** (it has no prompt's answer to carry it);
`session/cancel` stops it; a `session/prompt` that arrives meanwhile **waits its turn** and is
listed in `queued`; compacting and rewinding are refused while it runs; the link is not closed
under it. **`_lembas/session/history` marks its user turn `machine`**, with its `turnId` and the
whole note as `text`. Written down as well: the order of such a turn's events, that turns never
overlap, and what two notes in a row are (one turn with both, or two turns one after the other).
- **The client's side**: the row of such a turn is never sent to the device as a prompt — not on
seeing it, and not on reattaching when the device no longer knows its id; then what the history
has for that id is imported. `conformance/reattach.json` is that decision, for a person's turn
and for the harness's.
- **Clarified, not changed**: on a `machine` turn's `prompt` event, `text` is the line a transcript
shows (`⏎ ` and the note's first line), not the whole note.
- **`blocks/team_lead.md`**, one bullet more: the main agent does not wait for a report or ask for
one; a report starts its next turn by itself, and when the reports it needs are in it answers the
person in that turn, unasked, and never tells the person to ask again. A session keeps the system
prompt it was started with (`context.md` §10), so only sessions started after the change read it.
Amended before any release carried it, after a review of the CLI's implementation found work that
could be lost around such turns. No capability, field or method is added by these; a client that
follows 3.10.0 as first written follows this.
- **A schedule's run waits for its subagents** (`acp.md`, *Scheduled work* → *The run waits for its
subagents*; `reports.md` §2). A scheduled turn on a device does not end while a subagent it
started is still out: the turn stays open (`waiting_for_subagents`), each report reaches the main
agent in the same turn, and the answer's `text` and `report` come from the last reply. Before,
the run answered with the reply that ended the main agent's first turn ("the subagents are on
it") and the real answer came in a turn `report_write` was not offered in. A run is one turn;
background commands are not waited for; Stop on a scheduled turn stops the run's subagents too,
and so does any other end of the turn with subagents still out.
- **A session that still has work out** (`acp.md`, section of that name; `conformance/outstanding.json`,
8 cases): with no turn running, a subagent that works or waits, a report about to wake the main
agent, or a background command makes a session *not idle* for the device — the link is not
closed for a change of limits, a service does not start again for an update, and a terminal
opening the session is refused in words. `status.busy` still means "a turn runs".
- **Stop, said whole** (`session/cancel`; *A turn the harness starts*): it stops the turn and no
subagent (the scheduled turn apart); a turn stopped while it waited for a model slot is in the
history like any stopped turn, its note with it; notes a stopped turn had not delivered are kept
with the session, across a restart.
- **A steer nobody could be handed** (*A turn the harness starts*, Steer): kept with the session,
across a restart, and taken in at the next turn's first step in every mode — said with `steered`
and its id — and never also handed back as `unsent`. And the `task` end that carries `unsent`
comes before the `inbox` event that says the queue is empty.
- **A wake that may not start a turn** (a schedule's session on an interactive-only model): the
session is idle again and the note is kept for the person's next message.
- **A steered message is given to the model once** (`_lembas/steer`; part of `harness_turns`). A
prompt's turn that ends with no link up carries its too-late steers to the next turn, as a
harness turn does — an `unsent` in an answer nobody reads was a message lost. And a
`session/prompt` whose `turnId` is the `messageId` of a steered message the device still knows
(taken in, carried, or waiting in the running turn) does not run: it is answered with
`_meta.lembas.steered` saying which. A client that lost the link can send again safely.
- **`session/cancel` may name its turn** (`_meta.lembas.turnId`; part of `harness_turns`, which no
release has carried yet; `conformance/cancel.json`, 7 cases). A prompt can now wait behind a
turn its client did not start, and a cancel that names no turn stops whatever runs: a client
stopping a reply whose prompt still waited stopped the harness's turn instead, and its own
prompt ran later with nobody following. With the id: the turn is stopped if it runs; taken out
of the queue if it waits — its `session/prompt` answered `cancelled`, the running turn left
alone; nothing if it is neither. Sent as a request, the cancel is answered
`{ cancelled: "running" | "queued" | "none" }`. Without the id, as before.
## 3.9.0
Written ahead of the implementations; the CLI carries it in the same round. A new capability and
+1 -1
View File
@@ -1 +1 @@
3.9.0
3.10.0
+194 -11
View File
@@ -69,6 +69,7 @@ change to the protocol is a change here first, then in both projects.
| `tree` | spec 3.4.0 (`subagents.md` §5–§13): the `team` event; `_lembas/team`, `_lembas/team/transcript`, `_lembas/team/findings`, `_lembas/team/stop`; `subagent` on `session/request_permission` |
| `scheduled` | spec 3.5.0 (*Scheduled work on a linked computer*, below): `scheduled` in `_meta.lembas` of `session/new` and `session/prompt` read, and the run's outcome in the prompt's answer; `scheduled` on `session/request_permission`; `_lembas/monitor`; `limits.scheduled` in `_lembas/hello` and `initialize`. Listed by every build that has it, whatever the setting says: whether this device *accepts* scheduled work is `limits.scheduled` |
| `directory_model` | spec 3.9.0 (*The model last used in a directory*, below): `model` on a `Dir` of `_lembas/directories`' answer; `list: false` in its params |
| `harness_turns` | spec 3.10.0 (*A turn the harness starts*, below): such a turn is a turn in `_lembas/session/status` (`busy`, `turnId`, then `lastTurnId`), takes `_lembas/steer`, hands back `unsent` on its `task` end, makes a prompt wait, and is in `_lembas/session/history` as a user turn with `machine`; and — since prompts now wait behind turns the client did not start — `_meta.lembas.turnId` on `session/cancel` names the turn to stop or to take out of the queue, and `session/cancel` sent as a request is answered |
| `reports` | spec 3.8.0 (`reports.md` §6): `scheduled.notify` in `_meta.lembas` of `session/new` and `session/prompt` read; `report_write` offered to the model of a schedule's run that notifies; the report the run wrote carried in the prompt's answer (`scheduled.report`); the status `silent` no longer given to a turn whose request said `notify` |
## Standard ACP, as used here
@@ -196,14 +197,16 @@ message id). The device keeps, per session, the last 200 ids it accepted with th
and every terminal use alike, so they outlive a restart and a session moving between a terminal and
the service in either direction; files untouched for 30 days are pruned — and **a prompt with a known turnId does not run again**: it gets the
original's answer — when that one is done, or at once if it is. Without a `turnId` the device makes
one. A prompt that arrives while the session works waits its turn.
one. A prompt that arrives while the session works waits its turn — behind a turn the harness
started as behind any other (*A turn the harness starts*).
Result: `{ stopReason: "end_turn" | "max_turn_requests" | "max_tokens" | "cancelled", _meta: { lembas: { turnId, … } } }`,
where `_meta.lembas` may also carry:
| Field | When |
|---|---|
| `unsent: string[]` | messages sent with `_lembas/steer` that the turn ended before taking in — send them next |
| `unsent: string[]` | messages sent with `_lembas/steer` that the turn ended before taking in — send them next. Only in an answer a client is there to read: when no link is up as the turn ends, they are carried to the next turn instead (`_lembas/steer`, *A steered message is given to the model once*) and this answer, kept for a resend, has none |
| `steered: "taken" \| "carried" \| "waiting"` | spec 3.10.0 (capability `harness_turns`): the `turnId` is the `messageId` of a message this session was steered — **nothing ran**; what became of that message (`_lembas/steer`, below) |
| `command: string` | the prompt was that command |
| `summary: string` | `/compact` |
| `undone: { prompt, files } \| null` | `/undo` (null: nothing to undo) |
@@ -214,9 +217,42 @@ where `_meta.lembas` may also carry:
Params: `{ sessionId, modeId }`, lowered to `remote.max_mode`. Result `{}`.
### `session/cancel` — client → agent (notification)
### `session/cancel` — client → agent (notification, or a request)
Params: `{ sessionId }`. Stops the running turn.
Params: `{ sessionId, _meta?: { lembas?: { turnId?: string } } }`.
**Without a `turnId`** — ACP's own cancel, and all a device before 3.10.0 knows: stops the running
turn, whoever started it: the client's prompt, a turn typed in a terminal, or one the harness
started. Prompts waiting behind it still run.
**With `_meta.lembas.turnId`** (spec 3.10.0, capability `harness_turns`; `conformance/cancel.json`)
the client says **which turn it means** — where `session/prompt` carries the same id, in
`_meta.lembas` like every other extension of an ACP method — and only that turn is touched:
| The turn named is | The device |
|---|---|
| **running** | stops it, as a cancel without an id does |
| **queued** (its `session/prompt` waits behind another turn) | takes it out of the queue: it never runs, its `session/prompt` is answered at once with `stopReason: "cancelled"` (a scheduled one with `scheduled.status: "cancelled"`), and **the turn that runs is not touched**. The id stays known: the same prompt sent again gets that answer and does not run |
| **neither** (finished already, or never heard of) | does nothing |
Without the id a client that stops a reply whose prompt still waits on the device stops whatever
runs there instead — the harness's own turn, a terminal's — and its own prompt runs afterwards
with nobody following it. A client sends the id whenever it knows the turn it means and the
device lists `harness_turns`; a device without the capability ignores `_meta` and stops the
running turn, so to such a device a client sends a cancel only when its own turn is the one
running (`_lembas/session/status`).
**The answer.** As a notification it is answered with nothing, as ACP has it. Sent as a
**request** (the same method and params, with an id) a device with the capability answers
`{ cancelled: "running" | "queued" | "none" }` — what it found the turn to be, or for a cancel
without an id whether a turn ran — so a client that needs to know whether anything was stopped
asks, and one that does not need not wait.
**It stops
the turn, not the team**: subagents that work go on, and a report that arrives later starts a turn
as any does (*A turn the harness starts*) — a subagent is stopped by `_lembas/team/stop`. The one
exception is a scheduled turn, where Stop stops the run and its subagents with it (*Scheduled
work*, *The run waits for its subagents*).
### `session/update` — agent → client (notification)
@@ -443,6 +479,35 @@ In a scheduled turn:
- Subagents as in an agent chat (`agents`, the tree, findings); a subagent's call only the person
can allow is an approval like the main agent's, with `scheduled` beside `subagent`.
**The run waits for its subagents** (spec 3.10.0; `conformance/outstanding.json`, `run_waits`). In
a chat the main agent's turn may end while subagents work, and each report wakes it with a turn
of its own (`subagents.md` §9). A run has nobody to read those turns and one answer to give, so
**a scheduled turn does not end while a subagent it started is still out** — a team's subagent
that is `working`, `waiting` or `paused`, a background `task` subagent still running — or while a
report waits for the main agent to get a slot:
- When the main agent's reply ends with subagents out, the turn stays open: its progress is
`waiting_for_subagents` (`progress.md` §4), it holds no slot of its model meanwhile (`team.md`
§8, and takes one again before it goes on), and **each report reaches it in the same turn**, as
a note at a step boundary (`team.md` §7) — never as a turn of its own. The model reads exactly
what a woken turn would have given it.
- So a run is **one turn**, from its `task` start to its `task` end, with the run's `turnId` on
every event; `report_write` is offered throughout; and the answer's `text` and `report` are
from the turn's last reply — given after the last report came in.
- **Background commands are not waited for** — one may never end. A command the run left running
is still the run's (`interactive.md` §2): its note later wakes a turn of the session, which is
scheduled work, and in which `report_write` answers its `unavailable` text: the run has
answered, and there is no answer left to carry a report.
- **What bounds the wait**: nothing new. Every subagent's own turn ends by its step limit and its
budgets; the session's time budget, where one is set, counts the wait (looked at when the
next report comes in, as between any two steps); and a run that says
nothing for the client's inactivity limit is stopped by the client, as any run is. While it
waits, the tree (`team`), the subagents' tool calls (`sub_tool`) and their phases are still said.
- **Stop (`session/cancel`) on a scheduled turn stops the run**: the turn, and every subagent of
it that still works or waits. The same when the turn ends any other way with subagents still
out — an error, the step limit, a budget: they are stopped with it, and none of them leaves a
note. **Nothing of a run's subagents works after its answer.**
### How the turn ends and reports
`session/prompt`'s answer carries the run's outcome in `_meta.lembas.scheduled`:
@@ -609,6 +674,94 @@ for a schedule's run on a device (*Scheduled work*, *The run's model*).
(`kind: client` — the model a chat or a run starts on, from what was named, what the directory
says, the models the person has and the default.)
## A turn the harness starts (spec 3.10.0)
Capability `harness_turns`. A note that reaches an idle session — a finished job's, a subagent's
report or message, a team's report or message — **wakes** it: the harness starts a turn by itself,
with the note as its user message (`loop.json` `jobs`, `team.md` §7). Nobody typed it and no
`session/prompt` began it. **Over the link it is a turn like any other**:
- **Its id.** The device makes one for it — a new one for every such turn, the same from its start
to its end — and says it on the turn's `task` start, on its `prompt` event (with `machine: true`)
and on its `task` end. A client tells two harness turns in a row apart by it.
- **Its events, in order.** `task` start, `prompt`, the turn's own events (steps, text, tool calls),
`task` end. A job's note is said first, as `job_note`, before the `task` start of the turn it
starts. **Turns never overlap**: no event of the next turn — its `task` start included — comes
before this one's `task` end, whoever started either.
- **Two notes in a row.** A note that arrives while any turn runs — the first note's turn included —
starts no turn: it goes to the model at that turn's next step (a `job_note` says so, where it is
a job's) and the turn carries on with it, even past what would have been its last step. A note
that arrives after the turn's end starts the next turn. So two subagents finishing one after the
other are one turn with both notes or two turns one after the other, by when the second finished;
never two at once.
- **Status** (`_lembas/session/status`): `busy: true` and `turnId` its id while it runs;
`lastTurnId` its id once it has ended, kept across a restart as any finished turn is.
- **Steer** (`_lembas/steer`): accepted while it runs, taken in at its next step, said with
`steered`. A message it ended before taking in comes back as `unsent` on its `task` end event —
it has no prompt's answer to carry it — and the client sends it next, as it does a prompt's
`unsent`. That `task` end comes **before** any `inbox` event that says the queue is empty, so an
emptied queue is never read as messages taken in. With no client listening (no link is up) the
message is **kept with the session — across a restart of the device — and goes in at the next
turn's first step**, whoever starts that turn and whatever the device's own setting for messages
typed mid-task: it is said with `steered` and its id there, and is never handed back as `unsent`
as well. In a session a terminal runs it stays in the terminal's own queue.
- **Stop** (`session/cancel`): stops it — and nothing else: no subagent is stopped with it, and a
report that arrives afterwards starts a turn as any does. Notes it had not given the model yet
start no further turn: they are kept with the session — across a restart — and go in with the
person's next message. A turn stopped **while it still waits for a model slot** (`team.md` §8)
had already begun for the client — its `task` start and its `prompt` were said — so it is a
stopped turn like any other: its user turn is in the history under its id, the note with it,
and the model reads it with the next message. Nothing of it is lost.
- **A prompt** (`session/prompt`) that arrives while it runs waits its turn — it is in `queued` —
and runs after the turn's `task` end; the client that no longer wants it takes it back with
`session/cancel` and its `turnId`, which leaves this turn alone. A prompt carrying the harness turn's own id does not run:
the id is known, and the answer is `null` (the turn has none of this side's).
- **Compacting and rewinding** (`_lembas/session/compact`, `_lembas/session/rewind`) are refused
while it runs, as during any turn. Once it has ended it is rewound by its id like any turn.
- **History** (`_lembas/session/history`): its user turn is there, with its `turnId`, `machine: true`
and the whole note as `text`; the reply follows it.
- **The link** is not closed for a change of limits while one runs (*`_lembas/hello`*: "once no
session is working"), nor while one is about to: see *A session that still has work out*.
- **Scheduled sessions.** A turn a schedule's job wakes is the schedule's work: it does not run on
an interactive-only model (`interactive.md`), and the device says so in a `notice` instead. No
turn starts, so the session is idle again — the main agent holds no slot for it — and the note
is kept, as after a Stop: it goes in with the person's next message. During a schedule's run
itself no such turn starts at all: the run's turn takes its subagents' reports in (*The run
waits for its subagents*).
**The client's side.** The row it keeps for such a turn is the harness's (`machine`), keyed by the
turn's id; the reply after it is filled from the events between that id's `prompt` and its `task`
end, and from nowhere else. The client **never sends the row to the device as a prompt** — not
when it first sees it, and not when it reattaches and the device does not know the id any more (a
device restarted in the middle of the turn): then it imports what `history` has after the user turn
with that id, and closes the reply as it stands. `conformance/reattach.json` gives the decision for
a row with turn T from what `status` says.
A device without `harness_turns` (before 3.10.0) runs these turns the same way and says `prompt`
with `machine` and both `task` events with the id, but its `status` says `busy: false` and names no
turn while one runs, it refuses a steer then, and a prompt sent then fails (`-32603`); a client
follows such a turn by its `task` events alone and sends nothing to the session until its end.
## A session that still has work out (spec 3.10.0)
A session's turn may end with work of it still going on **in the device's process**: a subagent
that works or waits for a slot, a report about to wake the main agent, a background command.
`_lembas/session/status` then says `busy: false` — no turn runs — and shows the work in `tree` and
`jobs`. The device treats such a session as **not idle** wherever letting go of it would lose
that work (`conformance/outstanding.json`, `has_work`):
- it does not close the link for a change of limits (*`_lembas/hello`*), and a service does not
start again on a newly installed release, until no session has a turn running or waiting **and
none has work out**;
- **a terminal on the device that opens the session is refused, in words that name what still
works**, as it is while a turn runs. A terminal is another process: it could carry the
conversation on from the store, but not the subagents and commands, and closing the service's
copy would stop them with no report ever arriving. So the session stays where its work is; the
person waits, or stops the subagents and jobs (`_lembas/team/stop`, `_lembas/job/stop`), and
opens it then.
Deleting the session (`_lembas/session/delete`) still stops everything, as it says.
## `_lembas/*` methods
Direction is who sends it. "→ result" marks a request; the others are notifications.
@@ -628,7 +781,8 @@ that is not linked.
The device's limits apply to every request as they are at that moment. When what the hello and
`initialize` said changes (the device's `remote:` block was edited — a folder added, remote work
turned on), the device closes the link once no session is working and dials again at once, so the
turned on), the device closes the link once no session is working — no turn runs or waits, and no
session has work out (*A session that still has work out*) — and dials again at once, so the
client hears the new limits.
### `_lembas/event` — agent → client
@@ -641,8 +795,8 @@ client hears the new limits.
| Event | Fields |
|---|---|
| `prompt` | `text` (as the person sees it: a command's name, not its body), `turnId`, `attachments?: [{ name, mimeType, size }]`, `machine?: true` (capability `jobs`) — the turn was started by the harness, not typed: a finished job's or subagent's note, or a subagent's message, beginning with its mark (`loop.json` `jobs.marks`); a client shows it as such and sends it to no model of its own |
| `task` | `state: "start" \| "end"`, `turnId` — every turn has one: the client's, or one made here for a turn typed in a terminal |
| `prompt` | `text` (as the person sees it: a command's name, not its body), `turnId`, `attachments?: [{ name, mimeType, size }]`, `machine?: true` (capability `jobs`) — the turn was started by the harness, not typed: a finished job's or subagent's note, a subagent's message, or a team's report or message (`team.md` §7), each a note beginning with its mark (`loop.json` `jobs.marks`, `team.marks`). `text` is then the line a transcript shows for it — `⏎ ` and the note's first line: for a job's note the line after its mark, for a team's note the mark itself, which names who reports; the whole note is `text` of the `job_note` before it, where a job's, and of the turn in `history`. A client shows it as the harness's and sends it to no model of its own, and never back to the device as a prompt (*A turn the harness starts*) |
| `task` | `state: "start" \| "end"`, `turnId` — every turn has one: the client's, or one made here for a turn typed in a terminal or started by the harness. `unsent?: string[]` (capability `harness_turns`) on the `end` of a turn the harness started: the `_lembas/steer` messages that turn ended before taking in, as `unsent` in a prompt's answer — send them next |
| `steered` | `texts`, `ids?` — the `_lembas/steer` message ids taken in at this step |
| `mode` | `mode` |
| `model` | `ref` (the device's ref, above), `effort` (one of the model's levels: an effort, `"off"` or `"default"`), `connection` (the device connection it is spoken to through) and **`instance: boolean`** — true exactly when that connection is the login of **this link's** instance, i.e. the model is one the instance serves (its served id is `ref`, or `ref` less a leading `<connection>/`). Whenever either changes, for any reason: `/model`, `/effort`, the settings tool, a fallback, `_lembas/configure` |
@@ -716,13 +870,39 @@ Params `{ sessionId, model?: <instance's name>, effort?: <level>, agents?: { min
Params `{ sessionId, text, messageId? }`: a message for the running task, given to the model at its
next step. Result `{ queued: number }`. `-32602` when nothing runs: send it as a prompt instead.
"Runs" is any turn — the client's prompt, a terminal's, or one the harness started (capability
`harness_turns`; a device without it refuses a steer during a harness turn).
**A steered message is given to the model once** (spec 3.10.0, capability `harness_turns`). What
becomes of a message the device accepted, whichever kind of turn it was steered into:
- **taken in** at a step of that turn — said with `steered` and its `messageId`;
- **handed back** when the turn ended first and a client is there to hear it: `unsent` in the
prompt's answer, or on the `task` end of a turn the harness started. The device has let go of
it; the client sends it next, as a prompt;
- **carried** when the turn ended first and **no link is up** — after a prompt's turn exactly as
after a harness turn: kept with the session, across a restart, taken in at the next turn's
first step (said with `steered` and its id there), and never handed back as well. In a session
a terminal runs it stays in the terminal's own queue instead.
A client that lost the link cannot always tell which of these happened. So **a `session/prompt`
whose `turnId` is the `messageId` of a steered message the device still knows does not run**: it
is answered at once, `stopReason: "end_turn"`, with `_meta.lembas.steered` — `"taken"` (the model
has been given it, in some turn), `"carried"` (it waits for the next turn's first step) or
`"waiting"` (it is in the queue of the turn running now, and will be taken in or handed back).
Only a message that was handed back, or that the device never accepted, runs as a prompt. The
device keeps the ids of the last 200 messages taken in with the session, across a restart; a
client therefore uses one id for a message whether it steers it or prompts it (LLeMbas: the
message's id), and sending again is always safe.
### `_lembas/session/history` — client → agent → result
Params `{ sessionId }`. Result `{ sessionId, title, root, turns }`, each turn
`{ role: "user", text, turnId?, attachments?: [{ name, mimeType, size }] }` (`turnId`
the turn the message started — the client's, or the one made for a turn typed in a terminal — kept
with the message in the store; `attachments`, and the text without them) or `{ role: "assistant", text, reasoning, tools: [{ id, name, args, output?, isError? }] }`.
`{ role: "user", text, turnId?, attachments?: [{ name, mimeType, size }], machine?: true }` (`turnId`
the turn the message started — the client's, or the one made for a turn typed in a terminal or
started by the harness — kept with the message in the store; `attachments`, and the text without
them; `machine` (capability `harness_turns`) on a turn the harness started, whose `text` is the
whole note, beginning with its mark) or `{ role: "assistant", text, reasoning, tools: [{ id, name, args, output?, isError? }] }`.
### `_lembas/session/status` — client → agent → result
@@ -732,7 +912,10 @@ Params `{ sessionId }`. Result
without waiting for the next change; `progress` the main agent's progress object or `null` (capability `progress`), and `tree` the subagent tree or `null` when the session has none (capability `tree`), for the same reason; `jobs` the session's background jobs, `JobInfo[]` running first (capability `jobs`), for the same reason; the turn fields with capability `turns`: the turn running now, the ones waiting, the last
one finished (for a session not open, `held: "none"`, the last one it finished before). **Reattaching** after a restart or a dropped link, for an incomplete row with turn T:
T running → follow it; T queued → wait, and follow it when it starts; T done → import it from
`history`; T unknown → send the prompt again (safe: the device deduplicates).
`history`; T unknown → send the prompt again (safe: the device deduplicates) — unless the row is a
turn the harness started, which is never sent: import what `history` has for T
(`conformance/reattach.json`). `busy` is true, and `turnId` names the turn, for **every** turn that
runs — a harness turn included, with capability `harness_turns`.
### `_lembas/jobs` — client → agent → result (capability `jobs`)
+77
View File
@@ -0,0 +1,77 @@
{
"about": "Spec 3.10.0 (acp.md, `session/cancel`): which turn a cancel touches. `turn`: the `_meta.lembas.turnId` the cancel carries, absent for ACP's own cancel; `running`: the id of the turn that runs in the session now, absent when none does; `queued`: the ids of the prompts waiting their turn. The result `cancelled` is what the device answers a cancel sent as a request: `running` — the running turn is stopped; `queued` — that prompt is taken out of the queue and answered `cancelled`, and the running turn is not touched; `none` — nothing is done. `stops`: the id of the turn stopped, `withdraws`: the id taken out of the queue (each absent when none). LLeMbas: what it may expect of a device with `harness_turns`; CLI: acp/turns.ts `cancelOf`.",
"cases": [
{
"about": "No id, a turn runs: ACP's cancel — the running turn, whoever started it.",
"running": "h2",
"queued": [
"t8"
],
"expect": {
"cancelled": "running",
"stops": "h2"
}
},
{
"about": "No id, nothing runs: nothing to stop.",
"queued": [],
"expect": {
"cancelled": "none"
}
},
{
"about": "The turn named is the one that runs: stopped.",
"turn": "t7",
"running": "t7",
"queued": [],
"expect": {
"cancelled": "running",
"stops": "t7"
}
},
{
"about": "The turn named waits behind a harness turn: taken out of the queue; the harness turn is not touched.",
"turn": "t8",
"running": "h2",
"queued": [
"t8"
],
"expect": {
"cancelled": "queued",
"withdraws": "t8"
}
},
{
"about": "Two prompts wait; the second is named: only it goes.",
"turn": "t9",
"running": "h2",
"queued": [
"t8",
"t9"
],
"expect": {
"cancelled": "queued",
"withdraws": "t9"
}
},
{
"about": "The turn named finished already, while another runs: nothing is done — the running turn is somebody else's.",
"turn": "t6",
"running": "h2",
"queued": [
"t8"
],
"expect": {
"cancelled": "none"
}
},
{
"about": "An id the session never heard of, nothing running: nothing is done.",
"turn": "x1",
"queued": [],
"expect": {
"cancelled": "none"
}
}
]
}
+224
View File
@@ -0,0 +1,224 @@
{
"about": "Spec 3.10.0 (acp.md, *A session that still has work out* and *The run waits for its subagents*): what a session still has out when no turn of it runs. `agents`: the team as its tree has it — the main agent (`lead`: `working`, `waiting` or `idle`) and every live subagent with its state (subagents.md §9); an ended subagent is not in it. `jobs`: the session's background jobs that are not a team's subagents (a team's subagent counts once, by its state), each `kind` (`command` or `subagent`, a background `task`) and `state` as in JobInfo. The result: `subagents` — who still works for the session and will report: the team's subagents that are `working`, `waiting` or `paused`, by name in tree order, then the running background `task` subagents by job id; `commands` — the running background commands by job id; `run_waits` — a schedule's run does not end yet: a subagent is out, or the main agent is `waiting` (a report waits for it to get a slot) — never for a command, which may not end; `has_work` — the session is not idle for the device (the link is not closed for a change of limits, a service does not start again for an update, a terminal opening the session is refused): `run_waits`, or a command runs. LLeMbas: where its own scheduled runs with a team end; CLI: src/session/outstanding.ts.",
"cases": [
{
"about": "Nothing out: a team whose subagents have all reported, and no jobs.",
"agents": [
{
"name": "lead",
"state": "idle"
},
{
"name": "api",
"state": "finished"
}
],
"jobs": [],
"expect": {
"subagents": [],
"commands": [],
"run_waits": false,
"has_work": false
}
},
{
"about": "A subagent works after the main agent's reply ended.",
"agents": [
{
"name": "lead",
"state": "idle"
},
{
"name": "api",
"state": "working"
}
],
"jobs": [],
"expect": {
"subagents": [
"api"
],
"commands": [],
"run_waits": true,
"has_work": true
}
},
{
"about": "One waits for a slot, one is in its last turn after its context filled, one has finished: the first two are out, in tree order.",
"agents": [
{
"name": "lead",
"state": "idle"
},
{
"name": "web",
"state": "finished"
},
{
"name": "api",
"state": "paused"
},
{
"name": "docs",
"state": "waiting"
}
],
"jobs": [],
"expect": {
"subagents": [
"api",
"docs"
],
"commands": [],
"run_waits": true,
"has_work": true
}
},
{
"about": "Every subagent has finished, and the last report waits for the main agent to get a slot: the run is not over.",
"agents": [
{
"name": "lead",
"state": "waiting"
},
{
"name": "api",
"state": "finished"
}
],
"jobs": [],
"expect": {
"subagents": [],
"commands": [],
"run_waits": true,
"has_work": true
}
},
{
"about": "A background task subagent still runs: out, named by its job.",
"agents": [
{
"name": "lead",
"state": "idle"
}
],
"jobs": [
{
"id": "job2",
"kind": "subagent",
"state": "running"
},
{
"id": "job1",
"kind": "subagent",
"state": "done"
}
],
"expect": {
"subagents": [
"job2"
],
"commands": [],
"run_waits": true,
"has_work": true
}
},
{
"about": "A background command runs: the session has work out, but a run does not wait for it — it may never end.",
"agents": [
{
"name": "lead",
"state": "idle"
}
],
"jobs": [
{
"id": "job1",
"kind": "command",
"state": "running"
}
],
"expect": {
"subagents": [],
"commands": [
"job1"
],
"run_waits": false,
"has_work": true
}
},
{
"about": "Finished, stopped and lost jobs are not out.",
"agents": [
{
"name": "lead",
"state": "idle"
}
],
"jobs": [
{
"id": "job1",
"kind": "command",
"state": "done"
},
{
"id": "job2",
"kind": "command",
"state": "stopped"
},
{
"id": "job3",
"kind": "subagent",
"state": "lost"
},
{
"id": "job4",
"kind": "command",
"state": "error"
}
],
"expect": {
"subagents": [],
"commands": [],
"run_waits": false,
"has_work": false
}
},
{
"about": "Both kinds: subagents first by name, then the task subagent by job; the command beside them.",
"agents": [
{
"name": "lead",
"state": "working"
},
{
"name": "api",
"state": "working"
}
],
"jobs": [
{
"id": "job3",
"kind": "command",
"state": "running"
},
{
"id": "job4",
"kind": "subagent",
"state": "running"
}
],
"expect": {
"subagents": [
"api",
"job4"
],
"commands": [
"job3"
],
"run_waits": true,
"has_work": true
}
}
]
}
+124
View File
@@ -0,0 +1,124 @@
{
"about": "Spec 3.10.0 (acp.md, `_lembas/session/status` and *A turn the harness starts*): the client's rule for an incomplete row after a restart or a dropped link. `turn`: the row's turn id T; `machine`: the row is a turn the harness started (its `prompt` event said `machine`); `status`: what `_lembas/session/status` answered — `busy`, `turnId` (the turn running now), `queued`, `lastTurnId`. The result `do`: `follow` — T runs: take its events until its `task` end; `wait` — T is queued: follow it when it starts; `import` — read the reply after the user turn with T from `_lembas/session/history` (for a harness turn the device does not know any more: whatever is there, and nothing when nothing is); `resend` — send the prompt again with T. A harness turn is never resent: its text is a note, not a person's words. LLeMbas: services/device_link.py; CLI: acp/turns.ts reattach (the client's rule, kept there for these cases).",
"cases": [
{
"about": "The person's turn still runs: followed.",
"turn": "t7",
"status": {
"busy": true,
"turnId": "t7",
"queued": [],
"lastTurnId": "t6"
},
"expect": {
"do": "follow"
}
},
{
"about": "A harness turn still runs — status names it as it names any turn: followed.",
"turn": "h2",
"machine": true,
"status": {
"busy": true,
"turnId": "h2",
"queued": [],
"lastTurnId": "t7"
},
"expect": {
"do": "follow"
}
},
{
"about": "The person's prompt waits behind a harness turn: waited for, then followed.",
"turn": "t8",
"status": {
"busy": true,
"turnId": "h2",
"queued": [
"t8"
],
"lastTurnId": "t7"
},
"expect": {
"do": "wait"
}
},
{
"about": "The person's turn was the last to finish: imported from the history.",
"turn": "t7",
"status": {
"busy": false,
"queued": [],
"lastTurnId": "t7"
},
"expect": {
"do": "import"
}
},
{
"about": "A harness turn was the last to finish: imported by its id.",
"turn": "h2",
"machine": true,
"status": {
"busy": false,
"queued": [],
"lastTurnId": "h2"
},
"expect": {
"do": "import"
}
},
{
"about": "The device does not know the person's turn: the prompt is sent again, and the device runs it once.",
"turn": "t9",
"status": {
"busy": false,
"queued": [],
"lastTurnId": "t7"
},
"expect": {
"do": "resend"
}
},
{
"about": "The same while a harness turn runs: sent again, and it waits its turn there.",
"turn": "t9",
"status": {
"busy": true,
"turnId": "h3",
"queued": [],
"lastTurnId": "t7"
},
"expect": {
"do": "resend"
}
},
{
"about": "A harness turn the device no longer knows (it restarted in the middle of it): never sent — what the history has for it is all there is.",
"turn": "h2",
"machine": true,
"status": {
"busy": false,
"queued": [],
"lastTurnId": "t7"
},
"expect": {
"do": "import"
}
},
{
"about": "The first of two harness turns in a row, while the second runs and a person's turn finished in between: imported, not sent, and not taken for the one that runs.",
"turn": "h2",
"machine": true,
"status": {
"busy": true,
"turnId": "h3",
"queued": [],
"lastTurnId": "t8"
},
"expect": {
"do": "import"
}
}
]
}
+1
View File
@@ -12,3 +12,4 @@ You are the main agent of this session. You can add subagents with team_add: age
- A subagent whose context fills saves its findings and ends. Read them with team_findings, then replace it (team_replace) if its part is not done.
- Step in when a subagent is stuck, when two disagree, or when the plan has to change: decide, and tell those it concerns (team_assign for new work).
- Review every report against what you asked for — read the work itself where it matters — and send back what is not done. Then give your own answer to the person.
- You do not wait for a report or ask for one. End your turn when you have nothing left to do but wait; each report arrives by itself, as a message marked as a team report, and starts your next turn. When the reports you need are in, answer the person in that turn, unasked — never tell the person to ask again for the result.
+7
View File
@@ -40,6 +40,13 @@ not in the list at all.
A subagent of a run is never offered it: the run's own agent files the report.
**The run is the schedule's turn, whole** (spec 3.10.0). On a linked computer that turn stays
open while the run's subagents work and takes their reports in (`acp.md`, *The run waits for its
subagents*), so the tool is offered until the run answers — after the last report. A turn the
session starts by itself *after* that answer — a background command the run left ended — is the
schedule's work (`interactive.md` §2) but not its run: the tool answers `unavailable` there,
because no answer is left to carry a report.
## 3. Notify when
A schedule says when its owner wants to hear from it (`scheduled.notify.values`):
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "lembas-cli",
"version": "2.0.0-beta.12",
"version": "2.0.0-beta.13",
"description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.",
"license": "MIT",
"private": true,
+154 -38
View File
@@ -33,7 +33,7 @@ import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts"
import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts"
import { pickShell, shellLaunch } from "./shellrc.ts"
import { callTitle } from "../session/display.ts"
import { sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts"
import { cancelOf, sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts"
import { expandHome } from "../config/paths.ts"
import { asMode, MODES, type Mode } from "../config/schema.ts"
import { isLevel, readLevel, type Level } from "../provider/effort.ts"
@@ -47,6 +47,7 @@ import type { Hub } from "./hub.ts"
import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import { isNote } from "../session/prefix.ts"
import { outstandingReason } from "../session/outstanding.ts"
import { deniedText, finalReply, judgeMonitor, monitorTimeout, notifyOf, permissionFor, refusalText, runMonitor, runOutcome, SCHEDULED, scheduledMode, type Report, type ScheduledTurn } from "./scheduled.ts"
export const ACP_VERSION = 1
@@ -182,8 +183,14 @@ export interface Session {
off?: () => void
/** Prompts that came while it worked: they wait their turn instead of being refused. */
queue?: Promise<unknown>
/** The turn the harness started by itself and runs now (a note waking the session, acp.md *A turn
* the harness starts*): no prompt of the client's began it, and `end` lets the queue move on. */
own?: { turnId: string; end: () => void }
/** Its turns by id: a prompt sent twice runs once. */
turns: TurnLog<PromptResult>
/** The prompts waiting their turn, by id: what takes one out of the queue (`session/cancel`
* with its turnId) — it is answered as cancelled then, and never runs. */
waiting?: Map<string, () => void>
/** The command set last sent to the client, to send it again only when it changed. */
commands?: string
/** Spec 3.8.0: the report the run under way has written (the last one), for its answer. */
@@ -195,6 +202,50 @@ export interface Session {
scheduled?: ScheduledTurn
}
/** Whether a turn runs in the session now, whoever started it: a prompt of the client's, or the
* harness's own (a note waking it). What status, steer, compact, rewind and letting go ask. */
export const working = (s: Session): boolean => s.prompting || s.own !== undefined
/** Whether the session is anything but idle: a turn runs or waits its turn — or none does, and
* work of it is still out: a subagent that works or waits, a report about to wake it, a
* background command (session/outstanding.ts; acp.md, *A session that still has work out*). What
* the service asks before it starts again for an update, closes the link for a change of limits,
* or lets a terminal have the session: each of those would lose that work. */
export const occupied = (s: Session): boolean => working(s) || s.queue !== undefined || s.app.out().has_work
/** Why a terminal may not have this session now, in words — or undefined when it may. */
export function keeps(s: Session): string | undefined {
if (working(s) || s.queue !== undefined) return "this session is working on a prompt from the web UI — wait for it to finish, then open it"
return outstandingReason(s.app.out())
}
/** A `task` event of a turn no prompt of the client's began — the harness's own. It is kept in the
* session's turn log as a terminal's turns are (running, then the last one finished, with no
* answer of this side's), and it holds the queue: a prompt that arrives meanwhile runs after it,
* never beside it. True for such a turn's events. */
function ownTurn(s: Session, e: Event): boolean {
if (e.type !== "task" || !e.turnId) return false
if (e.state === "start") {
// While a prompt of the client's runs, every turn is that prompt's.
if (s.prompting) return false
let end!: () => void
const over = new Promise<void>((r) => (end = r))
s.own = { turnId: e.turnId, end }
s.turns.started(e.turnId)
const tail = (s.queue ?? Promise.resolve()).then(() => over)
s.queue = tail
void tail.then(() => {
if (s.queue === tail) s.queue = undefined
})
return true
}
if (s.own?.turnId !== e.turnId) return false
s.turns.ended(e.turnId)
s.own.end()
s.own = undefined
return true
}
/** What `session/prompt` answers. */
export type PromptResult = { stopReason: string; _meta?: { lembas: Record<string, unknown> } }
@@ -300,6 +351,10 @@ export const CAPABILITIES = [
// Harness spec 3.9.0: `model` on a Dir of `_lembas/directories` — the model last used in
// exactly that directory — and `list: false`, the directory alone.
"directory_model",
// Harness spec 3.10.0 (acp.md, *A turn the harness starts*): a turn a note starts by itself is a
// turn in `status`, takes a steer, makes a prompt wait, hands back `unsent` on its `task` end
// and is in `history` with `machine`.
"harness_turns",
] as const
export const STOP: Record<string, string> = { stop: "end_turn", steps: "max_turn_requests", budget: "max_tokens", cancelled: "cancelled", error: "end_turn" }
@@ -415,7 +470,7 @@ const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test
* not text. */
export function historyTurns(messages: Message[], cwd = "") {
type Tool = { id: string; name: string; args: string; output?: string; isError?: boolean }
type Turn = { role: "user"; text: string; turnId?: string; attachments?: ReturnType<typeof storedAttachments> } | { role: "assistant"; text: string; reasoning: string; tools: Tool[] }
type Turn = { role: "user"; text: string; turnId?: string; attachments?: ReturnType<typeof storedAttachments>; machine?: true } | { role: "assistant"; text: string; reasoning: string; tools: Tool[] }
const turns: Turn[] = []
let reply: Extract<Turn, { role: "assistant" }> | undefined
const calls = new Map<string, Tool>()
@@ -425,7 +480,8 @@ export function historyTurns(messages: Message[], cwd = "") {
const texts = m.parts.map((p) => (p.type === "text" ? p.text : ""))
const text = texts.filter((t) => !ATTACHMENT.test(t)).join("\n").trim()
const attachments = storedAttachments(texts, cwd)
if (text || attachments.length) turns.push({ role: "user", text, ...(m.turnId ? { turnId: m.turnId } : {}), ...(attachments.length ? { attachments } : {}) })
// A turn the harness started (a note, with its mark) is in the history as what it is.
if (text || attachments.length) turns.push({ role: "user", text, ...(m.turnId ? { turnId: m.turnId } : {}), ...(attachments.length ? { attachments } : {}), ...(m.machine ? { machine: true as const } : {}) })
continue
}
if (!reply) {
@@ -511,7 +567,10 @@ export class AcpAgent {
peer.on("_lembas/terminal/input", (p) => this.terminalInput(p))
peer.on("_lembas/terminal/resize", (p) => this.terminalResize(p))
peer.on("_lembas/terminal/close", (p) => this.terminalClose(String(p?.terminalId ?? "")))
peer.on("session/cancel", (p) => this.cancel(p))
// ACP's notification, answered with nothing — and the same as a request, answered with what
// was found (acp.md `session/cancel`).
peer.on("session/cancel", (p) => void this.cancel(p).catch(() => {}))
peer.handle("session/cancel", (p) => this.cancel(p))
// With the hub (the service), the sessions are its, not this link's: a link that drops
// and comes back -- the instance updated, the network blinked -- finds them still working, and
// the instance follows them again instead of losing the turn. Without it (`serve --stdio`), the
@@ -827,8 +886,9 @@ export class AcpAgent {
s.agent = this
this.equipShow(s)
s.off = s.app.bus.on((e) => {
const own = ownTurn(s, e)
if (s.agent !== this) return
this.forward(s, e)
this.forward(s, e, own)
// A turn can change the set (skill_manage made a skill, a command file was written).
if (e.type === "task" && e.state === "end") this.sendCommands(s)
})
@@ -972,25 +1032,6 @@ export class AcpAgent {
}
private store?: Store
/** Whether a session runs here, and whether it is working (the hub, before a terminal opens it). */
holding(id: string): "busy" | "idle" | undefined {
const s = this.sessions.get(id)
return s ? (s.prompting ? "busy" : "idle") : undefined
}
/** Whether any session this link runs is working, or has prompts waiting. */
anyBusy(): boolean {
return [...this.sessions.values()].some((s) => s.prompting || s.queue)
}
/** Let go of an idle session: a terminal carries it on from the store. */
drop(id: string) {
const s = this.sessions.get(id)
if (!s || s.prompting) return
this.sessions.delete(id)
void s.app.close()
}
notifyInstance(method: string, params: unknown) {
this.peer.notify(method, params)
}
@@ -1083,6 +1124,10 @@ export class AcpAgent {
// A turn id this session has taken already: not run again — the original's answer,
// now or when it is done.
if (s.turns.has(turnId)) return s.turns.run(turnId, () => Promise.reject(new Error("unreachable")))
// An id this session knows as a steered message's: the same message, sent again as a prompt by
// a client that could not tell what became of it. The model is not given it twice.
const steered = s.app.engine.steerState(turnId)
if (steered) return { stopReason: "end_turn", _meta: { lembas: { turnId, steered } } }
// Spec 3.5.0: a scheduled turn is judged again (the setting may have been turned off since the
// session was opened); a prompt without `scheduled` is the person's, in the run's agent chat.
const scheduled = this.judgeScheduled(p?._meta?.lembas?.scheduled)
@@ -1118,15 +1163,30 @@ export class AcpAgent {
s.app.setAutomated(false)
}
}
return s.turns.run(turnId, (started) => {
// Idle: it starts now, in this tick — a steer sent right after it must find the session working.
const next = s.queue ? s.queue.then(() => run(started), () => run(started)) : run(started)
/** The queue's tail is this turn until it is over. */
const chain = (next: Promise<PromptResult>): Promise<PromptResult> => {
const tail = next.catch(() => {})
s.queue = tail
void tail.then(() => {
if (s.queue === tail) s.queue = undefined
})
return next
}
return s.turns.run(turnId, (started) => {
// Idle: it starts now, in this tick — a steer sent right after it must find the session working.
if (!s.queue) return chain(run(started))
// It waits its turn — and may be taken back while it does (`session/cancel` with its id):
// answered as cancelled at once, and when its place in the queue comes nothing runs.
let withdrawn = false
let bail!: (r: PromptResult) => void
const gone = new Promise<PromptResult>((r) => (bail = r))
const cancelled: PromptResult = { stopReason: "cancelled", _meta: { lembas: { turnId, ...(scheduled ? { scheduled: runOutcome({ runId: scheduled.runId, reason: "cancelled", text: "" }) } : {}) } } }
const waiting = (s.waiting ??= new Map())
waiting.set(turnId, () => ((withdrawn = true), waiting.delete(turnId), bail(cancelled)))
const turn = () => (waiting.delete(turnId), withdrawn ? Promise.resolve(cancelled) : run(started))
const ran = chain(s.queue.then(turn, turn))
ran.catch(() => {})
return Promise.race([ran, gone])
})
}
@@ -1167,7 +1227,7 @@ export class AcpAgent {
const reason = await app.turns.prompt(prepared.prompt, prepared.extra, prepared.shown, { turnId, attachments: prepared.attachments })
// Messages sent mid-task (`_lembas/steer`) that the task ended before taking in: handed back,
// so the web UI sends them as the next turn rather than losing them.
const unsent = app.engine.takeInbox()
const unsent = this.leftover(s)
return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(unsent.length ? { unsent } : {}), ...(prepared.command ? { command: prepared.command } : {}) } } }
} finally {
// A command's model and mode hold for its prompt only — unless the turn itself changed the
@@ -1178,6 +1238,17 @@ export class AcpAgent {
}
}
/** What a prompt's turn ended before taking in (`_lembas/steer`). With a client there to read
* the answer it is handed back (`unsent`); with none — the link is down as the turn ends — it
* is kept with the session for the next turn's first step, as after a turn the harness
* started (engine.carry): an answer nobody reads would lose it. One or the other. */
private leftover(s: Session): string[] {
const agent = s.agent ?? this
if (!agent.peer.isClosed) return s.app.engine.takeInbox()
s.app.engine.carry()
return []
}
/** A scheduled request's settings as this device runs them (spec 3.5.0), or undefined when the
* request is not scheduled; a refusal is thrown as -32602 with `data.reason`. */
private judgeScheduled(meta: any): ScheduledTurn | undefined {
@@ -1215,12 +1286,16 @@ export class AcpAgent {
try {
if (prepared.model) app.switchModel(prepared.model, "borrowed")
const reason = await app.turns.prompt(prepared.prompt, prepared.extra, prepared.shown, { turnId, attachments: prepared.attachments })
const unsent = app.engine.takeInbox()
const unsent = this.leftover(s)
return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: meta(unsent.length ? { unsent } : {}, reason, finalReply(app.engine.messages), error) } }
} finally {
off()
if (prepared.model) app.returnModel(prev)
app.engine.mode = turn.mode
// Nothing of a run's subagents works after its answer: by a turn that ended as meant they
// have all reported (the turn waited for them); one that was stopped, failed or ran out of
// steps or budget takes them with it — nobody would read what they report.
if (app.out().run_waits) app.stopSubagents()
}
}
@@ -1259,7 +1334,8 @@ export class AcpAgent {
sessionId: id,
exists: true,
held: "here",
busy: s.prompting,
// Every turn that runs, whoever started it: a wake turn is named like any other.
busy: working(s),
title: (this.store ??= new Store()).session(id)?.title ?? "",
...(s.turns.running ? { turnId: s.turns.running } : {}),
queued: s.turns.queued(),
@@ -1346,7 +1422,7 @@ export class AcpAgent {
const t = this.terminalFor(p)
if (t) return t.client.request("hub/rewind", { sessionId: t.sessionId, turnId }, 15_000)
const s = this.get(p)
if (s.prompting || s.turns.queued().length) throw new RpcError(INVALID_PARAMS, "this session is working — rewind it when the reply is done")
if (working(s) || s.turns.queued().length) throw new RpcError(INVALID_PARAMS, "this session is working — rewind it when the reply is done")
const reverted = s.app.turns.rewind(turnId)
if (reverted === undefined) throw new RpcError(INVALID_PARAMS, `this session has no turn ${turnId}`)
s.turns.forget(reverted)
@@ -1385,7 +1461,7 @@ export class AcpAgent {
const t = this.terminalFor(p)
if (t) return t.client.request("hub/compact", { sessionId: t.sessionId }, 600_000)
const s = this.get(p)
if (s.prompting) throw new RpcError(INVALID_PARAMS, "this session is working — compact it when the reply is done")
if (working(s)) throw new RpcError(INVALID_PARAMS, "this session is working — compact it when the reply is done")
try {
return { summary: await s.app.engine.compact() }
} catch (e) {
@@ -1416,7 +1492,9 @@ export class AcpAgent {
const t = this.terminalFor(p)
if (t) return t.client.request("hub/steer", { sessionId: t.sessionId, text, messageId: id }, 15_000)
const s = this.get(p)
if (!s.prompting) throw new RpcError(INVALID_PARAMS, "this session is not working on anything; send it as a prompt")
// Any turn that runs takes it in, the harness's own included: a message typed while the model
// answers a subagent's report joins that turn.
if (!working(s)) throw new RpcError(INVALID_PARAMS, "this session is not working on anything; send it as a prompt")
s.app.engine.enqueue(text, id)
return { queued: s.app.engine.queued }
}
@@ -1505,21 +1583,59 @@ export class AcpAgent {
return {}
}
private cancel(p: any) {
/** `session/cancel`: stop the running turn — or, with `_meta.lembas.turnId`, that turn and no
* other: stopped when it runs, taken out of the queue when it waits (its prompt is answered as
* cancelled and never runs), nothing when it is neither. What was found is the answer. */
private async cancel(p: any): Promise<{ cancelled: "running" | "queued" | "none" }> {
const named = p?._meta?.lembas?.turnId
const turn = typeof named === "string" && named.trim() ? named.trim().slice(0, 100) : undefined
const t = this.terminalFor(p)
if (t) return t.client.notify("hub/cancel", { sessionId: t.sessionId })
this.sessions.get(String(p?.sessionId ?? ""))?.app.cancel()
if (t) {
// The terminal knows its turns. One named is asked of it; a terminal of a build that has no
// such request is not told to stop whatever runs there.
if (turn !== undefined) return t.client.request<{ cancelled: "running" | "queued" | "none" }>("hub/cancel", { sessionId: t.sessionId, turnId: turn }, 15_000).catch(() => ({ cancelled: "none" as const }))
t.client.notify("hub/cancel", { sessionId: t.sessionId })
return { cancelled: t.busy ? "running" : "none" }
}
const s = this.sessions.get(String(p?.sessionId ?? ""))
if (!s) return { cancelled: "none" }
// ACP's own cancel: whatever runs, as ever.
if (turn === undefined) {
const ran = working(s)
s.app.cancel()
return { cancelled: ran ? "running" : "none" }
}
const found = cancelOf({ turn, ...(s.turns.running ? { running: s.turns.running } : {}), queued: s.turns.queued() })
if (found.withdraws !== undefined) {
const take = s.waiting?.get(found.withdraws)
if (!take) return { cancelled: "none" }
take()
} else if (found.stops !== undefined) s.app.cancel()
return { cancelled: found.cancelled }
}
private update(s: Session, update: Record<string, unknown>) {
this.peer.notify("session/update", { sessionId: s.id, update })
}
private forward(s: Session, e: Event) {
private forward(s: Session, e: Event, own = false) {
// A model change says whether the model is this link's instance's: its ref is the
// provider's now (`deepseek/x`), so the ref alone no longer tells.
const event = e.type === "model" ? { ...e, instance: this.isInstance(e.connection) } : e.type === "team" ? { ...e, tree: treeOf(s.app) } : e
let event: Event | Record<string, unknown> = e.type === "model" ? { ...e, instance: this.isInstance(e.connection) } : e.type === "team" ? { ...e, tree: treeOf(s.app) } : e
// The end of a turn the harness started has no prompt's answer to carry what was steered into
// it too late. To a client that hears events it goes back on the event (`unsent`, as in a
// prompt's answer) — said before the queue is said to be empty, so an emptied queue is never
// read as messages taken in. With nobody listening it is kept with the session and goes in at
// the next turn's first step (engine.carry): one or the other, never both.
let handedBack = false
if (own && e.type === "task" && e.state === "end") {
if (this.lembas && !this.peer.isClosed) {
const unsent = s.app.engine.unsent
if (unsent.length) (event = { ...e, unsent }), (handedBack = true)
} else s.app.engine.carry()
}
if (this.lembas) this.peer.notify("_lembas/event", { sessionId: s.id, event })
if (handedBack) s.app.engine.takeInbox()
switch (e.type) {
case "text":
return this.update(s, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: e.text } })
+15 -6
View File
@@ -23,7 +23,7 @@ import { join } from "node:path"
import { isLocal, paths } from "../config/paths.ts"
import type { Mode } from "../config/schema.ts"
import type { CommandInfo } from "../session/commands.ts"
import { clampMode, refusalFor, type AcpAgent, type Limits } from "./agent.ts"
import { clampMode, keeps, occupied, refusalFor, type AcpAgent, type Limits } from "./agent.ts"
import { addPendingDeleted } from "./pending.ts"
import { INVALID_PARAMS, Peer, RpcError, type Transport } from "./rpc.ts"
@@ -178,9 +178,12 @@ export class Hub {
if (this.agent === agent) this.agent = undefined
}
/** Whether anything works here now: a session the link runs, or one a terminal shares mid-turn. */
/** Whether anything works here now: a session the link runs — a turn of it, or with none
* running its subagents and background jobs, which live in this process — or one a terminal
* shares mid-turn. While it is true the service does not start again for an update and the
* link is not closed for a change of limits. */
busy(): boolean {
return [...this.held.values()].some((s) => s.prompting || s.queue) || [...this.shared.values()].some((s) => s.busy)
return [...this.held.values()].some(occupied) || [...this.shared.values()].some((s) => s.busy)
}
private announce(s: Shared) {
@@ -202,9 +205,15 @@ export class Hub {
private releaseFor(peer: Peer, id: string): void {
const other = this.shared.get(id)
if (other && other.client !== peer && !other.client.isClosed) throw new RpcError(INVALID_PARAMS, `this session is open in another terminal (pid ${other.pid})`)
const held = this.agent?.holding(id)
if (held === "busy") throw new RpcError(INVALID_PARAMS, "this session is working on a prompt from the web UI — wait for it to finish, then open it")
if (held) this.agent!.drop(id)
// The hub's own copy — whether a link is up or not: it is let go of only when nothing of it
// works here. A terminal cannot take over a turn, a subagent or a background job that runs in
// this process, and closing the copy would stop them; so it is refused, in words.
const held = this.held.get(id)
if (!held) return
const why = keeps(held)
if (why) throw new RpcError(INVALID_PARAMS, why)
this.held.delete(id)
void held.app.close()
}
private accept(peer: Peer) {
+38 -3
View File
@@ -18,7 +18,7 @@ import { readLevel } from "../provider/effort.ts"
import { clampMode, effortOf, markRemote, permissionParams, planParams, planReplyFrom, questionParams, questionReplyFrom, replyFrom, STOP, type PromptResult } from "./agent.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import type { SessionContext } from "../app.ts"
import { sessionTurnFile, sessionTurns, type TurnLog } from "./turns.ts"
import { cancelOf, sessionTurnFile, sessionTurns, type TurnLog } from "./turns.ts"
import { dropAttachments, preparePrompt } from "./prompt.ts"
import { connectHub, Hub } from "./hub.ts"
import { isLocal } from "../config/paths.ts"
@@ -459,6 +459,9 @@ export class Share {
}
}
/** The web UI's prompts that have not started here yet, by turn id: what takes one back. */
private waiting = new Map<string, () => void>()
private mine(p: any) {
if (!this.sharedId || p?.sessionId !== this.sharedId) throw new RpcError(INVALID_PARAMS, "that session is not open in this terminal any more")
}
@@ -470,6 +473,9 @@ export class Share {
const turnId = typeof p?.turnId === "string" && p.turnId ? p.turnId : crypto.randomUUID()
// A turn id taken already: the original's answer.
if (this.turns.has(turnId)) return this.turns.run(turnId, () => Promise.reject(new Error("unreachable")))
// A steered message's id, sent again as a prompt: not given to the model twice.
const steered = this.app.engine.steerState(turnId)
if (steered) return { stopReason: "end_turn", _meta: { lembas: { turnId, steered } } }
// What the client holds for the session (its instructions, personalization, library scope),
// passed on by the hub: read into the prompt here as the service would.
if (p?.context && typeof p.context === "object") this.app.setContext(p.context as SessionContext, typeof p?.instance === "string" ? p.instance : undefined)
@@ -496,8 +502,28 @@ export class Share {
// A command's mode from the web never goes past remote.max_mode in a session shared under
// the device's limits (not by name), as in a session the service runs.
if (input.mode && !this.explicit) input.mode = clampMode(input.mode, limits.maxMode)
const reason = await this.hooks.prompt({ ...input, turnId }, started)
return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(command ? { command } : {}) } } }
// Until it starts it may be taken back (`session/cancel` with its id): answered as
// cancelled now, and when the terminal comes to it nothing is sent.
let withdrawn = false
let bail!: (r: PromptResult) => void
const gone = new Promise<PromptResult>((r) => (bail = r))
this.waiting.set(turnId, () => ((withdrawn = true), this.waiting.delete(turnId), bail({ stopReason: "cancelled", _meta: { lembas: { turnId } } })))
const begin = () => {
this.waiting.delete(turnId)
if (withdrawn) throw new Error("withdrawn")
started()
}
// A hook may call `begin` before it returns its promise: its throw is the promise's.
let asked: Promise<string>
try {
asked = this.hooks.prompt({ ...input, turnId }, begin)
} catch (e) {
asked = Promise.reject(e)
}
const ran = asked
.then((reason): PromptResult => ({ stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(command ? { command } : {}) } } }))
ran.catch(() => {})
return Promise.race([ran, gone]).finally(() => this.waiting.delete(turnId))
})
})
// The terminal's turns: `_lembas/session/status` for a shared session asks here.
@@ -591,6 +617,15 @@ export class Share {
peer.on("hub/cancel", (p) => {
if (this.sharedId && p?.sessionId === this.sharedId) this.app.cancel()
})
// The same with the turn named (acp.md `session/cancel`): that turn and no other.
peer.handle("hub/cancel", (p) => {
this.mine(p)
const running = this.app.turns.current?.turnId
const found = cancelOf({ turn: String(p?.turnId ?? ""), ...(running ? { running } : {}), queued: [...this.waiting.keys()] })
if (found.withdraws !== undefined) this.waiting.get(found.withdraws)?.()
else if (found.stops !== undefined) this.app.cancel()
return { cancelled: found.cancelled }
})
peer.handle("hub/mode", (p) => {
this.mine(p)
const mode = asMode(p?.mode)
+22
View File
@@ -116,6 +116,28 @@ export function sessionTurns<R>(sessionId: string): TurnLog<R> {
return new TurnLog<R>(sessionTurnFile<R>(sessionId))
}
/** The client's rule (LLeMbas applies it; kept here so both suites answer the same cases,
* conformance/reattach.json): what to do with an incomplete row of turn `turn` after a restart or
* a dropped link, from what `_lembas/session/status` says. A turn the harness started (`machine`)
* is never sent to the device: what its history has for it is all there is. */
export function reattach(o: { turn: string; machine?: boolean; status: { turnId?: string; queued?: readonly string[]; lastTurnId?: string } }): { do: "follow" | "wait" | "import" | "resend" } {
if (o.status.turnId === o.turn) return { do: "follow" }
if (o.status.queued?.includes(o.turn)) return { do: "wait" }
if (o.status.lastTurnId === o.turn || o.machine) return { do: "import" }
return { do: "resend" }
}
/** Which turn a `session/cancel` touches (harness/acp.md; conformance/cancel.json). `turn`: the id
* it names (`_meta.lembas.turnId`), absent for ACP's own cancel, which means the running turn.
* A turn that is named and waits is taken out of the queue and the running one left alone; one
* that is neither running nor waiting is nobody's to stop. */
export function cancelOf(o: { turn?: string; running?: string; queued?: readonly string[] }): { cancelled: "running" | "queued" | "none"; stops?: string; withdraws?: string } {
if (o.turn === undefined) return o.running !== undefined ? { cancelled: "running", stops: o.running } : { cancelled: "none" }
if (o.running === o.turn) return { cancelled: "running", stops: o.turn }
if (o.queued?.includes(o.turn)) return { cancelled: "queued", withdraws: o.turn }
return { cancelled: "none" }
}
export class TurnLog<R = unknown> {
private entries = new Map<string, Entry<R>>()
private values = new Map<string, R | null>()
+38 -2
View File
@@ -29,6 +29,7 @@ import type { SubagentResult } from "./tool/task.ts"
import type { Client, ResolvedModel } from "./provider/types.ts"
import { modelTitle, firstReply, promptTitle } from "./session/title.ts"
import { Turns } from "./session/turns.ts"
import { outstanding, type Outstanding } from "./session/outstanding.ts"
import { Snapshots } from "./git/snapshot.ts"
import { CWD_META, REMOTE_META, SCHEDULED_META, SCHEDULED_MODEL_META, Store } from "./session/store.ts"
import { BUILTIN_TOOLS } from "./tool/registry.ts"
@@ -174,6 +175,12 @@ export interface App {
jobsSessionId(): string
/** The open session's jobs, running first. */
jobs(): Job[]
/** What the session still has out when no turn of it runs (session/outstanding.ts): subagents
* that work or wait, a report waiting for the main agent, background commands. */
out(): Outstanding
/** Stop every subagent of the session — a team's members, background `task` subagents — without
* a note: a schedule's run that ended leaves none working (acp.md, *Scheduled work*). */
stopSubagents(): void
/** A note for the open session (a job's end, a subagent's message), beginning with its mark: to
* the model's next step while a turn runs, else a turn of its own marked `machine`. `shown`:
* the line a transcript shows for it. */
@@ -501,7 +508,14 @@ export function createApp(o: AppOptions): App {
if (turns.current || engine.busy) return engine.note(text)
// A turn a schedule's job wakes is the schedule's: not run on an interactive-only model.
const no = kind === "scheduled" ? notAutomated(engine.model) : undefined
if (no) return void bus.emit({ type: "notice", level: "warn", message: `a job's note did not start a turn: ${no}` })
if (no) {
// No turn — so the note waits for the person's next message, kept with the session, and the
// main agent is idle again: a team that woke it gave it a slot for a turn that will not run
// (it would hold the slot, and every later report would be handed to that turn).
engine.keepNote(text)
teamRt.leadDone()
return void bus.emit({ type: "notice", level: "warn", message: `a job's note did not start a turn: ${no} It goes in with your next message.` })
}
void turns.prompt(text, [], shown, { machine: true }).catch((e) => bus.emit({ type: "notice", level: "warn", message: `a job's note could not start a turn: ${(e as Error).message}` }))
}
const detach = registry.attach({ sessionId: jobsSessionId, bus, wake, store, runningMax: () => loaded.config.limits?.jobs ?? registry.limits.runningMax })
@@ -512,7 +526,7 @@ export function createApp(o: AppOptions): App {
if (e.type !== "done") return
const left = engine.takeNotes()
if (!left.length) return
if (e.reason === "cancelled") return void engine.pendingContext.push(...left)
if (e.reason === "cancelled") return void left.forEach((n) => engine.keepNote(n))
setTimeout(() => {
for (const n of left) wake(n, shownLine(n))
}, 0)
@@ -766,6 +780,9 @@ export function createApp(o: AppOptions): App {
forget: () => teamRt.team.forgetTold(),
beforeTurn: (signal) => teamRt.beforeLeadTurn(signal),
},
// A schedule's run is not over while its subagents work (acp.md, *Scheduled work*): the run's
// turn waits for their reports. Any other turn ends, and a report wakes the session.
hold: { out: () => (automated && kind === "scheduled" && out().run_waits ? Math.max(1, out().subagents.length) : 0), rest: () => teamRt.leadDone() },
changing: () => changing(),
modeText: modeNote,
// The configured MCP servers, up to loop.json's wait: their tools in the first list.
@@ -835,6 +852,14 @@ export function createApp(o: AppOptions): App {
})
// The lead's turn ended: it is idle, and its slot frees (team.md §8).
bus.on((e) => e.type === "done" && teamRt.leadDone())
/** What the session still has out (session/outstanding.ts): its subagents, its background jobs. */
const out = (): Outstanding =>
outstanding({
agents: teamRt.team.tree().map((a) => ({ name: a.name, state: a.state })),
jobs: registry.running(jobsSessionId()).filter((j) => !j.team).map((j) => ({ id: j.id, kind: j.kind, state: j.state })),
})
// A turn that waits for its subagents looks again when one of them changes or ends.
bus.on((e) => (e.type === "team" || e.type === "job") && engine.poke())
// Spec 3.4.0: the main agent's mode reaches down the tree; its progress and context are in it.
bus.on((e) => {
if (e.type === "mode") teamRt.mainMode(e.mode)
@@ -1150,6 +1175,17 @@ export function createApp(o: AppOptions): App {
registry,
jobsSessionId,
jobs: () => registry.list(jobsSessionId()),
out,
stopSubagents() {
// The team's members leave it, with no note about it (stopAll); a background `task`
// subagent ends without one too — nobody is left to read either.
teamRt.stopAll()
for (const j of registry.running(jobsSessionId())) {
if (j.kind !== "subagent") continue
j.quiet = true
registry.stop(j)
}
},
wake,
team: teamRt,
get context() {
+3 -1
View File
@@ -496,6 +496,7 @@ export class JobRegistry {
job.ended = undefined
job.exit = undefined
job.lastError = undefined
job.quiet = undefined
this.persist(job)
this.emit(job, "start")
}
@@ -526,7 +527,8 @@ export class JobRegistry {
this.persist(job)
this.forget(job.sessionId)
this.emit(job, "end")
if (!job.silent) this.deliver(job, text)
// `quiet`: stopped with nobody left to read its note (a schedule's run that ended).
if (!job.silent && !job.quiet) this.deliver(job, text)
return { text, stopped }
}
+158 -6
View File
@@ -103,6 +103,11 @@ export interface EngineOptions {
/** Spec 3.4.0, a subagent: it ended by its own call (team_finish): the turn stops after this step. */
ended?(): boolean
}
/** A turn with nobody at it — a schedule's run (acp.md, *Scheduled work*) — does not end while
* subagents it started still work: their reports come into the same turn. `out`: how many are
* still out, 0 when the turn may end (and always 0 for any other turn); `rest`: the agent gives
* up its model slot while it waits. `poke()` says that the answer may have changed. */
hold?: { out(): number; rest?(): void }
}
/** What a prompt carries besides its text. */
@@ -152,6 +157,15 @@ const wrapUpText = (limit: string) => fillPrompt(LOOP.wrap_up.message, { limit }
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"
/** What was meant for the model and has not reached it, kept with the session so that a restart
* does not lose it: `notes` — the harness's notes that started no turn (the turn was stopped, or
* might not start), which go in with the next message; `steers` — messages steered into a turn
* the harness started that ended before taking them in, with nobody listening to hand them back
* to, which go in at the next turn's first step. */
export const CARRIED_META = "carried"
type Carried = { notes: string[]; steers: { text: string; id?: string }[]; taken?: string[] }
/** How many ids of steered messages the model has been given are remembered, newest last. */
export const STEERS_KEPT = 200
export class Engine {
messages: Message[] = []
@@ -181,6 +195,10 @@ export class Engine {
private notes: string[] = []
/** Those given to the model in this turn: kept word for word through a compaction, like the prompt. */
private turnSteers: string[] = []
/** Kept with the session (CARRIED_META) until the model has them. */
private carried: Carried = { notes: [], steers: [] }
/** The turn waits for its subagents' reports (EngineOptions.hold): what ends the wait. */
private poked: (() => void) | undefined
/** busy_input: steer — the inbox goes in at the next step; queue — it waits for the task to end. */
busyInput: "steer" | "queue" = "steer"
/** The session's plan (plan_write / plan_update), kept with the session and put into the
@@ -248,6 +266,65 @@ export class Engine {
this.plan = this.storedPlan()
this.results = this.resultsFor(o.sessionId)
this.kept = this.storedPrefix()
this.carried = this.storedCarried()
}
/** What the store holds for this session that the model has not been given yet. */
private storedCarried(): Carried {
const none: Carried = { notes: [], steers: [], taken: [] }
if (!this.o.store || !this.sessionId) return none
try {
const c = this.o.store.meta<Partial<Carried> | null>(this.sessionId, CARRIED_META)
if (!c || typeof c !== "object") return none
return {
taken: Array.isArray(c.taken) ? c.taken.filter((n): n is string => typeof n === "string").slice(-STEERS_KEPT) : [],
notes: Array.isArray(c.notes) ? c.notes.filter((n): n is string => typeof n === "string") : [],
steers: Array.isArray(c.steers) ? c.steers.filter((x) => x && typeof x.text === "string").map((x) => ({ text: x.text, ...(typeof x.id === "string" ? { id: x.id } : {}) })) : [],
}
} catch {
return none
}
}
private saveCarried() {
if (!this.o.store || !this.sessionId) return
try {
this.o.store.setMeta(this.sessionId, CARRIED_META, this.carried.notes.length || this.carried.steers.length || this.carried.taken?.length ? this.carried : null)
} catch {}
}
/** A note of the harness's that starts no turn — the turn it was for was stopped, or may not
* start: kept with the session, and given to the model with the next message. */
keepNote(text: string) {
this.carried.notes.push(text)
this.saveCarried()
}
/** What became of a steered message, by the id its sender gave it: `taken` — the model has been
* given it, in some turn of this session (the last STEERS_KEPT ids are remembered, with the
* session); `carried` — kept for the next turn's first step; `waiting` — in the running turn's
* queue, to be taken in or handed back. Undefined: not known here, or handed back as unsent.
* A prompt carrying such an id is that same message and must not give it to the model twice. */
steerState(id: string): "taken" | "carried" | "waiting" | undefined {
if (!id) return undefined
if (this.carried.taken?.includes(id)) return "taken"
if (this.carried.steers.some((x) => x.id === id)) return "carried"
if (this.inboxIds.includes(id)) return "waiting"
return undefined
}
/** Messages steered into this turn that it ended before taking in, with nobody to hand them
* back to: kept with the session, and given to the model at the next turn's first step — in
* every `busy_input` mode, since nobody will send them again. Emptied from the inbox, so they
* are never handed back as well. */
carry(): number {
const texts = this.inbox.splice(0)
const ids = this.inboxIds.splice(0)
if (!texts.length) return 0
this.carried.steers.push(...texts.map((text, i) => ({ text, ...(ids[i] ? { id: ids[i] } : {}) })))
this.saveCarried()
this.o.bus.emit({ type: "inbox", texts: [], mode: this.busyInput })
return texts.length
}
/** The prefix the store holds for this session, if any: a resumed session sends what it kept. */
@@ -534,6 +611,7 @@ export class Engine {
this.keptBase = undefined
this.lastRequest = undefined
this.kept = this.storedPrefix()
this.carried = this.storedCarried()
this.o.bus.emit({ type: "plan", plan: this.plan })
this.o.toolCtx.readFiles.clear()
this.o.toolCtx.fileStamps.clear()
@@ -724,6 +802,7 @@ export class Engine {
this.inbox.push(text)
this.inboxIds.push(id)
this.o.bus.emit({ type: "inbox", texts: [...this.inbox], mode: this.busyInput })
this.poke()
}
/** How many messages wait. */
@@ -731,6 +810,11 @@ export class Engine {
return this.inbox.length
}
/** The messages that wait, left where they are. */
get unsent(): string[] {
return [...this.inbox]
}
/** Take one waiting message out (↑ in the box, to look at or edit it); `putBack` returns it. */
unqueue(index: number): string | undefined {
if (index < 0 || index >= this.inbox.length) return undefined
@@ -759,6 +843,45 @@ export class Engine {
* carries its own mark. */
note(text: string) {
this.notes.push(text)
this.poke()
}
/** Something a waiting turn waits on may have changed (EngineOptions.hold): a note came, a
* subagent ended or was stopped. */
poke() {
const p = this.poked
this.poked = undefined
p?.()
}
/** Whether something waits to go to the model at the next step. */
private hasInput(): boolean {
return this.notes.length > 0 || this.carried.steers.length > 0 || (this.busyInput === "steer" && this.inbox.length > 0)
}
/** The reply is done and subagents of this turn are still out (EngineOptions.hold): wait for
* what they send. True: something came, and the turn goes on with it. False: nothing is out
* any more, or the turn was stopped (`signal`). */
private async awaitReports(signal: AbortSignal): Promise<boolean> {
const hold = this.o.hold
if (!hold || hold.out() === 0) return false
// Its slot goes to whoever waits for one: the reports are what it waits for.
hold.rest?.()
while (!signal.aborted && !this.hasInput() && hold.out() > 0) {
this.progress.set({ phase: "waiting_for_subagents", running: hold.out() })
await new Promise<void>((resolve) => {
const done = () => {
signal.removeEventListener("abort", done)
if (this.poked === done) this.poked = undefined
resolve()
}
this.poked = done
signal.addEventListener("abort", done, { once: true })
})
}
if (signal.aborted || !this.hasInput()) return false
// A slot again before it goes on (team.md §8) — it may wait for one, and be stopped waiting.
return this.o.team?.beforeTurn ? await this.o.team.beforeTurn(signal) : true
}
/** Notes the task ended before delivering. */
@@ -777,13 +900,20 @@ export class Engine {
const said = notes.map((n) => n.split("\n").find((l, i) => i > 0 && l.trim()) ?? n.split("\n")[0]!).join("; ")
this.o.bus.emit({ type: "notice", level: noteNeedsAttention(said) ? "warn" : "info", message: said })
}
if (this.busyInput !== "steer" || !this.inbox.length) return notes.length > 0
const texts = this.inbox.splice(0)
const ids = this.inboxIds.splice(0).filter((i): i is string => typeof i === "string")
// What an earlier turn left (carry) goes in whatever the mode; the inbox only when steering.
const late = this.carried.steers.splice(0)
const now = this.busyInput === "steer" ? this.inbox.splice(0) : []
const nowIds = this.busyInput === "steer" ? this.inboxIds.splice(0) : []
if (!late.length && !now.length) return notes.length > 0
const texts = [...late.map((x) => x.text), ...now]
const ids = [...late.map((x) => x.id), ...nowIds].filter((i): i is string => typeof i === "string")
// The model has these now: their ids are remembered with the session (steerState).
if (ids.length) this.carried.taken = [...(this.carried.taken ?? []), ...ids].slice(-STEERS_KEPT)
if (late.length || ids.length) this.saveCarried()
this.turnSteers.push(...texts)
this.push({ role: "user", parts: [{ type: "text", text: `${this.o.steerMark ?? STEER_MARK}\n${texts.join("\n\n")}` }], turn: false })
this.o.bus.emit({ type: "steered", texts, ...(ids.length ? { ids } : {}) })
this.o.bus.emit({ type: "inbox", texts: [], mode: this.busyInput })
this.o.bus.emit({ type: "inbox", texts: [...this.inbox], mode: this.busyInput })
return true
}
@@ -810,7 +940,9 @@ export class Engine {
this.busy = true
this.o.bus.emit({ type: "prompt", text: shown, ...(meta.turnId ? { turnId: meta.turnId } : {}), ...(meta.attachments?.length ? { attachments: meta.attachments } : {}), ...(meta.machine ? { machine: true as const } : {}) })
try {
return await this.run(text, [...this.pendingContext.splice(0), ...extra], meta.turnId, meta.machine, meta.maxSteps)
const kept = this.carried.notes.splice(0)
if (kept.length) this.saveCarried()
return await this.run(text, [...kept, ...this.pendingContext.splice(0), ...extra], meta.turnId, meta.machine, meta.maxSteps)
} finally {
this.busy = false
}
@@ -825,6 +957,17 @@ export class Engine {
if (!this.kept || this.kept.model !== this.model.ref) await this.o.beforeFirst?.()
// A team's lead holds a slot of its model while its turn runs (team.md §8): it may wait for one.
if (this.o.team?.beforeTurn && !(await this.o.team.beforeTurn(signal))) {
// Stopped while it waited for a slot. The turn has begun for everyone who listens — its
// `task` start and its `prompt` were said — so its message is in the conversation as any
// stopped turn's is, under the turn's id: a note that started it is not lost with it (and
// what was waiting to go in with it, `extra`, is not either), and the model reads it with
// the next message.
this.push({
role: "user",
parts: [{ type: "text", text }, ...extra.map((t) => (typeof t === "string" ? { type: "text" as const, text: t } : t))],
...(turnId ? { turnId } : {}),
...(machine ? { machine } : {}),
})
bus.emit({ type: "done", reason: "cancelled" })
return "cancelled"
}
@@ -975,7 +1118,16 @@ export class Engine {
bus.emit({ type: "notice", level: "warn", message: `the reply hit the output limit${limit} while writing a tool call; a call cut short is not run, and the model is told to split it` })
// The model is done, but the user said something meanwhile: it carries on with that, in the
// same task.
if (calls.length === 0 && !wrapUp && (this.notes.length || (this.busyInput === "steer" && this.inbox.length))) continue
if (calls.length === 0 && !wrapUp && this.hasInput()) continue
// A run with nobody at it is not over while its subagents work: it waits for their reports,
// which come in at this step boundary, and answers after the last one.
if (calls.length === 0 && !wrapUp && this.o.hold) {
if (await this.awaitReports(signal)) continue
if (signal.aborted) {
bus.emit({ type: "done", reason: "cancelled" })
return "cancelled"
}
}
if (calls.length === 0 || wrapUp) {
const reason = wrapUp ? (ranOut ? "budget" : "steps") : "stop"
bus.emit({ type: "done", reason })
+49
View File
@@ -0,0 +1,49 @@
// What a session still has out when no turn of it runs (harness/acp.md, *A session that still has
// work out*; conformance/outstanding.json): subagents that work or wait, a report that waits for
// the main agent, background commands that run. One rule, asked by three things: a schedule's run
// (it is not over while its subagents work), the service (it does not start again, close the link
// or let a terminal take the session while any of it is out), and whoever says why.
export interface OutstandingInput {
/** The team as its tree has it: the main agent (`lead`) and every live subagent, with its state. */
agents: { name: string; state: string }[]
/** The session's background jobs that are not a team's members (those count once, by their
* state in `agents`): `kind` and `state` as in JobInfo. */
jobs: { id: string; kind: string; state: string }[]
}
export interface Outstanding {
/** Who still works for the session and will report: the subagents working, waiting for a slot
* or in their last turn (`paused`), by name in tree order, then the background `task`
* subagents still running, by job id. */
subagents: string[]
/** The background commands still running, by job id. */
commands: string[]
/** A schedule's run does not end yet: a subagent is out, or a report waits for the main agent
* (it is `waiting` for a slot). Background commands do not hold a run: one may never end. */
run_waits: boolean
/** The session is not idle, though no turn runs: anything above. */
has_work: boolean
}
const LEAD = "lead"
const OUT = new Set(["working", "waiting", "paused"])
export function outstanding(o: OutstandingInput): Outstanding {
const members = o.agents.filter((a) => a.name !== LEAD && OUT.has(a.state)).map((a) => a.name)
const running = o.jobs.filter((j) => j.state === "running")
const subagents = [...members, ...running.filter((j) => j.kind === "subagent").map((j) => j.id)]
const commands = running.filter((j) => j.kind === "command").map((j) => j.id)
const run_waits = subagents.length > 0 || o.agents.some((a) => a.name === LEAD && a.state === "waiting")
return { subagents, commands, run_waits, has_work: run_waits || commands.length > 0 }
}
/** Why a session with work out is not let go of, in words a person at a terminal reads. */
export function outstandingReason(out: Outstanding): string | undefined {
if (!out.has_work) return undefined
const parts: string[] = []
if (out.subagents.length) parts.push(`its subagent${out.subagents.length === 1 ? "" : "s"} still work${out.subagents.length === 1 ? "s" : ""} (${out.subagents.join(", ")})`)
else if (out.run_waits) parts.push("a subagent's report is about to start its next turn")
if (out.commands.length) parts.push(`${out.commands.length === 1 ? "a background command still runs" : "background commands still run"} (${out.commands.join(", ")})`)
return `this session is not idle in the service: ${parts.join(", and ")}. A terminal cannot take them over — wait for them to finish, or stop them in the web UI (the Team panel, the job strip), then try again`
}
+170
View File
@@ -0,0 +1,170 @@
// `session/cancel` with the turn named (harness/acp.md; spec 3.10.0, capability harness_turns): a
// prompt that waits behind a turn its client did not start is taken out of the queue — answered as
// cancelled, never run — and the turn that runs is not touched. Without the id, the running turn.
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent, type Limits } from "../src/acp/agent.ts"
import { Hub } from "../src/acp/hub.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { Share } from "../src/acp/share.ts"
import { createApp } from "../src/app.ts"
import { paths } from "../src/config/paths.ts"
import { setTrust } from "../src/project/root.ts"
import { delta, fakeProvider, toolCall, type Fake, type Scripted } from "./fake-provider.ts"
let fake: Fake | undefined
const stops: (() => unknown)[] = []
const roots: string[] = []
afterEach(async () => {
for (const root of roots.splice(0)) writeFileSync(join(root, "f1"), "")
for (const s of stops.splice(0).reverse()) await s()
fake?.stop()
})
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, o: typeof a): Transport => ({
send: (t) => queueMicrotask(() => o.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), o.end()),
})
return [side(a, b), side(b, a)]
}
const SLOW = 30_000
const say = (text: string): Scripted => ({ chunks: [delta({ content: text }, "stop")] })
/** A reply that stays open for `ms` after its first words. */
const slow = (text: string, ms: number): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms })
const waitFor = (flag: string) => `until [ -e ${flag} ]; do sleep 0.05; done`
function setup(script: Scripted[]) {
fake = fakeProvider(script)
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: { f/m: {} }\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), "model: f/m\nmode: auto\n")
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-cancel-")))
setTrust(dir, "trusted")
roots.push(dir)
return dir
}
const limitsFor = (root: string): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true })
async function link(root: string, hub?: Hub) {
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limitsFor(root), undefined, hub)
const c = new Peer(tb)
const events: any[] = []
c.on("_lembas/event", (p) => void events.push(p.event))
c.on("_lembas/session/announce", () => {})
c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
return { c, events }
}
const until = async (ok: () => boolean | Promise<boolean>, ms = 10_000) => {
const end = Date.now() + ms
while (Date.now() < end && !(await ok())) await Bun.sleep(20)
return ok()
}
const go = (c: Peer, sid: string, text: string, meta: Record<string, unknown>) => c.request<any>("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], _meta: { lembas: meta } })
const cancel = (c: Peer, sid: string, turnId?: string) => c.request<any>("session/cancel", { sessionId: sid, ...(turnId ? { _meta: { lembas: { turnId } } } : {}) })
test("a queued prompt named by its turn is taken out of the queue; the harness turn that runs is not touched", async () => {
const root = setup([{ chunks: [toolCall(0, "j1", "bash", JSON.stringify({ command: waitFor("f1"), background: true, description: "wait for f1" })), delta({}, "tool_calls")] }, say("Started."), slow("Seen the end.", 4000)])
const { c, events } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
const status = () => c.request<any>("_lembas/session/status", { sessionId: sid })
await go(c, sid, "go", { turnId: "web-1" })
writeFileSync(join(root, "f1"), "")
// The harness's turn runs, and its reply has begun.
expect(await until(() => events.some((e) => e.type === "prompt" && e.machine) && events.some((e) => e.type === "text" && e.text === "… "))).toBe(true)
const m = events.find((e) => e.type === "prompt" && e.machine)
let answer: any
const second = go(c, sid, "and now this", { turnId: "web-2" }).then((r) => (answer = r))
expect(await until(async () => (await status()).queued.includes("web-2"))).toBe(true)
// An id nobody has, and one that finished: nothing is done.
expect(await cancel(c, sid, "nobody")).toEqual({ cancelled: "none" })
expect(await cancel(c, sid, "web-1")).toEqual({ cancelled: "none" })
expect(await status()).toMatchObject({ busy: true, turnId: m.turnId, queued: ["web-2"] })
// The queued one: out of the queue, answered as cancelled now — while the other turn still runs.
expect(await cancel(c, sid, "web-2")).toEqual({ cancelled: "queued" })
await second
expect(answer).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "web-2" } } })
expect(await status()).toMatchObject({ busy: true, turnId: m.turnId, queued: [] })
expect(events.some((e) => e.type === "done" && e.reason === "cancelled")).toBe(false)
// The harness turn, named: stopped.
expect(await cancel(c, sid, m.turnId)).toEqual({ cancelled: "running" })
expect(await until(() => events.some((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId))).toBe(true)
expect(await until(async () => !(await status()).busy)).toBe(true)
// The withdrawn prompt never ran — not then, and not when its place in the queue came; sent
// again, its id is known and it is answered as cancelled.
expect(fake!.requests).toHaveLength(3)
expect(events.filter((e) => e.type === "prompt").map((e) => e.turnId)).toEqual(["web-1", m.turnId])
expect(await go(c, sid, "and now this", { turnId: "web-2" })).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "web-2" } } })
expect(fake!.requests).toHaveLength(3)
// Nothing runs now: ACP's own cancel finds nothing either.
expect(await cancel(c, sid)).toEqual({ cancelled: "none" })
}, SLOW)
test("a queued scheduled run taken back answers as a cancelled run", async () => {
const root = setup([slow("First.", 3000)])
const { c, events } = await link(root)
const meta = { scheduled: { schedule_id: "sched1", run_id: "run8", title: "Check", mode: "auto" } }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
// The person writes into the run's chat; the next run arrives meanwhile and waits.
const first = go(c, sid, "hello", { turnId: "web-1" })
expect(await until(() => events.some((e) => e.type === "text" && e.text === "… "))).toBe(true)
const run = go(c, sid, "check", { turnId: "run8", ...meta })
expect(await until(async () => (await c.request<any>("_lembas/session/status", { sessionId: sid })).queued.includes("run8"))).toBe(true)
expect(await cancel(c, sid, "run8")).toEqual({ cancelled: "queued" })
expect(await run).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "run8", scheduled: { run_id: "run8", status: "cancelled", text: "", error: null } } } })
expect((await first).stopReason).toBe("end_turn")
expect(fake!.requests).toHaveLength(1)
}, SLOW)
test("in a session a terminal runs: a web prompt that has not started there is taken back, and nothing is sent when its turn comes", async () => {
const root = setup([say("typed here")])
const hub = new Hub({ service: true, limits: { ...limitsFor(root), enabled: true } })
expect(await hub.listen()).toBe(true)
stops.push(() => hub.close())
const { c } = await link(root, hub)
// The terminal is busy with something of its own until the test lets it go on.
let free!: () => void
const busy = new Promise<void>((r) => (free = r))
let begun = 0
const app = createApp({ cwd: root, modelTitles: false, asker: { ask: async () => ({ kind: "once" as const }) } })
const share = new Share(app, {
prompt: async (r, started) => {
await busy
started()
begun++
return app.turns.prompt(r.prompt, r.extra, r.shown, { turnId: r.turnId, attachments: r.attachments })
},
compact: () => app.engine.compact(),
deleted: () => app.newSession(),
notice: () => {},
changed: () => {},
})
stops.push(() => share.close())
await share.start()
const sid = app.engine.sessionId!
expect(await until(() => hub.shared.has(sid))).toBe(true)
const sent = go(c, sid, "from the web", { turnId: "web-1" })
expect(await until(async () => (await c.request<any>("_lembas/session/status", { sessionId: sid })).queued.includes("web-1"))).toBe(true)
expect(await cancel(c, sid, "nobody")).toEqual({ cancelled: "none" })
expect(await cancel(c, sid, "web-1")).toEqual({ cancelled: "queued" })
expect(await sent).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "web-1" } } })
// The terminal comes to it: it is gone.
free()
await busy
await Bun.sleep(0)
expect(begun).toBe(0)
expect(fake!.requests).toHaveLength(0)
expect(app.turns.current).toBeUndefined()
}, SLOW)
+374
View File
@@ -0,0 +1,374 @@
// What a session still has out after its turn's reply (harness/acp.md: *A turn the harness starts*,
// *Scheduled work on a linked computer*; spec 3.10.0): subagents that work, background jobs, a
// note or a steered message that has not reached the model. None of it is lost — not to a terminal
// opening the session, not to the service starting again, not to Stop, and not to a restart — and
// a schedule's run is not over while its subagents work.
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent, type Limits } from "../src/acp/agent.ts"
import { Hub } from "../src/acp/hub.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { releaseForResume } from "../src/acp/share.ts"
import { createApp, type App } from "../src/app.ts"
import type { AskReply } from "../src/bus/index.ts"
import { paths } from "../src/config/paths.ts"
import { LOOP } from "../src/harness.ts"
import { MARKS } from "../src/jobs/note.ts"
import { setTrust } from "../src/project/root.ts"
import { delta, fakeProvider, toolCall, type Fake, type Scripted } from "./fake-provider.ts"
let fake: Fake | undefined
const stops: (() => unknown)[] = []
const roots: string[] = []
afterEach(async () => {
// Whatever a test left waiting for its flag ends now: no loop outlives the test, pass or fail.
for (const root of roots.splice(0)) for (const flag of ["f1", "f-api", "f-web"]) writeFileSync(join(root, flag), "")
for (const s of stops.splice(0).reverse()) await s()
fake?.stop()
})
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, o: typeof a): Transport => ({
send: (t) => queueMicrotask(() => o.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), o.end()),
})
return [side(a, b), side(b, a)]
}
const SLOW = 30_000
const say = (text: string): Scripted => ({ chunks: [delta({ content: text }, "stop")] })
const call = (id: string, name: string, args: unknown): Scripted => ({ chunks: [toolCall(0, id, name, JSON.stringify(args)), delta({}, "tool_calls")] })
/** A reply that stays open for `ms` after its first words: time to look at the turn while it runs. */
const slow = (text: string, ms = 2500): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms })
const system = (body: any): string => body.messages[0].content
const memberName = (body: any): string | undefined => /You are "([a-z0-9-]+)" \(s\d+\), a subagent/.exec(system(body))?.[1]
const users = (body: any): string => body.messages.filter((m: any) => m.role === "user").map((m: any) => (typeof m.content === "string" ? m.content : m.content.map((p: any) => p.text ?? "").join("\n"))).join("\n")
const leads = () => fake!.requests.filter((r) => !memberName(r))
/** The lead's script — its replies in order — and each member's by its name. A member that has
* said all it has says it is done. */
function scripted(lead: Scripted[], members: Record<string, Scripted[]> = {}) {
const at: Record<string, number> = {}
return (body: any): Scripted => {
const who = memberName(body) ?? "lead"
const list = who === "lead" ? lead : (members[who] ?? [])
const n = (at[who] = (at[who] ?? -1) + 1)
return list[n] ?? say(`${who} has nothing more.`)
}
}
/** A command that ends when the test lets it (`release`): never before, however slow the machine. */
const waitFor = (flag: string) => `until [ -e ${flag} ]; do sleep 0.05; done`
const add = (name: string, id = `add-${name}`) => call(id, "team_add", { name, role: `the ${name}`, task: `Do the ${name}.`, goal: "a service" })
/** A member that works until its flag is there, then reports. */
const member = (name: string, report = `The ${name} is done.`): Scripted[] => [call(`w-${name}`, "bash", { command: waitFor(`f-${name}`) }), say(report)]
function setup(script: Scripted[] | ((body: any, n: number) => Scripted | undefined), o: { config?: string; model?: string; models?: string } = {}) {
fake = fakeProvider(script)
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: ${o.models ?? "{ f/m: {} }"}\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), `model: ${o.model ?? "f/m"}\nmode: auto\n${o.config ?? ""}`)
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-out-")))
Bun.spawnSync(["git", "init", "-q", dir])
setTrust(dir, "trusted")
roots.push(dir)
return dir
}
const limitsFor = (root: string, extra: Partial<Limits> = {}): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true, ...extra })
/** A fake LLeMbas on a link of its own — to `hub`'s sessions when there is one. */
async function link(root: string, hub?: Hub) {
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limitsFor(root), undefined, hub)
const c = new Peer(tb)
const events: any[] = []
c.on("_lembas/event", (p) => void events.push(p.event))
c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
const machine = () => events.filter((e) => e.type === "prompt" && e.machine === true)
const ended = (turnId: string) => events.some((e) => e.type === "task" && e.state === "end" && e.turnId === turnId)
const texts = () => events.filter((e) => e.type === "text").map((e) => e.text).join("")
return { c, events, machine, ended, texts, drop: () => tb.close() }
}
async function service(root: string) {
const hub = new Hub({ service: true, limits: { ...limitsFor(root), enabled: true } })
expect(await hub.listen()).toBe(true)
stops.push(async () => {
for (const s of hub.held.values()) await s.app.close().catch(() => {})
hub.close()
})
return hub
}
const until = async (ok: () => boolean, ms = 10_000) => {
const end = Date.now() + ms
while (Date.now() < end && !ok()) await Bun.sleep(20)
return ok()
}
const go = (c: Peer, sid: string, text = "go", meta: Record<string, unknown> = {}) => c.request<any>("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], ...(Object.keys(meta).length ? { _meta: { lembas: meta } } : {}) })
const sched = (extra: Record<string, unknown> = {}) => ({ schedule_id: "sched1", run_id: "run7", title: "Check", mode: "auto", ...extra })
const waitingForSubagents = (events: any[]) => events.some((e) => e.type === "phase" && !e.agent && e.progress?.phase === "waiting_for_subagents")
// ── 1. A session with subagents or jobs out is not let go of ─────────────────────────────────
test("a subagent still works after the lead's turn: the service is busy, a terminal is refused in words, and the report still comes", async () => {
const root = setup(scripted([add("api"), say("api is on it."), say("All done.")], { api: member("api") }))
const hub = await service(root)
const { c, machine, ended, texts } = await link(root, hub)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
expect((await go(c, sid)).stopReason).toBe("end_turn")
// No turn runs — and the session is not idle: its subagent works.
expect((await c.request<any>("_lembas/session/status", { sessionId: sid })).busy).toBe(false)
expect(hub.busy()).toBe(true)
const why = await releaseForResume(sid)
expect(why).toContain("api")
expect(why).toContain("subagent")
// Nothing was stopped by the asking: the member reports, and the lead answers.
writeFileSync(join(root, "f-api"), "")
expect(await until(() => machine().length === 1 && ended(machine()[0].turnId))).toBe(true)
expect(texts()).toContain("All done.")
expect(users(leads().at(-1))).toContain("[Team report from api to lead:]\nThe api is done.")
// Now it is idle, and a terminal may have it.
expect(await until(() => !hub.busy())).toBe(true)
expect(await releaseForResume(sid)).toBeUndefined()
expect(hub.held.has(sid)).toBe(false)
}, SLOW)
test("a background command still runs after the turn: busy, and a terminal is told which job", async () => {
const root = setup([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), say("Started."), say("Seen the end.")])
const hub = await service(root)
const { c, machine, ended } = await link(root, hub)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid)
expect(hub.busy()).toBe(true)
const why = await releaseForResume(sid)
expect(why).toContain("job1")
expect(hub.held.has(sid)).toBe(true)
writeFileSync(join(root, "f1"), "")
expect(await until(() => machine().length === 1 && ended(machine()[0].turnId))).toBe(true)
expect(await until(() => !hub.busy())).toBe(true)
expect(await releaseForResume(sid)).toBeUndefined()
}, SLOW)
// ── 2. A schedule's run is not over while its subagents work ─────────────────────────────────
test("a scheduled run that uses a team: one turn, the answer and the report from its last reply — after the member reported", async () => {
const report = { title: "The API", summary: "The API is written.", body: "## Done\n\nsrc/api.ts" }
const root = setup(scripted([add("api"), say("api is on it."), call("r1", "report_write", report), say("Filed: the API is done.")], { api: member("api") }))
const { c, events, machine } = await link(root)
const meta = { scheduled: sched({ notify: "always" }) }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
let answered = false
const run = go(c, sid, "check", { turnId: "run7", ...meta }).then((r) => ((answered = true), r))
await until(() => answered || waitingForSubagents(events))
// The lead's reply has ended and the member works: the run has not answered.
expect(answered).toBe(false)
expect(await c.request<any>("_lembas/session/status", { sessionId: sid })).toMatchObject({ busy: true, turnId: "run7" })
writeFileSync(join(root, "f-api"), "")
const r = await run
expect(r.stopReason).toBe("end_turn")
expect(r._meta.lembas.scheduled).toEqual({ run_id: "run7", status: "ok", text: "Filed: the API is done.", error: null, report: { ...report, importance: "normal" } })
// One turn from start to end: the report came in at a step, not as a turn of its own.
expect(events.filter((e) => e.type === "task").map((e) => `${e.state} ${e.turnId}`)).toEqual(["start run7", "end run7"])
expect(machine()).toHaveLength(0)
expect(users(leads()[2])).toContain("[Team report from api to lead:]\nThe api is done.")
// A schedule's session is offered a team, and its run report_write.
const tools = leads()[0].tools.map((t: any) => t.function.name)
expect(tools).toEqual(expect.arrayContaining(["team_add", "report_write"]))
// Nothing of the run is left working.
const after = await c.request<any>("_lembas/session/status", { sessionId: sid })
expect(after.busy).toBe(false)
expect(after.tree.agents.filter((a: any) => a.state === "working" || a.state === "waiting").map((a: any) => a.name)).toEqual([])
}, SLOW)
test("a waiting run holds no slot: with two slots and two subagents both work at once, and each report comes into the one turn", async () => {
const root = setup(scripted([add("api"), add("web"), say("Both are on it."), say("One is in."), say("Both are in.")], { api: member("api"), web: member("web") }), { models: "{ f/m: { parallel: 2 } }" })
const { c, events, machine } = await link(root)
const meta = { scheduled: sched() }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
let answered = false
const run = go(c, sid, "check", { turnId: "run7", ...meta }).then((r) => ((answered = true), r))
await until(() => answered || waitingForSubagents(events))
expect(answered).toBe(false)
// While the main agent's own turn ran, web waited for a slot; now it has the main agent's.
const states = async () => Object.fromEntries((await c.request<any>("_lembas/session/status", { sessionId: sid })).tree.agents.map((a: any) => [a.name, a.state]))
expect(await states()).toEqual({ lead: "idle", api: "working", web: "working" })
writeFileSync(join(root, "f-api"), "")
expect(await until(() => answered || leads().length === 4)).toBe(true)
expect(answered).toBe(false)
writeFileSync(join(root, "f-web"), "")
const r = await run
expect(r._meta.lembas.scheduled).toMatchObject({ status: "ok", text: "Both are in." })
expect(events.filter((e) => e.type === "task").map((e) => `${e.state} ${e.turnId}`)).toEqual(["start run7", "end run7"])
expect(machine()).toHaveLength(0)
expect(users(leads()[3])).toContain("[Team report from api to lead:]")
expect(users(leads()[4])).toContain("[Team report from web to lead:]")
expect(await states()).toEqual({ lead: "idle", api: "finished", web: "finished" })
}, SLOW)
// ── 6. Stop ──────────────────────────────────────────────────────────────────────────────────
test("Stop on a scheduled run stops the run: the turn, and the subagent still working for it", async () => {
const root = setup(scripted([add("api"), say("api is on it.")], { api: member("api") }))
const { c, events, machine } = await link(root)
const meta = { scheduled: sched() }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
let answered = false
const run = go(c, sid, "check", { turnId: "run7", ...meta }).then((r) => ((answered = true), r))
await until(() => answered || waitingForSubagents(events))
expect(answered).toBe(false)
c.notify("session/cancel", { sessionId: sid })
const r = await run
expect(r.stopReason).toBe("cancelled")
expect(r._meta.lembas.scheduled.status).toBe("cancelled")
// The member left with the run: stopped, and nothing of it starts a turn afterwards.
const tree = (await c.request<any>("_lembas/session/status", { sessionId: sid })).tree
expect(tree.agents.map((a: any) => a.name)).toEqual(["lead"])
expect(tree.ended.map((a: any) => `${a.name} ${a.state}`)).toEqual(["api stopped"])
const asked = fake!.requests.length
writeFileSync(join(root, "f-api"), "")
await Bun.sleep(300)
expect(fake!.requests).toHaveLength(asked)
expect(machine()).toHaveLength(0)
}, SLOW)
test("Stop in a chat stops the turn that runs and no subagent: the next report starts a turn as any does", async () => {
const root = setup(scripted([add("api"), add("web"), say("Both are on it."), slow("Looking at the API.", 5000), say("And the web is in.")], { api: member("api"), web: member("web") }))
const { c, events, machine, ended } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid)
writeFileSync(join(root, "f-api"), "")
// Stopped once its reply has begun: the model was asked, so the next turn gets the next reply.
expect(await until(() => machine().length === 1 && events.some((e) => e.type === "text" && e.text === "… "))).toBe(true)
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(machine()[0].turnId))).toBe(true)
expect(events.some((e) => e.type === "done" && e.reason === "cancelled")).toBe(true)
// web was not stopped with the lead's turn.
const tree = (await c.request<any>("_lembas/session/status", { sessionId: sid })).tree
expect(tree.agents.find((a: any) => a.name === "web").state).toBe("working")
writeFileSync(join(root, "f-web"), "")
expect(await until(() => machine().length === 2 && ended(machine()[1].turnId))).toBe(true)
expect(machine()[1].text).toBe("⏎ [Team report from web to lead:]")
}, SLOW)
// ── 3. Stop while a wake turn waits for a model slot ─────────────────────────────────────────
test("Stop while a wake turn waits for a slot: its note stays in the history under the turn's id, and the model reads it next", async () => {
const root = setup(
scripted([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), add("api"), add("web"), say("Waiting."), say("All in.")], { api: member("api"), web: member("web") }),
{ models: "{ f/m: { parallel: 2 } }" },
)
const { c, events, machine, ended } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid, "go", { turnId: "web-1" })
// Both slots are the members'. The job ends: its note wakes the lead, which waits for a slot.
writeFileSync(join(root, "f1"), "")
expect(await until(() => machine().length === 1 && events.some((e) => e.type === "notice" && String(e.message).startsWith("waiting for a free slot")))).toBe(true)
const m = machine()[0]
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(m.turnId))).toBe(true)
// The client was told the turn began: the history has it, as it has any stopped turn.
const h: any = await c.request("_lembas/session/history", { sessionId: sid })
const note = h.turns.find((t: any) => t.turnId === m.turnId)
expect(note).toBeDefined()
expect(note.machine).toBe(true)
expect(note.text).toStartWith(`${MARKS.command}\njob1 (${waitFor("f1")}) exited with 0`)
// …and the model reads it with what comes next.
writeFileSync(join(root, "f-api"), "")
writeFileSync(join(root, "f-web"), "")
expect(await until(() => leads().some((r) => users(r).includes("[Team report from")))).toBe(true)
expect(users(leads().at(-1))).toContain(`job1 (${waitFor("f1")}) exited with 0`)
}, SLOW)
// ── 4, 7. A message steered into a turn the harness started ──────────────────────────────────
test("a steer a wake turn never took in comes back on the turn's end — said before the queue is said empty", async () => {
const root = setup([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), say("Started."), slow("Never finished.", 5000)])
const { c, events, machine, ended } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid)
writeFileSync(join(root, "f1"), "")
expect(await until(() => machine().length === 1)).toBe(true)
const m = machine()[0]
await c.request("_lembas/steer", { sessionId: sid, text: "one more thing" })
const steered = events.length
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(m.turnId), 3000)).toBe(true)
await Bun.sleep(50)
const end = events.findIndex((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId)
expect(events[end].unsent).toEqual(["one more thing"])
const emptied = events.findIndex((e, i) => i >= steered && e.type === "inbox" && e.texts.length === 0)
expect(emptied === -1 || emptied > end).toBe(true)
}, SLOW)
test("a steer left over with no client listening is kept with the session — across a restart — and goes in at the next turn's first step, once", async () => {
// busy_input: queue — the mode in which nothing went in at a step by itself.
const root = setup([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), say("Started."), slow("Seen the end.", 1500), say("And that too.")], { config: "busy_input: queue\n" })
const hub = await service(root)
const first = await link(root, hub)
const s: any = await first.c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(first.c, sid, "go", { turnId: "web-1" })
writeFileSync(join(root, "f1"), "")
expect(await until(() => first.machine().length === 1)).toBe(true)
expect(await first.c.request<any>("_lembas/steer", { sessionId: sid, text: "and one more thing", messageId: "web-2" })).toEqual({ queued: 1 })
// The link goes; the turn ends with nobody to hand the message back to.
first.drop()
const held = hub.held.get(sid)!
expect(await until(() => held.own === undefined && !held.app.engine.busy)).toBe(true)
// The device starts again: the session is opened from the store, by another process's agent.
await held.app.close()
hub.held.delete(sid)
const again = await link(root)
const r = await go(again.c, sid, "next", { turnId: "web-3" })
expect(r.stopReason).toBe("end_turn")
// In at the first step of the next turn, said with its id — and not handed back as well.
expect(again.events.find((e) => e.type === "steered")).toMatchObject({ texts: ["and one more thing"], ids: ["web-2"] })
expect(users(fake!.requests.at(-1))).toContain("and one more thing")
expect(r._meta.lembas.unsent).toBeUndefined()
// Once: the turn after it does not carry it again.
const h: any = await again.c.request("_lembas/session/history", { sessionId: sid })
expect(JSON.stringify(h.turns).split("and one more thing")).toHaveLength(2)
// The harness's turn is still marked as one after the restart (the store keeps `machine`).
expect(h.turns.filter((t: any) => t.machine).map((t: any) => t.turnId)).toEqual([first.machine()[0].turnId])
}, SLOW)
// ── 5. A wake that is refused leaves the lead idle, and the note waits ───────────────────────
test("a report that may not start a turn (a schedule's session on an interactive-only model): the lead is idle again, and the report goes in with the person's next message", async () => {
const root = setup(scripted([add("api"), say("api is on it."), say("Here it is.")], { api: member("api") }), { model: "open/flash", models: "{ open/flash: {}, plan/coder: { interactive_only: true } }" })
const yes = { ask: async (): Promise<AskReply> => ({ kind: "once" }) }
const app: App = createApp({ cwd: root, asker: yes, snapshots: false, modelTitles: false, kind: "scheduled" })
stops.push(() => app.close())
const notices: string[] = []
app.bus.on((e) => e.type === "notice" && notices.push(e.message))
// The person writes into the run's chat, and the lead starts a subagent.
await app.turns.prompt("build it")
// Between turns the session's model is changed to the plan's.
app.chooseModel("plan/coder")
writeFileSync(join(root, "f-api"), "")
expect(await until(() => notices.some((n) => n.includes("did not start a turn")))).toBe(true)
expect(app.engine.busy).toBe(false)
expect(app.team.team.get("lead")!.state).toBe("idle")
// The person's next turn carries the report.
await app.turns.prompt("and?")
expect(users(leads().at(-1))).toContain("[Team report from api to lead:]\nThe api is done.")
expect(LOOP.interactive.texts.scheduled).toContain("interactive use only")
}, SLOW)
+143
View File
@@ -0,0 +1,143 @@
// A steered message is given to the model once (harness/acp.md `_lembas/steer`; spec 3.10.0): a
// prompt carrying the id of a message the session was steered does not run — it says what became
// of the message — and a prompt's turn that ends with no link up carries its too-late steers to
// the next turn, as a turn the harness started does.
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent, type Limits } from "../src/acp/agent.ts"
import { Hub } from "../src/acp/hub.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { paths } from "../src/config/paths.ts"
import { setTrust } from "../src/project/root.ts"
import { delta, fakeProvider, type Fake, type Scripted } from "./fake-provider.ts"
let fake: Fake | undefined
const stops: (() => unknown)[] = []
afterEach(async () => {
for (const s of stops.splice(0).reverse()) await s()
fake?.stop()
})
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, o: typeof a): Transport => ({
send: (t) => queueMicrotask(() => o.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), o.end()),
})
return [side(a, b), side(b, a)]
}
const SLOW = 30_000
const say = (text: string): Scripted => ({ chunks: [delta({ content: text }, "stop")] })
const slow = (text: string, ms: number): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms })
const users = (body: any): string => body.messages.filter((m: any) => m.role === "user").map((m: any) => (typeof m.content === "string" ? m.content : m.content.map((p: any) => p.text ?? "").join("\n"))).join("\n")
function setup(script: Scripted[], config = "") {
fake = fakeProvider(script)
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: { f/m: {} }\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), `model: f/m\nmode: auto\n${config}`)
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-once-")))
setTrust(dir, "trusted")
return dir
}
const limitsFor = (root: string): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true })
async function link(root: string, hub?: Hub) {
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limitsFor(root), undefined, hub)
const c = new Peer(tb)
const events: any[] = []
c.on("_lembas/event", (p) => void events.push(p.event))
await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
return { c, events, drop: () => tb.close() }
}
async function service(root: string) {
const hub = new Hub({ service: true, limits: { ...limitsFor(root), enabled: true } })
expect(await hub.listen()).toBe(true)
stops.push(async () => {
for (const s of hub.held.values()) await s.app.close().catch(() => {})
hub.close()
})
return hub
}
const until = async (ok: () => boolean, ms = 10_000) => {
const end = Date.now() + ms
while (Date.now() < end && !ok()) await Bun.sleep(20)
return ok()
}
const go = (c: Peer, sid: string, text: string, turnId: string) => c.request<any>("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], _meta: { lembas: { turnId } } })
const begun = (events: any[]) => events.some((e) => e.type === "text" && e.text === "… ")
test("a message the turn took in, sent again as a prompt with its id, does not run: taken — also after a restart", async () => {
const root = setup([slow("First.", 1000), say("With it.")])
const hub = await service(root)
const { c, events } = await link(root, hub)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
const first = go(c, sid, "go", "web-1")
expect(await until(() => begun(events))).toBe(true)
await c.request("_lembas/steer", { sessionId: sid, text: "and say hello", messageId: "web-2" })
// While it waits in the running turn's queue, the same id as a prompt runs nothing either.
expect(await go(c, sid, "and say hello", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "waiting" } } })
expect((await first)._meta.lembas.unsent).toBeUndefined()
expect(events.find((e) => e.type === "steered")).toMatchObject({ ids: ["web-2"] })
expect(fake!.requests).toHaveLength(2)
expect(await go(c, sid, "and say hello", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "taken" } } })
// The device starts again: the session comes from the store, and still knows the id.
const held = hub.held.get(sid)!
await held.app.close()
hub.held.delete(sid)
const again = await link(root)
expect(await go(again.c, sid, "and say hello", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "taken" } } })
expect(fake!.requests).toHaveLength(2)
expect(again.events.some((e) => e.type === "prompt")).toBe(false)
}, SLOW)
test("a prompt's turn that ends with no link up carries its too-late steer; its id as a prompt says carried, then taken — the model reads it once", async () => {
// busy_input: queue — nothing goes in at a step by itself, so the turn ends with it waiting.
const root = setup([slow("First.", 1000), say("Second."), say("Third.")], "busy_input: queue\n")
const hub = await service(root)
const first = await link(root, hub)
const s: any = await first.c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
void go(first.c, sid, "go", "web-1").catch(() => {})
expect(await until(() => begun(first.events))).toBe(true)
await first.c.request("_lembas/steer", { sessionId: sid, text: "one more thing", messageId: "web-2" })
first.drop()
const held = hub.held.get(sid)!
expect(await until(() => !held.prompting && !held.app.engine.busy)).toBe(true)
// The link is back. The answer kept for the first prompt hands nothing back: it was carried.
const { c, events } = await link(root, hub)
expect((await go(c, sid, "go", "web-1"))._meta.lembas.unsent).toBeUndefined()
// "Send now" for the message the client is unsure of: not run, and said to be carried.
expect(await go(c, sid, "one more thing", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "carried" } } })
expect(fake!.requests).toHaveLength(1)
// The next turn takes it in at its first step.
expect((await go(c, sid, "next", "web-3")).stopReason).toBe("end_turn")
expect(events.find((e) => e.type === "steered")).toMatchObject({ texts: ["one more thing"], ids: ["web-2"] })
expect(await go(c, sid, "one more thing", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "taken" } } })
expect(fake!.requests).toHaveLength(2)
expect(users(fake!.requests[1]).split("one more thing")).toHaveLength(2)
}, SLOW)
test("a steer handed back as unsent is the client's again: its id as a prompt runs", async () => {
const root = setup([slow("First.", 1000), say("Now that.")], "busy_input: queue\n")
const { c, events } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
const first = go(c, sid, "go", "web-1")
expect(await until(() => begun(events))).toBe(true)
await c.request("_lembas/steer", { sessionId: sid, text: "then that", messageId: "web-2" })
expect((await first)._meta.lembas.unsent).toEqual(["then that"])
const r = await go(c, sid, "then that", "web-2")
expect(r._meta.lembas.steered).toBeUndefined()
expect(fake!.requests).toHaveLength(2)
expect(events.filter((e) => e.type === "prompt").map((e) => e.turnId)).toEqual(["web-1", "web-2"])
}, SLOW)
+231
View File
@@ -0,0 +1,231 @@
// A turn the harness starts by itself (harness/acp.md, *A turn the harness starts*; spec 3.10.0):
// a finished job's note waking an idle session. Over the link it is a turn like any other — status
// says busy and names it, a message steered joins it, Stop stops it, a prompt waits for it, the
// history keeps it marked `machine` — and two of them never overlap.
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent } from "../src/acp/agent.ts"
import { Peer, RpcError, type Transport } from "../src/acp/rpc.ts"
import { paths } from "../src/config/paths.ts"
import { MARKS } from "../src/jobs/note.ts"
import { setTrust } from "../src/project/root.ts"
import { delta, fakeProvider, toolCall, type Fake, type Scripted } from "./fake-provider.ts"
let fake: Fake | undefined
afterEach(() => fake?.stop())
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, o: typeof a): Transport => ({
send: (t) => queueMicrotask(() => o.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), o.end()),
})
return [side(a, b), side(b, a)]
}
async function client(script: Scripted[]) {
fake = fakeProvider(script)
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: { f/m: {} }\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), "model: f/m\nmode: auto\n")
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-acp-wake-")))
setTrust(dir, "trusted")
const [ta, tb] = pair()
new AcpAgent(new Peer(ta))
const c = new Peer(tb)
const events: any[] = []
c.on("_lembas/event", (p) => void events.push(p.event))
c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
const init: any = await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
const s: any = await c.request("session/new", { cwd: dir, mcpServers: [] })
const sid = s.sessionId as string
const status = () => c.request<any>("_lembas/session/status", { sessionId: sid })
const machine = () => events.filter((e) => e.type === "prompt" && e.machine === true)
const ended = (turnId: string) => events.some((e) => e.type === "task" && e.state === "end" && e.turnId === turnId)
const release = (flag: string) => writeFileSync(join(dir, flag), "")
return { c, events, sid, init, status, machine, ended, release }
}
const SLOW = 20_000
const until = async (ok: () => boolean, ms = 8000) => {
const end = Date.now() + ms
while (Date.now() < end && !ok()) await Bun.sleep(20)
return ok()
}
const said = (p: Promise<unknown>) => p.then(() => undefined, (e) => (e instanceof RpcError ? `${e.code} ${e.message}` : String(e)))
const go = (c: Peer, sid: string, text = "go", turnId?: string) =>
c.request<any>("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], ...(turnId ? { _meta: { lembas: { turnId } } } : {}) })
/** Background commands, each ending when the test lets it (`release`) — so never before the turn
* that started it has ended, however slow the machine — and the reply to having started them. */
const waitFor = (flag: string) => `until [ -e ${flag} ]; do sleep 0.05; done`
const background = (...flags: string[]): Scripted[] => [
{ chunks: flags.map((flag, i) => toolCall(i, `t${i + 1}`, "bash", JSON.stringify({ command: waitFor(flag), background: true, description: `wait for ${flag}` }))) },
{ chunks: [delta({ content: "Started." })] },
]
/** A reply that stays open for `ms` after its first words: time to look at the turn while it runs. */
const slow = (text: string, ms = 2500): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms })
/** The turns in the order their events came: `start <id>`, `prompt <id>`, `text <words>`, `end <id>`,
* with each turn's id replaced by its number. */
function order(events: any[]) {
const n = new Map<string, number>()
const of = (id: string) => n.get(id) ?? (n.set(id, n.size + 1), n.size)
const out: string[] = []
for (const e of events) {
if (e.type === "task") out.push(`${e.state} ${of(e.turnId)}`)
else if (e.type === "prompt") out.push(`prompt ${of(e.turnId)}${e.machine ? " machine" : ""}`)
else if (e.type === "text" && e.text.trim() && e.text !== "… ") out.push(`text ${e.text}`)
}
return out
}
test("status during a wake turn: busy, and the turn named — an id of its own, the one its prompt and task events carry", async () => {
const { c, events, sid, status, machine, ended, release } = await client([...background("f1"), slow("Seen the end.")])
const first = await go(c, sid, "go", "web-1")
release("f1")
expect(await until(() => machine().length === 1)).toBe(true)
const m = machine()[0]
expect(typeof m.turnId).toBe("string")
expect(m.turnId).not.toBe("web-1")
expect(first._meta.lembas.turnId).toBe("web-1")
// Its `task` start came before its prompt, with the same id.
const at = events.indexOf(m)
expect(events.slice(0, at).findLast((e) => e.type === "task")).toEqual({ type: "task", state: "start", turnId: m.turnId })
const during = await status()
expect(during).toMatchObject({ held: "here", busy: true, turnId: m.turnId, queued: [], lastTurnId: "web-1" })
expect(await until(() => ended(m.turnId))).toBe(true)
const after = await status()
expect(after.busy).toBe(false)
expect(after.turnId).toBeUndefined()
expect(after.lastTurnId).toBe(m.turnId)
}, SLOW)
test("initialize lists the harness_turns capability", async () => {
const { init } = await client([])
expect(init._meta.lembas.capabilities).toContain("harness_turns")
}, SLOW)
test("the history keeps a wake turn: its note as a user turn marked machine, with the turn's id, and the reply after it", async () => {
const { c, sid, machine, ended, release } = await client([...background("f1"), { chunks: [delta({ content: "Seen the end." })] }])
await go(c, sid, "go", "web-1")
release("f1")
expect(await until(() => machine().length === 1 && ended(machine()[0].turnId))).toBe(true)
const h: any = await c.request("_lembas/session/history", { sessionId: sid })
expect(h.turns.map((t: any) => t.role)).toEqual(["user", "assistant", "user", "assistant"])
expect(h.turns[0]).toEqual({ role: "user", text: "go", turnId: "web-1" })
expect(h.turns[0].machine).toBeUndefined()
const note = h.turns[2]
expect(note.machine).toBe(true)
expect(note.turnId).toBe(machine()[0].turnId)
expect(note.text).toStartWith(`${MARKS.command}\njob1 (${waitFor("f1")}) exited with 0`)
expect(h.turns[3].text).toBe("Seen the end.")
// The note is never a prompt: its id sent back as one runs nothing, and answers with no answer.
const asked = fake!.requests.length
expect((await c.request("session/prompt", { sessionId: sid, prompt: [{ type: "text", text: note.text }], _meta: { lembas: { turnId: note.turnId } } })) ?? null).toBeNull()
expect(fake!.requests).toHaveLength(asked)
expect(machine()).toHaveLength(1)
}, SLOW)
test("a message steered during a wake turn joins it", async () => {
const { c, events, sid, machine, ended, release } = await client([...background("f1"), slow("Seen the end."), { chunks: [delta({ content: "And hello." })] }])
await go(c, sid)
release("f1")
expect(await until(() => machine().length === 1)).toBe(true)
const m = machine()[0]
expect(await c.request<any>("_lembas/steer", { sessionId: sid, text: "and say hello", messageId: "web-2" })).toEqual({ queued: 1 })
expect(await until(() => ended(m.turnId))).toBe(true)
// Taken in at the turn's next step, inside the turn: before its end, and no turn of its own.
const steered = events.findIndex((e) => e.type === "steered")
expect(events[steered]).toMatchObject({ texts: ["and say hello"], ids: ["web-2"] })
expect(steered).toBeLessThan(events.findIndex((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId))
expect(fake!.requests).toHaveLength(4)
expect(String(fake!.requests[3].messages.at(-1).content)).toContain("and say hello")
expect(order(events).filter((l) => l.startsWith("prompt"))).toEqual(["prompt 1", "prompt 2 machine"])
// The turn's end hands nothing back: the message was taken in.
expect(events.find((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId).unsent).toBeUndefined()
}, SLOW)
test("Stop stops a wake turn; a message it had not taken in comes back on the turn's end", async () => {
const { c, events, sid, status, machine, ended, release } = await client([...background("f1"), slow("Never finished.", 5000)])
await go(c, sid)
release("f1")
expect(await until(() => machine().length === 1)).toBe(true)
const m = machine()[0]
await c.request("_lembas/steer", { sessionId: sid, text: "one more thing" })
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(m.turnId), 3000)).toBe(true)
expect(events.some((e) => e.type === "done" && e.reason === "cancelled")).toBe(true)
expect(events.find((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId)).toEqual({ type: "task", state: "end", turnId: m.turnId, unsent: ["one more thing"] })
expect((await status()).busy).toBe(false)
// Nothing is left to steer into: said in words.
expect(await said(c.request("_lembas/steer", { sessionId: sid, text: "anyone?" }))).toBe("-32602 this session is not working on anything; send it as a prompt")
}, SLOW)
test("a prompt that arrives during a wake turn waits for it: queued in status, run after the turn's end, never beside it", async () => {
const { c, events, sid, status, machine, ended, release } = await client([...background("f1"), slow("Seen the end."), { chunks: [delta({ content: "Second answer." })] }])
await go(c, sid, "go", "web-1")
release("f1")
expect(await until(() => machine().length === 1)).toBe(true)
const m = machine()[0]
const second = go(c, sid, "and now this", "web-2")
await Bun.sleep(100)
expect(await status()).toMatchObject({ busy: true, turnId: m.turnId, queued: ["web-2"] })
expect(ended(m.turnId)).toBe(false)
// Neither compacted nor rewound under a turn that runs, whoever started it.
expect(await said(c.request("_lembas/session/compact", { sessionId: sid }))).toBe("-32602 this session is working — compact it when the reply is done")
expect(await said(c.request("_lembas/session/rewind", { sessionId: sid, turnId: "web-1" }))).toBe("-32602 this session is working — rewind it when the reply is done")
expect(await second).toMatchObject({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2" } } })
expect(order(events)).toEqual([
"start 1", "prompt 1", "text Started.", "end 1",
"start 2", "prompt 2 machine", "text Seen the end.", "end 2",
"start 3", "prompt 3", "text Second answer.", "end 3",
])
expect((await status()).lastTurnId).toBe("web-2")
}, SLOW)
test("two notes one after the other: two turns, each prompt followed by its own events and its own end before the next begins", async () => {
const { c, events, sid, machine, ended, release } = await client([...background("f1", "f2"), { chunks: [delta({ content: "First seen." })] }, { chunks: [delta({ content: "Second seen." })] }])
await go(c, sid)
release("f1")
expect(await until(() => machine().length === 1 && ended(machine()[0].turnId))).toBe(true)
release("f2")
expect(await until(() => machine().length === 2 && ended(machine()[1].turnId))).toBe(true)
const [m1, m2] = machine()
expect(m1.turnId).not.toBe(m2.turnId)
expect(m1.text).toStartWith(`⏎ job1 (${waitFor("f1")})`)
expect(m2.text).toStartWith(`⏎ job2 (${waitFor("f2")})`)
expect(order(events)).toEqual([
"start 1", "prompt 1", "text Started.", "end 1",
"start 2", "prompt 2 machine", "text First seen.", "end 2",
"start 3", "prompt 3 machine", "text Second seen.", "end 3",
])
// Each note is said (`job_note`) before the turn it starts.
const notes = events.filter((e) => e.type === "job_note")
expect(notes.map((n) => n.jobId)).toEqual(["job1", "job2"])
expect(events.indexOf(notes[1])).toBeGreaterThan(events.findIndex((e) => e.type === "task" && e.state === "end" && e.turnId === m1.turnId))
expect(events.indexOf(notes[1])).toBeLessThan(events.findIndex((e) => e.type === "task" && e.state === "start" && e.turnId === m2.turnId))
const h: any = await c.request("_lembas/session/history", { sessionId: sid })
expect(h.turns.filter((t: any) => t.machine).map((t: any) => t.turnId)).toEqual([m1.turnId, m2.turnId])
}, SLOW)
test("a second note that arrives while the first one's turn runs joins that turn: one prompt, one end", async () => {
const { c, events, sid, machine, release } = await client([...background("f1", "f2"), slow("First seen.", 3000), { chunks: [delta({ content: "Both seen." })] }])
await go(c, sid)
release("f1")
expect(await until(() => machine().length === 1)).toBe(true)
release("f2")
expect(await until(() => fake!.requests.length === 4 && events.filter((e) => e.type === "task" && e.state === "end").length === 2)).toBe(true)
await Bun.sleep(200)
expect(machine()).toHaveLength(1)
expect(order(events)).toEqual(["start 1", "prompt 1", "text Started.", "end 1", "start 2", "prompt 2 machine", "text First seen.", "text Both seen.", "end 2"])
expect(events.filter((e) => e.type === "job_note").map((n) => n.jobId)).toEqual(["job1", "job2"])
// The second note went to the model inside the turn, under its mark.
expect(String(fake!.requests[3].messages.at(-1).content)).toStartWith(`${MARKS.command}\njob2 `)
}, SLOW)
+1 -1
View File
@@ -275,7 +275,7 @@ test("the terminal: a real shell through the link, only where remote.terminal sa
config(fake.url)
const root = project()
const off = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true })
expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled", "reports", "directory_model"])
expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled", "reports", "directory_model", "harness_turns"])
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 })
+8
View File
@@ -39,6 +39,8 @@ import { fillPrompt as fillText } from "../src/prompt/fill.ts"
import { isSilent, judgeCase, monitorHash, notifyInstruction, reportResult, reportTool, runLeaves, scheduledMode, stripSentinel } from "../src/acp/scheduled.ts"
import { clientModel, records, startModel, type SessionKind } from "../src/session/lastmodel.ts"
import { cancelOf, reattach } from "../src/acp/turns.ts"
import { outstanding, type OutstandingInput } from "../src/session/outstanding.ts"
import { background, scheduledRefusal, twin, type BackgroundCall, type Listed } from "../src/provider/interactive.ts"
type Case = Record<string, unknown>
@@ -56,6 +58,12 @@ function readableUnder(grants: Record<string, string> | undefined, path: string)
}
export const AREAS: Record<string, (c: Case) => unknown> = {
// Spec 3.10.0: which turn a `session/cancel` touches (src/acp/turns.ts).
cancel: (c) => cancelOf({ turn: c.turn as string | undefined, running: c.running as string | undefined, queued: c.queued as string[] | undefined }),
// Spec 3.10.0: what a session still has out when no turn of it runs (src/session/outstanding.ts).
outstanding: (c) => outstanding(c as unknown as OutstandingInput),
// Spec 3.10.0: a row reattached after a restart or a dropped link — the client's rule (src/acp/turns.ts).
reattach: (c) => reattach({ turn: c.turn as string, machine: c.machine === true, status: c.status as { turnId?: string; queued?: string[]; lastTurnId?: string } }),
// Spec 3.9.0: the model last used in a directory (src/session/lastmodel.ts).
last_model: (c) => {
const str = (k: string) => (typeof c[k] === "string" ? (c[k] as string) : undefined)