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
HomerandClaude Fable 5.2 e7a9037ed3 2.0.0-beta.12
ci / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 00:45:31 +00:00
HomerandClaude Fable 5.2 55706542a4 Review of spec 3.9.0: a schedule's run is never a person's turn
ci / check (push) Canceled after 0s
From an independent review of the round. Spec and CLI together.

- A scheduled prompt for a session open in a terminal is judged, then
  refused (data.reason terminal) instead of being passed to the terminal as
  a person's turn on the terminal's model.
- A schedule's session keeps its model with it: opened from the store again
  — or in a terminal — it is on the model it had, and stays a schedule's
  session there (nothing in it becomes the directory's model).
- On a refused scheduled turn nothing about the session is changed; a
  command's interactive-only model in one is the same -32602 with its
  reason. In a schedule's session a turn a job wakes, and a subagent started
  with no person's turn running, are still scheduled work.
- A rerouted title or summary is counted under the model that was asked and
  that model is named; a model that cannot take a summary (window too
  small, no tools) is nowhere to go.
- A borrowed model is given back with returnModel, so a command whose model
  is the session's own leaves nothing borrowed. What is remembered goes
  through records(), the rule the conformance cases test; a change of model
  inside a turn the harness started is not remembered.
- models.json: a directory's time is refreshed as it is used; a write stats
  nothing, and gone directories are dropped apart from any turn.
- lembas run with no terminal says the way forward, in the refusal and in
  --help.
- Permission rules: a rule written again (the same permission and pattern,
  later) sets the earlier one aside, as a narrower one does. Cases pin it.
- Conformance and the examples use made-up model names.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 00:45:03 +00:00
HomerandClaude Fable 5.2 18e9117ed3 A subagent's own automatic compaction is background work too
ci / check (push) Canceled after 0s
Spec 3.9.0, interactive.md §1 and §3: when a subagent's model is
interactive-only, the summary of its conversation is asked of that model's
twin, else of a default that is not interactive-only, else it is skipped —
said once, to the session the subagent works for — and the subagent goes on.
Before, only the session's own compaction went elsewhere.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 00:27:54 +00:00
HomerandClaude Fable 5.2 4d878b303e Interactive-only models: no scheduled work on one, background calls elsewhere
ci / check (push) Canceled after 0s
Harness spec 3.9.0 (interactive.md), the CLI's side.

- interactive_only is read from /v1/models; /model says which models are
  for interactive use only.
- A session's title and its compaction, asked for or automatic, are not
  asked of an interactive-only model: they go to its twin, else to the
  global model or the server's default when that is not interactive-only;
  with none the title is left, automatic compaction is skipped and said
  once, and a compaction asked for is refused in the spec's words.
- Scheduled work never uses one: a scheduled session/new or session/prompt
  is refused with the sentence and data.reason interactive_only before
  anything is sent, a scheduled turn cannot switch to one or start a
  subagent on one, and a scheduled session opened with no model skips one
  the directory remembers. lembas run with no terminal at all is the same.
- A person's turns, and the subagents of their session, are untouched.

Also the type of LOOP.interactive, which the spec commit left too narrow
for the JSON it reads.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 00:23:19 +00:00
HomerandClaude Fable 5.2 90cccac8bc spec 3.9.0: interactive-only models
ci / check (push) Canceled after 0s
Still 3.9.0, unreleased. A model served through a connection its provider
sells for a person's own turns only says interactive_only: true.

- interactive.md: what is interactive and what is not; scheduled work never
  runs on such a model (a schedule may not name one, a run fails with the
  sentence, a device refuses the scheduled turn itself and its subagents, a
  one-shot run with no terminal ends at once); a session's background calls
  — its title, its compaction — go to the model's twin, else to a default
  that is not interactive-only, else are skipped or refused in words.
- models/schema.json: interactive_only. loop.json: interactive (the field,
  the reason, the two sentences, what each background call does).
- acp.md: the field on /v1/models, data.reason interactive_only, the run's
  model.
- conformance: interactive.json (twin, background, scheduled); three cases
  in last_model.json.

The rules as functions, for the cases; the CLI's wiring follows.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 00:14:12 +00:00
HomerandClaude Fable 5.2 22143b1199 A schedule's session opened from the store again is still offered report_write
ci / check (push) Canceled after 0s
How a schedule opened its session (its notify-when among it) lived in the
agent's memory only. After a restart of the service a continuing schedule's
session came back from the store without it, and its next run was told to
file a report with a tool it had not been given. It is kept in the session's
meta now, where the mark that a schedule opened it already was.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 23:02:12 +00:00
HomerandClaude Fable 5.2 d44fd46c00 The model last used in a directory, remembered on this machine
ci / check (push) Canceled after 0s
Harness spec 3.9.0, the CLI's side.

- A session starts on: the model asked for, the project's setting, the
  model last used in exactly this directory (while the login serves it),
  the global setting, the server's default.
- The directory's model is written when a person's prompt starts a turn and
  when the person changes the model (/model, a setting, _lembas/configure, a
  shared terminal's session) — to models.json in the state directory, and
  nowhere else. Not for a turn the harness started, a command's own model, a
  one-shot run, or anything in a session a schedule opened (kept in the
  session's meta, so it holds after a restart).
- _lembas/directories: `model` on each directory a session may be opened
  in, and `list: false` for one directory alone; capability
  directory_model.
- /schedule names each schedule's type, Chat or Agentic, and /schedule new
  offers the two by name.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 22:55:49 +00:00
HomerandClaude Fable 5.2 2add5695a6 spec 3.9.0: the model last used in a directory; Chat and Agentic schedules
ci / check (push) Canceled after 0s
The harness spec, written ahead of both implementations.

- acp.md: a new section, "The model last used in a directory" — what the
  device remembers and when, how a session of its own starts, what
  _lembas/directories says (model on a Dir, list: false, capability
  directory_model) and the client's rule. Scheduled work: the two types of
  schedule, the run's model, and that a run never becomes the directory's.
- permission/rules.md §2: a narrower rule that a later one narrows again is
  set aside, so .env.example is read after a broad allow as before it.
- conformance: last_model.json (start, record, client), six cases in
  rules.json.

The CLI's side so far: the rule lookup, and the three rules of the new area
as functions; the memory itself and the link follow.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 22:45:26 +00:00
49 changed files with 4940 additions and 141 deletions

No files matched your search

+124 -1
View File
@@ -4,7 +4,130 @@ 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
Harness spec 3.9.0: the model last used in a directory, Chat and Agentic schedules, models that are for a person's own turns only.
Harness spec 3.9.0: the model last used in a directory, the two types of schedule, a permission rule set right.
### Added
- **Harness spec 3.9.0: the model last used in a directory** (`harness/acp.md`). A new agent
session in a directory starts on the model last used in exactly that directory — from the
terminal, the web, the desktop app or a phone — instead of the server's default. The memory is
this machine's (`models.json` in the state directory) and the server keeps no record of it.
`_lembas/directories` tells the server each directory's model (`model`, capability
`directory_model`) and answers for one directory alone with `list: false`.
It is written when you send a prompt and when you change the model (`/model`, a setting, the
chat's model in the web UI) — not by a subagent, a command's own model, a `lembas run` or a
scheduled run. A session here starts on, in order: `--model`, the project's `model`, **the
model last used in this directory** (while the server still serves it), your global `model`,
the server's default. `lembas uninstall --purge` removes the file with the rest of the state.
- **Harness spec 3.9.0: schedules are Chat or Agentic** — an Agentic schedule runs on one linked
computer in one directory with the agent's tools, on the model the schedule names or else the
one last used in that directory; a scheduled run never changes what the directory remembers.
`/schedule` says each schedule's type, and `/schedule new` offers the two by name.
- **Harness spec 3.9.0: interactive-only models** (`harness/interactive.md`). A server may mark a
model `interactive_only` — one its provider sells for a person's own turns and forbids for
automated, batch and scheduled use. Your turns, and the subagents and teams your session
starts, run on it as on any model. What is not your turn does not: the session's **title**
and its **compaction** (asked for or automatic) are asked of the same model under another
provider when the server lists one, else of your global `model` or the server's default when
that is not interactive-only; with none, the title stays the one made from your first prompt,
automatic compaction is skipped and said once, and `/compact` is refused with the reason. A
subagent's own automatic compaction goes the same way.
**Scheduled work never runs on one**: a scheduled session opened on such a model, or a
scheduled turn of a session that has come to be on one, is refused before anything is sent
(`data.reason: "interactive_only"`), a scheduled run's subagent on one is not started, and a
schedule that follows the directory skips such a model. `lembas run` with no terminal at all
(a cron job, a pipeline) is refused on one too. `/model` says which models are for
interactive use only.
A model that cannot take the summary — too small a window, no tools — is not asked; the model
that is asked is named in a notice and its tokens are counted under it.
### Fixed
- **A schedule's run is never run in a terminal as your turn.** A continuing schedule whose
session was open and shared in a terminal had its prompt passed to that terminal like one
typed in the web UI: on the terminal's model, remembered as the directory's, and without the
*Accept scheduled work* check. It is refused now, saying the session is open in a terminal
(`data.reason: "terminal"`), and the next run goes ahead once it is closed there.
- **A continuing schedule's session keeps its model across a restart of the service.** Opened
from the store again it started like a new session — on the directory's model — instead of on
the model it had. The model is kept with the session.
- **A continuing schedule's run after the service restarted is offered `report_write` again.**
How a schedule opened its session was kept in memory only, so a session opened from the store
again — the service restarted, or the link dialled anew — had lost it: the next run's prompt
told the model to file a report with a tool it was not given. It is kept with the session now.
- **`.env.example` is read without asking after a broad allow, as before it.** With `read: allow`
made in a menu, by an "always" answer or in a project, the defaults' `*.env.*: ask` and
`*.env.example: allow` both counted as narrower rules and the stricter won, so the allow
*started* a question about every example file. A narrower rule that a later one narrows again
is now set aside (`harness/permission/rules.md` §2, spec 3.9.0); `.env` and `.env.local` still ask.
## [2.0.0-beta.11] — 2026-11-13
+129 -3
View File
@@ -22,7 +22,7 @@ page *Harness-parity* in LLeMbas CLI's wiki.
| `permission/defaults.json` | The rules every session starts from |
| `permission/modes.json` | The four modes — manual, edit, auto, plan — as what each does with each risk class |
| `models/schema.json` | Model metadata: context, output limit, efforts and the thinking switch, vision, tools, notes, capacity (`parallel`); `levels` — the effort levels a chat offers and what each sends |
| `loop.json` | How one prompt runs: the step backstop, budgets, wrap-up, nudges, parallel calls, capacity; `jobs` — background work, its marks and limits; `subagents` — the model refusals, what names a model, the setting's label; `team` — a team's size, names, marks, refusals and texts; `progress` — the phases' texts; `context` — result ids, stubs, the output cap, the compaction table, the environment lines, the session notes; `scheduled` (3.5.0) — scheduled work on a linked computer: the setting, the modes, the approval wait, the sentinel, the watch command's limits and the refusals; `phone` (3.6.0) — phone actions: the capability, each action's fields, what is required and checked, the wait and the texts; `display` (3.7.0) — a call's title keys, states and facts, the blocks, the cards' actions; `scheduled.notify` (3.8.0) — notify-when and its texts; `pages` (3.8.0) — the fence word, the frame's variables, the note and the projection |
| `loop.json` | How one prompt runs: the step backstop, budgets, wrap-up, nudges, parallel calls, capacity; `jobs` — background work, its marks and limits; `subagents` — the model refusals, what names a model, the setting's label; `team` — a team's size, names, marks, refusals and texts; `progress` — the phases' texts; `context` — result ids, stubs, the output cap, the compaction table, the environment lines, the session notes; `scheduled` (3.5.0) — scheduled work on a linked computer: the setting, the modes, the approval wait, the sentinel, the watch command's limits and the refusals; `phone` (3.6.0) — phone actions: the capability, each action's fields, what is required and checked, the wait and the texts; `display` (3.7.0) — a call's title keys, states and facts, the blocks, the cards' actions; `scheduled.notify` (3.8.0) — notify-when and its texts; `pages` (3.8.0) — the fence word, the frame's variables, the note and the projection; `interactive` (3.9.0) — interactive-only models: the field, the two sentences, what each background call does with nowhere to go |
| `filesystem.md` | The file system a session works in: paths, node kinds, the four access levels, errors, listings, search and indexing by tokens, stacked instruction files, skills, memory |
| `context.md` | Context hygiene: what happens to a tool result when it is inserted, and never afterwards; the prefix that stays still; reasoning sent back during its turn; no absolute paths in the prompt |
| `team.md` | Teams: a lead and the members it adds, the size setting, the room, who receives what, reports, a manager's refusals, capacity, stopping |
@@ -31,11 +31,12 @@ page *Harness-parity* in LLeMbas CLI's wiki.
| `progress.md` | Progress (3.4.0): the thirteen phases every client shows the same way, the data each carries, their texts, and where they are sent |
| `reports.md` | Reports (3.8.0): a schedule's run files a report with `report_write`, or leaves a history line; notify-when (`always`, `when`, `never`) and the instruction for each; what a run leaves; the retired `[SILENT]`; a run on a linked computer |
| `pages.md` | HTML pages in answers (3.8.0, experimental): the `html-view` fence, what the model is told, the note and the text projection for a reader that cannot show a page, when pages are offered, the session note, the frame |
| `permission/rules.md` | Which permission rule decides (3.8.0): the layers, the candidate, the floors a later-made rule gives way to, and what making a rule does |
| `permission/rules.md` | Which permission rule decides (3.8.0): the layers, the candidate, the floors a later-made rule gives way to (3.9.0: a narrower rule that a later one narrows again is set aside), and what making a rule does |
| `interactive.md` | Interactive-only models (3.9.0): the field, what counts as a person's own turn, scheduled work that never runs on one, and where a session's background calls (title, compaction) go instead |
| `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 |
| `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
@@ -78,6 +79,131 @@ 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
a field, a rule amended, no tool and no text for a model.
- **The model last used in a directory** (`acp.md`, section of that name; capability
`directory_model`; `conformance/last_model.json`). A new agent session in a directory starts on
the model last used in exactly that directory — from the terminal, the web, the desktop app or
a phone — instead of the instance's default. The memory is the device's and stays on it
(`models.json` in the CLI's state): the server keeps no record. The device writes it when a
person's turn begins and when the person changes the session's model; never for a subagent, a
turn the harness started, a command's own model, a one-shot run or a schedule's session. A
session of the device's own starts by: the model asked for, the project's setting, **the
directory's model** (while it is served), the global setting, the instance's default.
`_lembas/directories` carries it — `model` on each `Dir` and on the answered directory — and
takes `list: false` to describe one directory without listing it. The client's rule: a new
agent chat on (device, directory) with no model chosen starts on that model when the person
still has it, else as before; an older device sends no `model`, which reads as *as before*.
- **Schedules have two types, Chat and Agentic** (`acp.md` *Scheduled work on a linked
computer*): Agentic is a schedule with `runs_on` — one device, one directory, the agent's tools
there — and Chat one without; no new field. **The run's model** of an Agentic schedule: the
model the schedule names, else the model last used in its directory on that device (asked of
the device as the run starts) when the person still has it, else as before. **A scheduled run
never becomes the directory's model.** A device that is away was already specified (3.5.0: the
run waits, then is missed); the model is resolved only once it is linked.
- **Permission rules** (`permission/rules.md` §2 rule 2; six cases in `conformance/rules.json`):
among the narrower rules a later-made candidate gives way to, one that a later rule narrows
again is set aside. The defaults ask about `*.env.*` and then allow `*.env.example`; after a
broad `read: allow` both counted and the strictest won, so making the allow *started* asking
about `.env.example`. Now the example file is read without asking after it as before it.
LLeMbas: the same change in its rule lookup, if it has the same floor. The same holds for a
rule **written again** — the same permission and pattern, later: the later one counts (five
more cases pin it, a project's deny narrowed by its own allow, and the person's own answer
standing through all of it).
- **Interactive-only models** (`interactive.md`, `models/schema.json` `interactive_only`,
`loop.json` `interactive`, `conformance/interactive.json`; three more cases in
`last_model.json`). A model served through a connection its provider sells for a person's own
turns only says `interactive_only: true`. **Scheduled work never runs on one**: it is not
offered for a schedule and is refused when named; a run whose model is one fails with the
sentence, and a device refuses such a scheduled turn itself (`data.reason:
"interactive_only"`), its subagents included; so does a one-shot `lembas run` with no
terminal at all. **Background calls go elsewhere**: a title or a compaction for a session on
such a model is asked of its twin (the same model under another provider), else of a default
that is not interactive-only, else the title and automatic compaction are skipped and a
compaction the person asked for is refused in words. What a person starts — their turns, the
subagents and teams of their session — stays on the model. A model that cannot take a summary
(its window too small, no tools) is nowhere to go; a rerouted call is counted under the model
asked, and the client names it. In a schedule's session, what runs with no person's turn — a
turn a job wakes, a subagent started after the run — is still scheduled work.
- **A schedule's session keeps its model, and is not run in a terminal** (`acp.md` *The run's
model*, *When the device is away, or refuses*): the device keeps the model with the session,
so one opened from its store again is on the model it had; and a scheduled prompt for a
session open in a terminal is refused (`data.reason: "terminal"`, `scheduled.texts.terminal`)
rather than run there as a person's turn.
## 3.8.1
A text. `prompts/blocks/html-pages.md` (`pages.md` §2) now says which of the two ways of
+1 -1
View File
@@ -1 +1 @@
3.8.1
3.10.0
+367 -19
View File
@@ -68,6 +68,8 @@ change to the protocol is a change here first, then in both projects.
| `agents` | spec 3.4.0: the session's Subagents setting `{ min, max }` is read from `_meta.lembas.agents` on `session/new`, `session/prompt` and `_lembas/configure` (*Subagents in an agent chat*, below) |
| `tree` | spec 3.4.0 (`subagents.md` §5–§13): the `team` event; `_lembas/team`, `_lembas/team/transcript`, `_lembas/team/findings`, `_lembas/team/stop`; `subagent` on `session/request_permission` |
| `scheduled` | spec 3.5.0 (*Scheduled work on a linked computer*, below): `scheduled` in `_meta.lembas` of `session/new` and `session/prompt` read, and the run's outcome in the prompt's answer; `scheduled` on `session/request_permission`; `_lembas/monitor`; `limits.scheduled` in `_lembas/hello` and `initialize`. Listed by every build that has it, whatever the setting says: whether this device *accepts* scheduled work is `limits.scheduled` |
| `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
@@ -133,6 +135,9 @@ device never answers on a model of its own instead, and never falls back on its
is true for every session the client opened, and a client has nothing to say about a device having
"answered on its own model": that notice is gone. A session a terminal shares (`announce`) keeps the
terminal's model, and its `instance` says which it is.
A session opened with neither `lembas_model` nor `model` starts as a session of the device's own
does (*The model last used in a directory*: the project's setting, else the model last used in
`cwd`, else the device's global setting, else the instance's default).
The id is the device's store id and lasts: a session the client names later that is not in memory
is opened from the store under the same rules (capability `sessions`). With capability `commands`,
an `available_commands_update` follows the answer.
@@ -192,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) |
@@ -210,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)
@@ -334,6 +374,20 @@ server. The server decides *when*; the device decides *whether*, and *how far*
chat has still holds, and the ones below are added. Numbers and texts: `loop.json` `scheduled`.
Conformance areas `scheduled`, `silent`, `monitor`.
### Two types of schedule: Chat and Agentic (spec 3.9.0)
Every client presents a schedule as one of two types, and the type is what `runs_on` says —
there is no field of its own:
| Type | `runs_on` | A run is |
|---|---|---|
| **Chat** | `null` | a turn on the server, with the server's tools, as a chat's |
| **Agentic** | `{ device, cwd, mode, approval_wait_minutes }` | an agent turn on **that device**, in **that directory**, with the agent's tools there (the shell, the files), under the device's limits and the schedule's mode |
An Agentic schedule is tied to one device and one directory; it has no meaning without them, and
a client does not offer the type while no device of the person's accepts scheduled work
(`limits.scheduled`). Everything below is about the Agentic type.
### The device's setting: Accept scheduled work
- **`remote.scheduled`** in the device's global config, **off by default**; shown as **Accept
@@ -374,6 +428,35 @@ session again on its next run; a fresh run opens a new one. The prompt's text is
for a scheduled run — the instruction, the run's time, and for a schedule that notifies only when
it matters the `[SILENT]` hint — composed exactly as for a run on the server; the device adds nothing.
**The run's model** (spec 3.9.0; `conformance/last_model.json`, `kind: client`). The client
resolves it for every run that opens a session, when the run starts, and sends it as
`lembas_model`:
1. **the model the schedule names**, when it names one;
2. else **the model last used in the schedule's directory on that device** — asked of the device
then (`_lembas/directories` with `path: cwd, list: false`, capability `directory_model`) —
when the person still has it;
3. else as before 3.9.0: the default a schedule without a model runs on.
Never an interactive-only model (`interactive.md` §2): a schedule cannot name one, the
directory's does not count when it is one, and a run left with one fails with the sentence —
which the device says too, should such a turn reach it (`data.reason: "interactive_only"`).
So an Agentic schedule that names no model follows the directory: change the model you work with
there, and the next run uses it. A schedule that continues one conversation keeps its session's
model from run to run; the client changes it (`_lembas/configure`) only when the schedule names a
model and the session is on another. **The device keeps that model with the session**: a
schedule's session opened from its store again — the service restarted, the session opened in a
terminal — is on the model it had, not on what a new session in the directory would start on
(the one exception to *How a session of the device's own starts*). The device is linked whenever this is asked — a run whose
device is away is `waiting` before anything is resolved (*When the device is away*).
**A scheduled run never becomes the directory's model.** The device records nothing for a session
a schedule opened — not the run's turn, not a `_lembas/configure` on it, not a turn the person
writes into the run's chat afterwards, in the web or in a terminal that opened the session
(`kind: record`). Otherwise a schedule that names a small
model for a nightly check would decide what the person's next chat in that folder starts on.
**The mode** (`scheduled.mode`; `_meta.mode` is ignored for a scheduled session): `manual`, `edit`
or `auto`, and **`edit` when absent** — so a run is never wider than Edit unless the person picked
Auto on that schedule. `plan` is refused (`scheduled.texts.plan`, `data: { reason: "plan" }`):
@@ -396,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`:
@@ -449,8 +561,15 @@ client's to decide from this answer (`reports.md` §4). A device without the cap
`_lembas/session/status` and the turn id, as for any agent chat.
- **Refused** (`-32602` from a scheduled `session/new`, `session/prompt` or `_lembas/monitor`): the
run **fails** with the device's message, said in the run's history and in the failure
notification; `data.reason` (`scheduled_off`, `folder`, `plan`, `permission`) lets the client say
what to change. Not retried.
notification; `data.reason` (`scheduled_off`, `folder`, `plan`, `permission`, and from spec 3.9.0
`interactive_only` — the session's model is one, `interactive.md` §2 — and `terminal`) lets the
client say what to change. Not retried.
- **Open in a terminal** (spec 3.9.0): a scheduled `session/prompt` for a session that is open
and shared in a terminal on the device is refused — `-32602`, `scheduled.texts.terminal`,
`data: { reason: "terminal" }` — after it is judged as any scheduled request (so `scheduled_off`
comes first). A terminal runs what a person types, on the terminal's model and rules; a
schedule's run is never passed to it as a person's turn. The run fails saying so, and the next
one goes ahead once the session is closed there.
### Monitor mode: a command watched on the device
@@ -476,6 +595,173 @@ tool reads them — followed by a newline and the exit status as decimal digits
the device hashes the output as it streams, however long). Nothing is normalised: a watch command
that prints a time changes every time, and should not.
## The model last used in a directory (spec 3.9.0)
**A new agent session in a directory starts on the model last used in that directory**, wherever
it is started from — the terminal, the web, the desktop app, a phone — instead of the instance's
default. What is remembered is **the device's, and stays on the device**: the server keeps no
record of it, so removing a device, or LLeMbas from it, leaves nothing of it behind on the
server. Capability `directory_model`; conformance area `last_model`.
### What the device remembers
- **One model per directory**: the ref (`provider/model`, the served id) of the model last used in
a session whose working directory is exactly that directory. The key is the directory's absolute
path as the file system has it — symlinks followed, no trailing slash — compared exactly:
**a directory does not inherit its parent's model, nor a parent its child's.**
- **Where**: in the device's own state (`models.json` in the CLI's state directory, written
atomically, mode 0600; local mode keeps it in the local root). Never in the project, never in
a session, never on the server. `lembas uninstall --purge` removes it with the rest of the
state; a plain uninstall keeps it with the settings and sessions, as it keeps those. The file
holds at most 500 directories — the ones used longest ago go first (a directory's time is
refreshed as it is used, to within an hour) — and directories that no longer exist are dropped
now and then, away from any turn: one that cannot be looked at (an unreachable mount) is kept.
- **When it is written** (`conformance/last_model.json`, `kind: record`) — for the main agent of a
session, in a terminal, on the link (`lembas service`) and on `serve --stdio` alike:
1. **a turn a person started begins**: the model the turn runs on is the directory's;
2. **the person changes the session's model** between turns or during one (`/model`, a setting,
`_lembas/configure` with a `model`): the new model is the directory's at once.
And **not**: a turn the harness started (`machine`: a job's note, a subagent's message), nor a
change of model made inside one (a model's own settings call there is nobody's choice); a
subagent's model; a command's own `model`, which holds for that prompt only; a one-shot
`lembas run`; and **anything in a session a schedule opened for its run** — a scheduled run
uses the directory's model (below) and never changes it, whichever model the schedule names.
### How a session of the device's own starts
The first of these that names a model (`kind: start`):
| # | Source | |
|---|---|---|
| 1 | the model asked for at the start | `--model`; `model` / `lembas_model` in `session/new` |
| 2 | the project's setting | `model` in a trusted project's configuration |
| 3 | **the model last used in this directory** | only while the login still serves it; otherwise skipped, silently, and kept |
| 4 | the device's global setting | `model` in the global configuration — what a login writes as its default |
| 5 | the instance's default | |
A project's setting comes first because it is written down on purpose and travels with the
project; the directory's memory comes before the global setting because the global setting is the
default for every directory that has none. A session opened from the store again starts by the
same order — except a schedule's, which keeps the model it had (*The run's model*); so does a
one-shot `lembas run`, which records nothing.
### What the device tells the client
`_lembas/directories` (below) says the remembered model of each directory it describes: `model`
on a `Dir`, and on the answered directory itself — present only where one is remembered **and**
the directory is `accepted`. It is the ref as recorded; the device does not vouch that the
instance still serves it. To ask about one directory without listing it, `list: false`.
A device without the capability (before 3.9.0) sends no `model` and ignores `list`: the client
then finds no `model` in the answer and starts as it did before.
### The client's rule
**A new agent chat on (device, directory) for which the person chose no model starts on the
directory's `model`, when the person still has that model** (it is one the instance serves to
them now); otherwise as before 3.9.0 — the person's or the instance's default. The same holds
for a schedule's run on a device (*Scheduled work*, *The run's model*).
- The client asks when the chat is made (`_lembas/directories` with the chat's `path` and
`list: false`; a directory dialog that has just listed the folder already holds the answer) and
may show the model as the choice it starts from. A device that is not linked then, or has no
capability, or answers without `model`: as before.
- A model the person chose is the chat's whatever the directory remembers — and, once a turn runs
on it, it is what the directory remembers next.
- **The client does not keep it**: the `model` of a directory is used for the session being
opened and stored nowhere but as that chat's own model. The device is asked again next time.
(`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.
@@ -495,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
@@ -508,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` |
@@ -540,10 +827,39 @@ of the output as it streams and keeps at most `scheduled.monitor.output_max_byte
### `_lembas/directories` — client → agent → result
Params `{ path?: string }`. Without a path: `{ path: "", places: Dir[] }`, the remote roots and every
trusted directory inside them. With one (absolute, inside the roots): `{ …Dir, parent, entries: Dir[], error? }`.
`Dir = { path, name, accepted: boolean, reason? }` — whether `session/new` would accept it.
Only on the link (an error on `serve --stdio`).
Params `{ path?: string, list?: boolean }`. Only on the link (an error on `serve --stdio`).
`Dir = { path, name, accepted: boolean, reason?, model? }` — `accepted`: whether `session/new`
would accept it (`reason`: why not); **`model`** (capability `directory_model`, spec 3.9.0): the
ref of the model last used in exactly that directory, absent where none is remembered or the
directory is not accepted (*The model last used in a directory*).
- **Without a path**: `{ path: "", places: Dir[] }`, the remote roots and every trusted directory
inside them. (`list` is ignored.)
- **With one** (absolute, inside the roots): `{ …Dir, parent, entries: Dir[], error? }` — the
directory itself, its parent (`""` at a root), and its subdirectories (hidden ones and
`node_modules` left out, at most 300, by name).
- **With one and `list: false`** (capability `directory_model`): `{ …Dir, parent }` — the directory
alone; nothing is listed, and `entries` is absent. This is how a client asks for one
directory's `model`.
```json
→ { "path": "/home/user" }
← { "path": "/home/user", "name": "user", "accepted": false, "reason": "…", "parent": "",
"entries": [
{ "path": "/home/user/notes", "name": "notes", "accepted": true },
{ "path": "/home/user/project", "name": "project", "accepted": true, "model": "open/flash" } ] }
→ { "path": "/home/user/project", "list": false }
← { "path": "/home/user/project", "name": "project", "accepted": true,
"model": "open/flash", "parent": "/home/user" }
→ { "path": "/home/user/notes", "list": false }
← { "path": "/home/user/notes", "name": "notes", "accepted": true, "parent": "/home/user" }
```
A device before 3.9.0 ignores `list` and answers the second request with `entries` and without
`model`; a client reads `model` only, and an absent one means *start as before*.
### `_lembas/configure` — client → agent → result
@@ -554,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
@@ -570,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`)
@@ -815,7 +1160,9 @@ Besides `/v1/models`, the chat completions, `/api/v1/instance` and `/mcp`:
model is the library's: logging in (or in again) sets config.yaml's `embedding:` to the first one
as `<connection>/<served id>` when no `embedding:` is set, and never replaces one that is;
`embedding: <served id>` also finds it. Voice uses the instance's own speech endpoints, not these
entries. Any other kind is ignored.
entries. Any other kind is ignored. An entry may carry **`interactive_only: true`** (spec
3.9.0, `interactive.md`; sent only when true): a model for a person's own turns only — the
device sends it no scheduled work and sends a session's background calls elsewhere.
- **`GET /api/v1/instance`** (the `models` scope) →
`{ service, version, name, connection, account: { email, name }, scope, default_model, services }`.
**`scope`** is what the token presented may do, space-separated, as its login granted it
@@ -882,7 +1229,8 @@ Besides `/v1/models`, the chat completions, `/api/v1/instance` and `/mcp`:
`instruction`, `rule`, `description`, `next_runs`, `timezone`. A run's `status` may also be
**`unchanged`** (monitor mode: the watch saw nothing new; no model ran), and `waiting_for` may be
**`device`**. A schedule that runs on a linked computer has
**`runs_on: { device, device_name, cwd, mode, approval_wait_minutes }`** (else `null`); one that
**`runs_on: { device, device_name, cwd, mode, approval_wait_minutes }`** (else `null`) — the
**Agentic** type, `null` being **Chat** (spec 3.9.0, *Two types of schedule*); one that
watches has **`watch: { kind: "url", url } | { kind: "command", command, timeout_s }`** (else
`null`). Creating one with the device's token, `runs_on.device: "this"` names the calling device.
A server without these answers 401 or 403 to the device's token, and the CLI says the server is
+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"
}
}
]
}
+414
View File
@@ -0,0 +1,414 @@
{
"about": "Spec 3.9.0 (interactive.md): interactive-only models. `models`: the served models in the list's order, each `{id, interactive_only?}` (absent: false). `kind: twin` — `model` → the id of the same model on a connection that is not interactive-only (another id with the same part after its first `/`, the first in order), or null. `kind: background` — where a background call that would use `model` goes. `call`: `title`, `compaction` (the person asked) or `auto_compaction`; `defaults`: the defaults to try after the twin, in order (a device: its global `model` setting, then the instance's default; the server: the instance's default) — one that is not listed or is interactive-only is passed over. `unfit`: models that cannot take the call (for a summary: a context window below what must be sent, or no tools for a conversation with tool calls) — passed over like models that are not listed. → `{model}` (the model asked: itself, the twin or a default), `{skip: true}`, or `{refused}` with loop.json interactive.texts.compact. `kind: scheduled` — scheduled work on `model` (a run's session, its subagent, a one-shot run with nobody at it): → `{run: true}`, or `{refused}` with interactive.texts.scheduled, `{{model}}` the id. The server's twin also has to be one the person may use in the chat's data group, which no case here turns on. CLI: src/provider/interactive.ts; LLeMbas: services/interactive.py.",
"cases": [
{
"about": "The plan's pay-as-you-go twin: the same model under another provider.",
"kind": "twin",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"expect": "payg/coder"
},
{
"about": "No other provider serves it.",
"kind": "twin",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "open/flash"
}
],
"expect": null
},
{
"about": "A twin that is itself interactive-only is none.",
"kind": "twin",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "other-plan/coder",
"interactive_only": true
}
],
"expect": null
},
{
"about": "The part after the first slash is compared whole: a longer name is another model.",
"kind": "twin",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder-plus"
},
{
"id": "payg/org/coder"
}
],
"expect": null
},
{
"about": "The first in the list's order.",
"kind": "twin",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "b/coder"
},
{
"id": "a/coder"
}
],
"expect": "b/coder"
},
{
"about": "A model that is not interactive-only is asked itself, as before.",
"kind": "background",
"call": "title",
"model": "open/flash",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"defaults": [
"payg/coder"
],
"expect": {
"model": "open/flash"
}
},
{
"about": "A title for a session on a plan's model goes to the twin.",
"kind": "background",
"call": "title",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"defaults": [
"open/flash"
],
"expect": {
"model": "payg/coder"
}
},
{
"about": "No twin: the default that is not interactive-only.",
"kind": "background",
"call": "compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "open/flash"
}
],
"defaults": [
"open/flash"
],
"expect": {
"model": "open/flash"
}
},
{
"about": "The first default is interactive-only too, the second is not.",
"kind": "background",
"call": "auto_compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "plan/max",
"interactive_only": true
},
{
"id": "open/flash"
}
],
"defaults": [
"plan/max",
"open/flash"
],
"expect": {
"model": "open/flash"
}
},
{
"about": "A default the list does not have is passed over.",
"kind": "background",
"call": "title",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "plan/max",
"interactive_only": true
}
],
"defaults": [
"gone/model"
],
"expect": {
"skip": true
}
},
{
"about": "Nowhere to go: a title is skipped.",
"kind": "background",
"call": "title",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "plan/max",
"interactive_only": true
}
],
"defaults": [
"plan/max"
],
"expect": {
"skip": true
}
},
{
"about": "Nowhere to go: compaction the person asked for is refused in words.",
"kind": "background",
"call": "compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "plan/max",
"interactive_only": true
}
],
"defaults": [
"plan/coder"
],
"expect": {
"refused": "This chat's model is on a connection for interactive use only, and compacting is background work its provider's terms do not allow. It needs the same model on a pay-as-you-go connection, or a default model that is not interactive-only."
}
},
{
"about": "Nowhere to go: automatic compaction is skipped and the turn goes on.",
"kind": "background",
"call": "auto_compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "plan/max",
"interactive_only": true
}
],
"defaults": [],
"expect": {
"skip": true
}
},
{
"about": "The twin's window is below what must be sent: the default that fits.",
"kind": "background",
"call": "compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"defaults": [
"open/flash"
],
"unfit": [
"payg/coder"
],
"expect": {
"model": "open/flash"
}
},
{
"about": "Nothing fits: a compaction the person asked for is refused, as with nowhere to go.",
"kind": "background",
"call": "compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"defaults": [
"open/flash"
],
"unfit": [
"payg/coder",
"open/flash"
],
"expect": {
"refused": "This chat's model is on a connection for interactive use only, and compacting is background work its provider's terms do not allow. It needs the same model on a pay-as-you-go connection, or a default model that is not interactive-only."
}
},
{
"about": "Nothing fits: automatic compaction is skipped.",
"kind": "background",
"call": "auto_compaction",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"defaults": [
"open/flash"
],
"unfit": [
"payg/coder",
"open/flash"
],
"expect": {
"skip": true
}
},
{
"about": "A scheduled run on a pay-as-you-go model.",
"kind": "scheduled",
"model": "payg/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"expect": {
"run": true
}
},
{
"about": "A scheduled run whose model is interactive-only fails with the sentence — never quietly on its twin.",
"kind": "scheduled",
"model": "plan/coder",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"expect": {
"refused": "plan/coder is on a connection for interactive use only: its provider's terms do not allow scheduled or background work. Choose a model on a pay-as-you-go connection."
}
},
{
"about": "A model the list does not have is not known to be one.",
"kind": "scheduled",
"model": "new/model",
"models": [
{
"id": "plan/coder",
"interactive_only": true
},
{
"id": "payg/coder"
},
{
"id": "open/flash"
}
],
"expect": {
"run": true
}
}
]
}
+378
View File
@@ -0,0 +1,378 @@
{
"about": "Spec 3.9.0 (acp.md *The model last used in a directory*; *Scheduled work*, *The run's model*). Three kinds. `kind: start` — the device: which model a session of its own starts on. `asked`: the model asked for at the start (--model; model / lembas_model in session/new); `project`: `model` in a trusted project's configuration; `directory`: the model remembered for exactly this directory; `global`: `model` in the device's global configuration; `served`: the ids the login serves now; `default`: the instance's default. → `{model, from}`, `from` one of `asked`, `project`, `directory`, `global`, `default`. Only the directory's model is checked against `served` and skipped when it is not there; the others are taken as written (a model nobody serves is that source's own error, as before). `kind: record` — the device: whether something makes the session's model the directory's. `session`: `terminal`, `link` (a session the client opened, or a terminal's shared one), `stdio`, `run` (one-shot lembas run) or `scheduled` (a session a schedule opened for its run); `agent`: `main` or `subagent`; `what`: `turn` (a turn begins; `machine: true` when the harness started it), `change` (the session's model is changed: /model, a setting, _lembas/configure; `machine: true` when it happens inside a turn the harness started) or `command` (a command's own model, for its prompt). → true or false. `kind: client` — the client (LLeMbas): the model a new agent chat on a device and directory, or a schedule's run there, starts on. `named`: the model the person chose for the chat, or the schedule names (absent: none); `directory`: `model` of the directory in the device's _lembas/directories answer (absent: none, an older device, or a device not asked); `has`: the models the person has now; `default`: what a chat or schedule without a model started on before 3.9.0. `scheduled: true`: it is a schedule's run, for which the directory's model counts only when it is not one of `interactive_only` (interactive.md §2; a person's chat may start on such a model). → `{model, from}`, `from` one of `named`, `directory`, `default`. CLI: src/session/lastmodel.ts.",
"cases": [
{
"about": "Nothing but the instance's default.",
"kind": "start",
"served": [
"open/flash",
"open/large"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "default"
}
},
{
"about": "The global setting — what a login writes — over the instance's default.",
"kind": "start",
"global": "open/large",
"served": [
"open/flash",
"open/large"
],
"default": "open/flash",
"expect": {
"model": "open/large",
"from": "global"
}
},
{
"about": "The model last used in this directory over the global setting.",
"kind": "start",
"directory": "other/coder",
"global": "open/large",
"served": [
"open/flash",
"open/large",
"other/coder"
],
"default": "open/flash",
"expect": {
"model": "other/coder",
"from": "directory"
}
},
{
"about": "The project's setting over the directory's memory: it is written down on purpose.",
"kind": "start",
"project": "open/large",
"directory": "other/coder",
"global": "open/flash",
"served": [
"open/flash",
"open/large",
"other/coder"
],
"default": "open/flash",
"expect": {
"model": "open/large",
"from": "project"
}
},
{
"about": "The model asked for over everything.",
"kind": "start",
"asked": "open/flash",
"project": "open/large",
"directory": "other/coder",
"global": "open/large",
"served": [
"open/flash",
"open/large",
"other/coder"
],
"default": "open/large",
"expect": {
"model": "open/flash",
"from": "asked"
}
},
{
"about": "The remembered model is no longer served: skipped, the global setting decides.",
"kind": "start",
"directory": "other/coder",
"global": "open/large",
"served": [
"open/flash",
"open/large"
],
"default": "open/flash",
"expect": {
"model": "open/large",
"from": "global"
}
},
{
"about": "…and with no global setting, the instance's default.",
"kind": "start",
"directory": "other/coder",
"served": [
"open/flash",
"open/large"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "default"
}
},
{
"about": "A global setting is not checked against the list here: it is taken as written.",
"kind": "start",
"global": "old/model",
"served": [
"open/flash"
],
"default": "open/flash",
"expect": {
"model": "old/model",
"from": "global"
}
},
{
"about": "A person's turn in a terminal.",
"kind": "record",
"session": "terminal",
"agent": "main",
"what": "turn",
"expect": true
},
{
"about": "A person's turn in a session the client opened.",
"kind": "record",
"session": "link",
"agent": "main",
"what": "turn",
"expect": true
},
{
"about": "An editor's session.",
"kind": "record",
"session": "stdio",
"agent": "main",
"what": "turn",
"expect": true
},
{
"about": "The person switches model.",
"kind": "record",
"session": "terminal",
"agent": "main",
"what": "change",
"expect": true
},
{
"about": "The chat's model is changed from the client between turns.",
"kind": "record",
"session": "link",
"agent": "main",
"what": "change",
"expect": true
},
{
"about": "A turn the harness started — a finished job's note — is nobody's choice.",
"kind": "record",
"session": "terminal",
"agent": "main",
"what": "turn",
"machine": true,
"expect": false
},
{
"about": "A subagent's model is not the directory's.",
"kind": "record",
"session": "terminal",
"agent": "subagent",
"what": "turn",
"expect": false
},
{
"about": "A command's own model holds for its prompt only.",
"kind": "record",
"session": "terminal",
"agent": "main",
"what": "command",
"expect": false
},
{
"about": "A one-shot run from a script.",
"kind": "record",
"session": "run",
"agent": "main",
"what": "turn",
"expect": false
},
{
"about": "A scheduled run never becomes the directory's model.",
"kind": "record",
"session": "scheduled",
"agent": "main",
"what": "turn",
"expect": false
},
{
"about": "…nor does a model change on a schedule's session.",
"kind": "record",
"session": "scheduled",
"agent": "main",
"what": "change",
"expect": false
},
{
"about": "A change of model made inside a turn the harness started — a model's own settings call there — is nobody's choice.",
"kind": "record",
"session": "terminal",
"agent": "main",
"what": "change",
"machine": true,
"expect": false
},
{
"about": "A person's turn in a session a schedule opened, wherever it is open: still the schedule's session.",
"kind": "record",
"session": "scheduled",
"agent": "main",
"what": "turn",
"expect": false
},
{
"about": "A new agent chat, no model chosen, the directory remembers one the person has.",
"kind": "client",
"directory": "other/coder",
"has": [
"open/flash",
"other/coder"
],
"default": "open/flash",
"expect": {
"model": "other/coder",
"from": "directory"
}
},
{
"about": "The person chose a model: theirs, whatever the directory remembers.",
"kind": "client",
"named": "open/flash",
"directory": "other/coder",
"has": [
"open/flash",
"other/coder"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "named"
}
},
{
"about": "The person no longer has the remembered model: as before.",
"kind": "client",
"directory": "other/coder",
"has": [
"open/flash"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "default"
}
},
{
"about": "An older device, or one that remembers nothing there: as before.",
"kind": "client",
"has": [
"open/flash",
"other/coder"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "default"
}
},
{
"about": "An Agentic schedule that names no model follows the directory.",
"kind": "client",
"directory": "open/large",
"has": [
"open/flash",
"open/large"
],
"default": "open/flash",
"expect": {
"model": "open/large",
"from": "directory"
}
},
{
"about": "A schedule that names one runs on it.",
"kind": "client",
"named": "open/flash",
"directory": "open/large",
"has": [
"open/flash",
"open/large"
],
"default": "open/large",
"expect": {
"model": "open/flash",
"from": "named"
}
},
{
"about": "The directory's model is compared exactly: another spelling is not the model.",
"kind": "client",
"directory": "Other/Coder",
"has": [
"open/flash",
"other/coder"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "default"
}
},
{
"about": "A schedule's run: an interactive-only model remembered for the directory does not count.",
"kind": "client",
"scheduled": true,
"directory": "plan/coder",
"has": [
"plan/coder",
"open/flash"
],
"interactive_only": [
"plan/coder"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "default"
}
},
{
"about": "…while a person's new chat there starts on it: that is interactive.",
"kind": "client",
"directory": "plan/coder",
"has": [
"plan/coder",
"open/flash"
],
"interactive_only": [
"plan/coder"
],
"default": "open/flash",
"expect": {
"model": "plan/coder",
"from": "directory"
}
},
{
"about": "The device, for a scheduled session opened with no model: the same skip (`served` here is what the login serves that scheduled work may use).",
"kind": "start",
"directory": "plan/coder",
"global": "open/flash",
"served": [
"open/flash"
],
"default": "open/flash",
"expect": {
"model": "open/flash",
"from": "global"
}
}
]
}
+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"
}
}
]
}
+225 -1
View File
@@ -1,5 +1,5 @@
{
"about": "Which permission rule decides (permission/rules.md, spec 3.8.0). The rules by layer: `defaults` true — permission/defaults.json as the `default` layer; `user` and `project` — a configuration's permission map (a key's value an action, or a map of pattern → action, read in the order written); `made` — rules made during the session, in order, each `by` an `always` answer or a `menu`. With `request` (`permission`, `pattern`: what one call asks for): expect the action that decides, or null where no rule matches. With `set` (a rule a person makes now, by a menu): expect `result` — `unchanged` (the action is already in force), `refused` with the rule in its way as `by`, or `made` with `still`, the stricter narrower rules that still apply, in the order read. The same answers for a rule typed into a file as for one a menu wrote. LLeMbas: security/permission rules; CLI: src/permission/evaluate.ts.",
"about": "Which permission rule decides (permission/rules.md, spec 3.8.0; rule 2's set-aside 3.9.0). The rules by layer: `defaults` true — permission/defaults.json as the `default` layer; `user` and `project` — a configuration's permission map (a key's value an action, or a map of pattern → action, read in the order written); `made` — rules made during the session, in order, each `by` an `always` answer or a `menu`. With `request` (`permission`, `pattern`: what one call asks for): expect the action that decides, or null where no rule matches. With `set` (a rule a person makes now, by a menu): expect `result` — `unchanged` (the action is already in force), `refused` with the rule in its way as `by`, or `made` with `still`, the stricter narrower rules that still apply, in the order read. The same answers for a rule typed into a file as for one a menu wrote. LLeMbas: security/permission rules; CLI: src/permission/evaluate.ts.",
"cases": [
{
"about": "The defaults alone: a file is read, a .env asks.",
@@ -322,6 +322,230 @@
},
"expect": null
},
{
"about": "Spec 3.9.0: a narrower rule that a later one narrows again does not count. The defaults ask about *.env.* and then allow *.env.example; after a broad allow made in a menu the example file is still read without asking.",
"defaults": true,
"made": [
{
"permission": "read",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": ".env.example"
},
"expect": "allow"
},
{
"about": "The same under a project's read: allow, in a subdirectory.",
"defaults": true,
"project": {
"read": "allow"
},
"request": {
"permission": "read",
"pattern": "config/.env.example"
},
"expect": "allow"
},
{
"about": "The same under the broadest rule, made by an \"always\" answer.",
"defaults": true,
"made": [
{
"permission": "*",
"pattern": "*",
"action": "allow",
"by": "always"
}
],
"request": {
"permission": "read",
"pattern": ".env.example"
},
"expect": "allow"
},
{
"about": "…and the sibling the defaults do not except still asks: only *.env.* speaks of it.",
"defaults": true,
"made": [
{
"permission": "read",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": ".env.production"
},
"expect": "ask"
},
{
"about": "Order matters as in a file: the narrow allow is read before the ask that takes it in, so nothing is set aside and the ask decides — as it does without the broad rule.",
"project": {
"read": {
"notes.private.md": "allow",
"*.private.*": "ask"
}
},
"made": [
{
"permission": "read",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": "notes.private.md"
},
"expect": "ask"
},
{
"about": "A later, narrower rule that is stricter is the one that counts just the same.",
"project": {
"bash": {
"git *": "ask",
"git push --force *": "deny"
}
},
"made": [
{
"permission": "bash",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "bash",
"pattern": "git push --force origin main"
},
"expect": "deny"
},
{
"about": "Spec 3.9.0: the same rule written again. A project allows *.env, which the defaults ask about; a broad allow made later changes nothing for it — the later of the two identical rules is the one that counts.",
"defaults": true,
"project": {
"read": {
"*.env": "allow"
}
},
"made": [
{
"permission": "read",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": ".env"
},
"expect": "allow"
},
{
"about": "…and written again stricter — the person allows *.key, the project denies it — the later one counts under the broad allow, as it decides without it.",
"user": {
"read": {
"*.key": "allow"
}
},
"project": {
"read": {
"*.key": "deny"
}
},
"made": [
{
"permission": "read",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "read",
"pattern": "id.key"
},
"expect": "deny"
},
{
"about": "A project's deny narrowed by its own later allow: the exception it wrote holds under a broad allow as without one.",
"project": {
"bash": {
"rm *": "deny",
"rm -i *": "allow"
}
},
"made": [
{
"permission": "bash",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "bash",
"pattern": "rm -i notes.txt"
},
"expect": "allow"
},
{
"about": "…and what the exception does not take in is still denied.",
"project": {
"bash": {
"rm *": "deny",
"rm -i *": "allow"
}
},
"made": [
{
"permission": "bash",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "bash",
"pattern": "rm notes.txt"
},
"expect": "deny"
},
{
"about": "The person's own ask against a project's narrower allow and a broad allow made later: the set-aside never touches rule 3 — it still asks.",
"defaults": true,
"user": {
"bash": "ask"
},
"project": {
"bash": {
"make *": "allow"
}
},
"made": [
{
"permission": "bash",
"pattern": "*",
"action": "allow",
"by": "menu"
}
],
"request": {
"permission": "bash",
"pattern": "make all"
},
"expect": "ask"
},
{
"about": "Choosing the action already in force changes nothing.",
"defaults": true,
+99
View File
@@ -0,0 +1,99 @@
# Interactive-only models
Spec 3.9.0. **Some models may be used for a person's own turns and for nothing else.** A
provider that sells a subscription for interactive use forbids automated services, batch scripts
and scheduled background jobs on it, and may suspend a key used for those. Whether a model is
one is the server's word — a property of the connection it is served through — and it says so
on the model: **`interactive_only: true`** (`models/schema.json`; in `/v1/models` and the model
objects of `/api/v2`, sent only when true). Nothing matches a name.
The server enforces this for what it runs itself. A device talks to the server's `/v1`, and the
server cannot tell what a request there is *for* — so the rules below are every client's, and a
device's most of all. The field and the texts: `loop.json` `interactive`; the cases:
`conformance/interactive.json`.
## 1. What is interactive, and what is not
**Interactive** — and so allowed on such a model — is a turn a person started and everything
that turn starts: the reply, the tool calls inside it, a subagent or a team the person's session
starts (on the session's model, or one the person named), a turn woken by one of their notes
(`machine`), and a command the person runs that asks a model for an answer shown to them at
once (the CLI's commit-message draft).
**Not interactive**, in two kinds:
- **Scheduled work**: a schedule's run — on the server, or as an agent turn on a linked
computer — with its subagents and its fallbacks, which are the same run. And a **one-shot run
with nobody at it**: the CLI's `lembas run` when none of its standard input, output and error
is a terminal (a cron job, a pipeline), which is the batch script the terms name.
- **Background calls**: what a client asks a model on a session's behalf that is not the answer
to the person's turn — **naming the session** (its title) and **compacting it** (the summary,
asked for by the person or by the harness when the window fills). A **subagent's own
automatic compaction** is one too: the subagent is the person's, the summary of its
conversation is not their turn.
## 2. Scheduled work never runs on one
- **A schedule may not be given one.** Wherever a schedule's model is chosen, an
interactive-only model is not offered, and one typed or sent is refused with
`interactive.texts.scheduled` (`{{model}}` the model as the person knows it).
- **A run whose model is one fails**, with that sentence, before anything is sent to the model —
never quietly on another model. (A model can become interactive-only after the schedule was
made.) For an Agentic schedule that names no model, the directory's model counts only when it
is not interactive-only (`conformance/last_model.json`, `kind: client` with `scheduled`).
- **On a linked computer** the device checks again, because it is the one that sends: a
scheduled `session/new` or `session/prompt` whose session's model is interactive-only is
refused — `-32602`, the sentence, `data: { reason: "interactive_only" }` — and the run fails
as any refused run does (`acp.md` *When the device is away, or refuses*). A scheduled
session opened with no model skips an interactive-only directory's model as it skips one no
longer served. During a scheduled turn the session's model cannot be changed to one, and a
subagent that would run on one is not started: the tool call answers the sentence, and the
run goes on without it.
- A one-shot run with nobody at it ends at once with the sentence, having sent nothing.
A person writing into a run's chat afterwards is a person: that turn is interactive. What the
run left working is still the run: in a session a schedule opened, a turn woken by one of its
jobs, and a subagent started when no person's turn is running, are scheduled work and are held
to this section.
## 3. Background calls go elsewhere
When the model a background call would use is interactive-only, the call goes to the first of
(`kind: background`):
1. **its twin** — the same model on a connection that is not interactive-only. Among served ids
(`provider/model`): another id with the same part after its first `/`, not interactive-only,
the first in the list's order (`kind: twin`). The server, which knows its connections, also
requires the twin to be one the person may use in the chat's data group;
2. **a default that is not interactive-only** — in order: on a device, its global `model`
setting, then the instance's default model; on the server, the instance's default model;
3. **nowhere**. Then:
| The call | With nowhere to go |
|---|---|
| a title | skipped: the session keeps the name made from its first prompt |
| compaction the person asked for | refused in words: `interactive.texts.compact` |
| automatic compaction | skipped, and the turn goes on — a client may say so once; the person can switch model, or start anew |
**A model that cannot take the call is not somewhere to go**: for a summary, one whose context
window is below what must be sent, or that takes no tools while the conversation holds tool
calls, is passed over like one that is not listed (`unfit` in the cases). A title fits anywhere.
A skipped automatic compaction is not an attempt: it does not count toward a client's limit on
compacting within one turn.
**The call is the other model's.** Its tokens are counted under the model that was asked, never
under the session's, and the client says which model that was — for a title once, for a
compaction each time.
A call that goes elsewhere is otherwise the same call: the summary is asked for with the same
conversation and comes back into the same session, whose model does not change. A model that is
not interactive-only is asked itself, as before 3.9.0. The model a title is asked of is the
client's small model where it has one (the CLI's `small_model`), else the session's; the rule is
applied to whichever it is. For a subagent's automatic compaction it is the subagent's model
that is looked at — its twin, the same defaults, or skipped and said once to the session it
works for.
## 4. What is outside this
Embedding, speech and image models are not chat models and carry no such field. A device's
watch command (`_lembas/monitor`) asks no model.
+16 -1
View File
@@ -483,7 +483,8 @@
"denied": "Nobody answered this approval within {{minutes}} minutes, so it counts as denied.",
"monitor_asks": "The watch command would need approval in {{mode}} mode ({{reason}}), and a watch has nobody to ask. Allow the command in the project's permission rules, or choose a wider mode for the schedule.",
"monitor_denied": "The watch command is refused here: {{reason}}.",
"no_reply": "The run ended without a reply."
"no_reply": "The run ended without a reply.",
"terminal": "This schedule's conversation is open in a terminal on the computer, and a scheduled run does not run as a person's turn there. Close the session in that terminal, or start a new one in it, and the next run goes ahead."
},
"notify": {
"values": [
@@ -511,6 +512,20 @@
"summary_max": 300
}
},
"interactive": {
"about": "Spec 3.9.0 (interactive.md): models a provider allows for a person's own turns only. `field`: what a model's metadata says (models/schema.json; /v1/models and /api/v2 model objects, sent only when true). `texts.scheduled`: the refusal of scheduled work on one — a schedule given it, a run whose model is one, a scheduled subagent, a one-shot run with nobody at it — `{{model}}` the model as the person knows it. `texts.compact`: compaction asked for by the person with no twin and no usable default. `background`: the calls that are not the answer to a person's turn, and what each does with nowhere to go.",
"field": "interactive_only",
"reason": "interactive_only",
"texts": {
"scheduled": "{{model}} is on a connection for interactive use only: its provider's terms do not allow scheduled or background work. Choose a model on a pay-as-you-go connection.",
"compact": "This chat's model is on a connection for interactive use only, and compacting is background work its provider's terms do not allow. It needs the same model on a pay-as-you-go connection, or a default model that is not interactive-only."
},
"background": {
"title": "skip",
"compaction": "refuse",
"auto_compaction": "skip"
}
},
"phone": {
"about": "Spec 3.6.0 (phone.md): `phone_action`, carried out by the LLeMbas app on the person's phone and confirmed there. `capability` is what the app declares with each message it sends; `fields` what each action reads (anything else in a call is dropped before the phone sees it); `required` the fields each action needs (a list inside the list: any one of them); `check` the order the fields' values are checked in; `wait_seconds` how long a call waits for the phone's answer; `texts` what the model is told, `what` what a bad field should have been. conformance/phone.json.",
"capability": "phone_actions",
+1
View File
@@ -18,6 +18,7 @@
"effort_style": { "enum": ["top", "kwargs", "both"], "description": "OpenAI Chat dialect: where the effort goes — top-level `reasoning_effort`, `chat_template_kwargs.reasoning_effort` (all llama.cpp reads), or both (the default)." },
"vision": { "type": "boolean", "description": "Takes images. Never sent images otherwise: most servers refuse the whole request." },
"html_pages": { "type": "boolean", "default": false, "description": "Spec 3.8.0 (pages.md): this model can write HTML pages — a complete, self-contained page in an `html-view` block of its reply. False by default; pages are offered only when this is true, the instance's switch is on and the chat's is." },
"interactive_only": { "type": "boolean", "default": false, "description": "Spec 3.9.0 (interactive.md): the model is served through a connection its provider allows for a person's own turns only — a subscription whose terms forbid automated, batch and scheduled background use. The server's word, from the connection's type; sent only when true. A client does not offer it for a schedule, sends it no scheduled work, and sends a session's background calls (title, compaction) to its twin or a default instead." },
"tools": { "type": "boolean", "description": "Takes tool calls. false: it can only talk; never sent a tools array." },
"notes": { "type": "string", "maxLength": 300, "description": "What the model is good at, in a line: other models are told about it in the roster, for handing work over." },
"capacity": {
+18 -2
View File
@@ -1,6 +1,6 @@
# Permission rules: which one decides
Spec 3.8.0. The rules are data (`defaults.json`, the person's own config, a project's, and those
Spec 3.8.0; §2 rule 2 amended in 3.9.0. The rules are data (`defaults.json`, the person's own config, a project's, and those
made while a session runs); the modes say what happens to a call no rule settles (`modes.json`);
the hardline is under all of it (`hardline.json`). This says **which rule decides a call when
several match** — in both implementations, for a rule a person typed into a file exactly as for
@@ -38,6 +38,21 @@ than it (`deny` over `ask` over `allow`) — the strictest of them decides:
`read *.env: ask` asking, and `bash: allow` leaves `bash "git push *": ask`: a later, broader
rule changes what a broader rule decided, never what somebody wrote for the narrower case. To
allow the narrow thing, name it.
**A narrower rule that a later one narrows again does not count** (spec 3.9.0): among those
rules, one is set aside when a rule read after it also matches the call and is narrower than
it, **or has the same permission and pattern** (the same rule, written again) — that later
rule is what was written for the case. The defaults say `read *.env.*: ask`
and then `read *.env.example: allow`; under a candidate `read *` only the second counts for
`.env.example`, so an example file is read without asking after a broad allow exactly as
before it. (Before 3.9.0 both counted and the strictest won: making `read: allow` *started*
asking about `.env.example`.) Order still matters as it does in a file: a narrower rule read
*before* the rule it narrows sets nothing aside. So `read *.env: ask` in the defaults,
written again as `read *.env: allow` by a project, is allowed under a later broad allow
exactly as it is without one; and a project's `bash "rm *": deny` followed by its own
`bash "rm -i *": allow` leaves `rm -i` allowed. The person's own answer (rule 3) is untouched
by any of this: what the `user` layer says of the call still stands against a project's or a
made rule, of any breadth.
3. **The person's own answer.** What the `user` layer alone says of the call — its last matching
rule, of any breadth. A project, an "always" answer and a menu cannot loosen what the person's
own configuration says.
@@ -66,4 +81,5 @@ When a person makes a rule — an "always" answer, or one set in a menu:
every call the same way.
- The person is told what it did: where it holds, whether it was saved, and **which stricter
rules still apply** — every rule of the `default`, `user` or `project` layer that is narrower
than the new rule and stricter than it.
than the new rule and stricter than it. (A rule set aside for every call it could decide is
still listed: the list is of rules, not of calls.)
+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.11",
"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,
+4
View File
@@ -182,6 +182,10 @@
"description": "The model reads images: @image files, pasted paths and view_image.",
"type": "boolean"
},
"interactive_only": {
"description": "The server's word that this model is for a person's own turns only (harness interactive.md): no scheduled work is sent to it, and a session's title and compaction are asked of another model.",
"type": "boolean"
},
"html_pages": {
"description": "The server's word that this model can write HTML pages (harness pages.md). Read and kept, never used here: a terminal's model is not offered pages.",
"type": "boolean"
+227 -60
View File
@@ -15,7 +15,8 @@
// applies in every mode, as everywhere.
import { existsSync, readdirSync, statSync } from "node:fs"
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
import { createApp, type App, type SessionContext } from "../app.ts"
import { createApp, InteractiveOnlyError, type App, type SessionContext } from "../app.ts"
import { INTERACTIVE_REASON } from "../provider/interactive.ts"
import type { AskReply, Asker, Event } from "../bus/index.ts"
import { FileIndex } from "../project/files.ts"
import { loadSkills } from "../skill/index.ts"
@@ -32,20 +33,22 @@ 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"
import { HARNESS_VERSION } from "../harness.ts"
import { findProject, trustedRoots, trustedWithin, trustOf } from "../project/root.ts"
import { VERSION } from "../version.ts"
import { CWD_META, REMOTE_META, Store } from "../session/store.ts"
import { CWD_META, REMOTE_META, SCHEDULED_META, Store } from "../session/store.ts"
import { lastModels } from "../session/lastmodel.ts"
import type { Message } from "../provider/types.ts"
import type { Hub } from "./hub.ts"
import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import { isNote } from "../session/prefix.ts"
import { deniedText, finalReply, judgeMonitor, monitorTimeout, notifyOf, permissionFor, refusalText, runMonitor, runOutcome, scheduledMode, type Report, type ScheduledTurn } from "./scheduled.ts"
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
/** The link's version (LLeMbas `services/device_link.py:PROTOCOL`, harness/acp.md *Versions*). 3:
@@ -180,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. */
@@ -193,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> } }
@@ -295,6 +348,13 @@ export const CAPABILITIES = [
// Harness spec 3.8.0 (reports.md §6): `scheduled.notify` read; report_write offered to a run's
// model, and the report it writes carried in the turn's answer.
"reports",
// 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" }
@@ -410,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>()
@@ -420,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) {
@@ -506,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
@@ -570,14 +634,18 @@ export class AcpAgent {
/** `_lembas/directories`: what the web UI offers when a chat is pointed at this device.
* Without a path: the places — the remote roots and every trusted directory inside them. With one:
* its subdirectories. Each says whether a session may be opened there, by the same rule
* its subdirectories (`list: false`: the directory alone). Each says whether a session may be opened there, by the same rule
* session/new applies; the device still decides when the session is asked for. */
private directories(p: any) {
const L = this.limits
if (!L) throw new RpcError(INVALID_PARAMS, "directories are offered on the LLeMbas link only")
// Spec 3.9.0 (capability directory_model): the model last used in exactly that directory, where
// a session could be opened in it. As remembered — the client checks the person still has it.
const modelOf = lastModels()
const describe = (dir: string) => {
const why = this.refusal(dir)
return { path: dir, name: basename(dir) || dir, accepted: !why, ...(why ? { reason: why } : {}) }
const model = why ? undefined : modelOf(dir)
return { path: dir, name: basename(dir) || dir, accepted: !why, ...(why ? { reason: why } : {}), ...(model ? { model } : {}) }
}
const wanted = typeof p?.path === "string" ? p.path.trim() : ""
if (!wanted) {
@@ -589,6 +657,10 @@ export class AcpAgent {
const dir = resolve(expandHome(wanted))
if (!underRoots(dir, L.roots)) throw new RpcError(INVALID_PARAMS, `${dir} is outside the directories this device accepts remote work in (remote.roots)`)
if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new RpcError(INVALID_PARAMS, `${dir} is not a directory on this machine`)
const up = dirname(dir)
const parent = up !== dir && underRoots(up, L.roots) ? up : ""
// `list: false`: the directory alone, nothing listed — how a client asks for its model.
if (p?.list === false) return { ...describe(dir), parent }
let entries: ReturnType<typeof describe>[] = []
let error: string | undefined
try {
@@ -602,8 +674,7 @@ export class AcpAgent {
} catch (e) {
error = (e as Error).message
}
const up = dirname(dir)
return { ...describe(dir), parent: up !== dir && underRoots(up, L.roots) ? up : "", entries, ...(error ? { error } : {}) }
return { ...describe(dir), parent, entries, ...(error ? { error } : {}) }
}
private newSession(p: any) {
@@ -629,9 +700,11 @@ export class AcpAgent {
const model = served !== undefined ? this.chatModel(served) : typeof p?._meta?.model === "string" ? p._meta.model : undefined
const effort = effortOf(p?._meta?.effort)
try {
session.app = createApp({ cwd, mode, asker: this.asker(session), modelTitles: false, model, ...(effort !== undefined ? { effort } : {}) })
// A schedule's session uses the directory's model and never becomes it (spec 3.9.0).
session.app = createApp({ cwd, mode, asker: this.asker(session), modelTitles: false, model, ...(effort !== undefined ? { effort } : {}), kind: scheduled ? "scheduled" : this.lembas ? "link" : "stdio", ...(scheduled ? { automated: true as const } : {}) })
} catch (e) {
throw new RpcError(INVALID_PARAMS, (e as Error).message)
// Scheduled work never runs on an interactive-only model (interactive.md §2): the sentence, and why.
throw new RpcError(INVALID_PARAMS, (e as Error).message, e instanceof InteractiveOnlyError ? { reason: INTERACTIVE_REASON } : undefined)
}
if (served !== undefined) {
const why = this.notServed(session.app, model!)
@@ -646,6 +719,15 @@ export class AcpAgent {
session.id = id
session.turns = turnLog(id)
markRemote(session.app.store, id)
if (scheduled) {
try {
// How it was opened, kept with the session: opened from the store again — after a restart
// of the service — it is still a schedule's, with the tools it was opened with.
session.app.store?.setMeta(id, SCHEDULED_META, scheduled)
} catch {}
// …and the model it is on, kept from here on.
session.app.forgetful()
}
// The client's chat: its memory calls land in that chat's data group (acp.md *Memory*).
session.app.setScope(id)
this.takeContext(session, p)
@@ -708,7 +790,9 @@ export class AcpAgent {
const id = s.app.canonicalRef(ref)
if (!conn) throw new RpcError(INVALID_PARAMS, `this device is not logged in to ${this.instanceConnection}, so it cannot run ${p.model}`)
if (Object.keys(conn.models).length && !conn.models[id]) throw new RpcError(INVALID_PARAMS, `${conn.webui?.name ?? this.instanceConnection} does not serve ${p.model} to this device`)
s.app.switchModel(ref)
// The person's change is the directory's model from now (spec 3.9.0) — a schedule's session
// apart, which the app was told never to remember.
s.app.chooseModel(ref)
}
const effort = effortOf(p?.effort)
// A level the model does not offer is read as its start level; the answer says the one used.
@@ -748,9 +832,18 @@ export class AcpAgent {
if (refused) throw new RpcError(INVALID_PARAMS, refused)
const L = this.limits
const session: Session = { id, cwd: dir, prompting: false, app: undefined as unknown as App, turns: turnLog(id) }
session.app = createApp({ cwd: dir, ...(L ? { mode: L.maxMode } : {}), asker: this.asker(session), modelTitles: false, resuming: id })
// `resume` reads what kind of session it is: a schedule's comes back as one, on its own model.
session.app = createApp({ cwd: dir, ...(L ? { mode: L.maxMode } : {}), asker: this.asker(session), modelTitles: false, resuming: id, kind: "link" })
session.app.resume(id)
markRemote(session.app.store, id)
// A schedule's session stays one: nothing in it becomes its directory's model, and its list
// of tools is the one it was opened with — report_write for a schedule that notifies
// (reports.md §2). `opened` used to live in memory only, so a continuing schedule's next run
// after a restart of the service was not offered the tool its prompt told it to call.
try {
const kept = session.app.store?.meta<ScheduledTurn | true>(id, SCHEDULED_META)
if (kept && typeof kept === "object") session.opened = kept
} catch {}
session.app.setScope(id)
if (L) session.app.engine.mode = clampMode(session.app.engine.mode, L.maxMode)
this.sessions.set(id, session)
@@ -793,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)
})
@@ -938,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)
}
@@ -1029,6 +1104,13 @@ export class AcpAgent {
private async prompt(p: any): Promise<PromptResult> {
const turnId = turnIdOf(p)
const t = this.terminalFor(p)
// A scheduled prompt is judged before anything else, and never becomes a person's turn: a
// session open in a terminal runs what is typed there, on the terminal's model and under its
// rules — so a schedule's run is refused while its session is open in one (acp.md, *Refused*).
if (t && p?._meta?.lembas?.scheduled !== undefined && p._meta.lembas.scheduled !== null) {
this.judgeScheduled(p._meta.lembas.scheduled)
throw new RpcError(INVALID_PARAMS, SCHEDULED.texts.terminal, { reason: "terminal" })
}
if (t) {
const L = this.limits
if (L && !t.explicit && MODE_RANK[t.mode] < MODE_RANK[L.maxMode])
@@ -1042,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)
@@ -1052,24 +1138,55 @@ export class AcpAgent {
const run = async (started: () => void): Promise<PromptResult> => {
s.prompting = true
// The turn that runs now says whether the session is a scheduled run's (it may wait behind another).
if (scheduled) s.scheduled = scheduled
// The turn that runs now is the schedule's, or the person's own in the run's chat: scheduled
// work never uses an interactive-only model — refused before anything is sent to it, and
// before anything about the session is changed.
const interactiveOnly = s.app.setAutomated(scheduled !== undefined)
if (interactiveOnly) {
s.app.setAutomated(false)
s.prompting = false
delete s.scheduled
throw new RpcError(INVALID_PARAMS, interactiveOnly, { reason: INTERACTIVE_REASON })
}
if (scheduled) (s.scheduled = scheduled), s.app.forgetful()
else delete s.scheduled
started()
try {
return await this.runPrepared(s, prepared, turnId)
} catch (e) {
// A command's own model that scheduled work may not use: the same refusal, with its reason.
if (e instanceof InteractiveOnlyError) throw new RpcError(INVALID_PARAMS, e.message, { reason: INTERACTIVE_REASON })
throw e
} finally {
s.prompting = false
// What comes next is the person's until a prompt says otherwise.
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])
})
}
@@ -1105,25 +1222,33 @@ export class AcpAgent {
for (const a of prepared.atPaths) this.indexFor(app.engine.o.toolCtx.cwd).used(a.replace(/\/$/, ""))
const prev = { model: app.engine.model.ref, mode: app.engine.mode, effort: app.engine.effort }
try {
if (prepared.model) app.switchModel(prepared.model)
if (prepared.model) app.switchModel(prepared.model, "borrowed")
if (prepared.mode) app.engine.mode = this.limits ? clampMode(prepared.mode, this.limits.maxMode) : prepared.mode
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
// mode (a plan approved), which then stays.
// The model back, and the effort the person had on it — not the model's default.
if (prepared.model && app.engine.model.ref !== prev.model) {
app.switchModel(prev.model)
app.engine.effort = prev.effort
}
if (prepared.model) app.returnModel(prev)
if (prepared.mode && app.engine.mode === (this.limits ? clampMode(prepared.mode, this.limits.maxMode) : prepared.mode)) app.engine.mode = prev.mode
}
}
/** 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 {
@@ -1159,17 +1284,18 @@ export class AcpAgent {
})
const prev = { model: app.engine.model.ref, effort: app.engine.effort }
try {
if (prepared.model) app.switchModel(prepared.model)
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.engine.model.ref !== prev.model) {
app.switchModel(prev.model)
app.engine.effort = prev.effort
}
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()
}
}
@@ -1208,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(),
@@ -1295,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)
@@ -1334,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) {
@@ -1365,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 }
}
@@ -1454,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) {
+39 -4
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)
@@ -604,7 +639,7 @@ export class Share {
this.mine(p)
// Compared as the ref the model has now: the instance's `<login>/<served>` names the
// same model as `deepseek/x`, and switching to it again would reset the effort.
if (typeof p?.model === "string" && p.model && this.app.canonicalRef(p.model) !== this.app.engine.model.ref) this.app.switchModel(p.model)
if (typeof p?.model === "string" && p.model && this.app.canonicalRef(p.model) !== this.app.engine.model.ref) this.app.chooseModel(p.model)
const effort = effortOf(p?.effort)
if (effort !== undefined) this.app.engine.effort = readLevel(this.app.engine.model, effort)
this.hooks.changed()
+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>()
+219 -8
View File
@@ -15,7 +15,7 @@ import { loadConfig, type Loaded } from "./config/load.ts"
import type { Mode } from "./config/schema.ts"
import { DEFAULT_RULES, toRules } from "./permission/evaluate.ts"
import { hardlineRules } from "./permission/hardline.ts"
import { clientFor, familyOf, resolveModel } from "./provider/index.ts"
import { clientFor, familyOf, resolveModel, ModelError } from "./provider/index.ts"
import { subagentModel, type ModelInfo } from "./team/subagents.ts"
import { assembleSystem, instructionFiles, knowledgeScope, modeText } from "./prompt/assemble.ts"
import type { Changing } from "./session/prefix.ts"
@@ -29,8 +29,9 @@ 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, Store } from "./session/store.ts"
import { CWD_META, REMOTE_META, SCHEDULED_META, SCHEDULED_MODEL_META, Store } from "./session/store.ts"
import { BUILTIN_TOOLS } from "./tool/registry.ts"
import { DEFAULT_LIMITS, MemoryStore } from "./memory/store.ts"
import { loadSkills, skillLines, type Skill } from "./skill/index.ts"
@@ -51,8 +52,15 @@ import { embedderFor } from "./library/embed.ts"
import { isLevel, levelsFor, readLevel, type Level } from "./provider/effort.ts"
import { memberTools as memberToolsOf, readingBashByDefault, Team, TEAM, TEAM_TOOLS, type Capacity, type TeamAgent } from "./team/team.ts"
import { whoDecides } from "./team/delegation.ts"
import { lastModel, records, rememberModel, startModel, type SessionKind } from "./session/lastmodel.ts"
import { globalConfigFile, readRaw } from "./config/settings.ts"
import { background, scheduledRefusal, type BackgroundCall, type Listed } from "./provider/interactive.ts"
import { TeamRuntime, type MemberHandle } from "./team/runtime.ts"
/** Scheduled or unattended work was about to use an interactive-only model (harness
* interactive.md §2): the message is the spec's sentence. */
export class InteractiveOnlyError extends ModelError {}
export interface AppOptions {
cwd: string
model?: string
@@ -74,6 +82,14 @@ export interface AppOptions {
* made first. Without it every reopening — the service opening a web chat's session from the
* store — left an empty, untitled session behind in the project, listed by /sessions as its id. */
resuming?: string
/** What kind of session it is, for the directory's model (harness acp.md, *The model last used
* in a directory*; `records` in session/lastmodel.ts): a terminal's (the default), one on the
* link, an editor's, a one-shot run, or one a schedule opened — the last two never make their
* model the directory's, though they start on it. */
kind?: SessionKind
/** Scheduled work, or a one-shot run with nobody at it (harness interactive.md §2): never on an
* interactive-only model — not at the start, by a switch, or in a subagent. */
automated?: true
}
const UNATTENDED: Record<Mode, string | undefined> = {
@@ -107,7 +123,20 @@ export interface App {
/** A ref in any form it may be written in (the old `<login>/<model>` too) as the ref the
* model has now; the ref itself when it names nothing. */
canonicalRef(ref: string): string
switchModel(ref: string): void
/** `borrowed`: for one prompt only (a command's own model) — not the directory's model; given
* back with `returnModel`. */
switchModel(ref: string, how?: "borrowed"): void
/** After a prompt on a borrowed model: the model and the effort the session had, and nothing
* borrowed any more — also when the command's model was the session's own. */
returnModel(prev: { model: string; effort: Level }): void
/** The person changed the session's model (`_lembas/configure`, a terminal's shared session):
* switched, and remembered for the directory. */
chooseModel(ref: string): void
/** This session is a schedule's from now on: nothing in it becomes its directory's model. */
forgetful(): void
/** Whether what runs now is scheduled work (a schedule's turn) or the person's own. On: the
* spec's sentence when the session's model is interactive-only and so may not run it. */
setAutomated(on: boolean): string | undefined
newSession(): void
/** Name the open session by hand (a chat renamed in the web UI); no model title follows. */
rename(title: string): void
@@ -146,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. */
@@ -225,7 +260,25 @@ export function createApp(o: AppOptions): App {
const trust = trustOf(project.root)
const trusted = trust === "trusted"
const loaded = loadConfig({ projectConfigDir: project.dir, trusted })
const model = resolveModel(loaded, o.model ?? loaded.config.model)
// The login's models as the interactive-only rules read them (harness interactive.md).
const listed = (): Listed[] => loaded.refs.map((r) => ({ id: r.ref, ...(loaded.connections[r.connection]?.models[r.id]?.interactive_only === true ? { interactive_only: true } : {}) }))
// Which model it starts on (harness acp.md, spec 3.9.0): the one asked for, the project's
// setting, the model last used in this directory while the login serves it, the global setting,
// the server's default.
const projectModel = trusted && typeof readRaw(join(project.dir, "config.yaml")).model === "string" ? loaded.config.model : undefined
const start = startModel({
asked: o.model,
project: projectModel,
directory: o.model || projectModel ? undefined : lastModel(o.cwd),
global: projectModel ? undefined : loaded.config.model,
// Scheduled work skips an interactive-only directory's model as it skips one no longer served.
served: listed().filter((m) => !(o.automated && m.interactive_only)).map((m) => m.id),
})
const model = resolveModel(loaded, start.model)
let automated = o.automated === true
/** Why scheduled work may not use `m`, or undefined: it is interactive-only (interactive.md §2). */
const notAutomated = (m: ResolvedModel): string | undefined => (m.spec.interactive_only === true ? scheduledRefusal(m.ref, [{ id: m.ref, interactive_only: true }]) : undefined)
if (automated && notAutomated(model)) throw new InteractiveOnlyError(notAutomated(model))
// An untrusted project is read-only: plan mode, and its own config is ignored.
let mode: Mode = o.mode ?? loaded.config.mode ?? "manual"
if (trust === "readonly") mode = "plan"
@@ -453,6 +506,16 @@ export function createApp(o: AppOptions): App {
const jobsSessionId = () => engine.sessionId ?? standIn
const wake = (text: string, shown: string) => {
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) {
// 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 })
@@ -463,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)
@@ -490,6 +553,9 @@ export function createApp(o: AppOptions): App {
if ("refused" in r) throw new ToolError(r.refused)
m = wanted && wanted.ref === r.model ? wanted : engine.model
}
// A scheduled run's subagents are the same run: none on an interactive-only model.
const scheduledNo = scheduledNow() ? notAutomated(m) : undefined
if (scheduledNo) throw new ToolError(scheduledNo)
// A team's member is not refused for capacity: the team gave it its slot (team.md §8).
if (!member) {
const running = registry.running(jobsSessionId()).filter((j) => j.kind === "subagent" && j.subagent && !j.team)
@@ -552,6 +618,7 @@ export function createApp(o: AppOptions): App {
return o.asker.plan
},
})
let compactionSkipSaid = false
const child = new Engine({
bus: childBus,
asker: askerFor(),
@@ -566,6 +633,16 @@ export function createApp(o: AppOptions): App {
effort: m.ref === engine.model.ref ? engine.effort : startEffort(m),
maxSteps: loaded.config.limits?.subagent_steps ?? LOOP.jobs.subagent_steps.default,
compaction,
// A subagent's own automatic compaction is background work like the session's
// (interactive.md §3): its twin, a default, or skipped — said once, to the session.
background: (call, needed) => {
const where = backgroundFor(child.model, call, needed)
if (where && !("client" in where) && !compactionSkipSaid) {
compactionSkipSaid = true
bus.emit({ type: "notice", message: `the subagent ${spec.name} is not compacting its conversation: its model is for interactive use only and there is no other model to ask for the summary` })
}
return where
},
perm: childPerm,
toolCtx: {
...baseToolCtx(),
@@ -691,6 +768,7 @@ export function createApp(o: AppOptions): App {
maxSteps: loaded.config.limits?.steps,
budget: { wall_seconds: loaded.config.limits?.wall_seconds, output_bytes: loaded.config.limits?.output_bytes, completion_tokens: loaded.config.limits?.completion_tokens },
compaction,
background: (call, needed) => backgroundFor(engine.model, call, needed),
perm,
toolCtx: { ...baseToolCtx(), jobs: { registry, owner: baseOwner }, team: { get runtime() { return teamRt }, as: TEAM.names.lead } },
system: (m, current, plan, ch) => system(m, current, ch, undefined, undefined, plan),
@@ -702,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.
@@ -771,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)
@@ -853,7 +942,14 @@ export function createApp(o: AppOptions): App {
named = "model"
const first = firstShown || store.firstPrompt(id)
const reply = firstReply(engine.messages)
const { client } = small()
// A title is background work: for an interactive-only model it is asked of the twin or a
// default, or not at all — the prompt's line stays (interactive.md §3).
const s = small()
const where = backgroundFor(s.model, "title")
if (where && !("client" in where)) return
const client = where?.client ?? s.client
// Said once (a session is named once), with the model that is asked.
if (where) bus.emit({ type: "notice", level: "info", message: `the session's title is asked of ${where.model.ref}: ${s.model.ref} is for interactive use only, and naming a session is background work` })
const signal = AbortSignal.timeout(120_000)
// Quietly: a title is not worth a warning, and the prompt's line is already there.
void modelTitle(client, first, reply, signal)
@@ -867,8 +963,70 @@ export function createApp(o: AppOptions): App {
const turns = new Turns(engine, snapshots, store)
// By provider for an instance's models (`deepseek/deepseek-flash`), src/provider/refs.ts.
const modelRefs = () => loaded.refs.map((r) => r.ref)
const switchModel = (ref: string) => {
/** Where a background call that would use `m` goes when `m` is interactive-only (harness
* interactive.md §3): its twin, else the global `model` setting, else the server's default —
* or skipped, or refused in words. Undefined: `m` itself, as ever. */
function backgroundFor(m: ResolvedModel, call: BackgroundCall, needed?: number): { client: Client; effort: Level; model: ResolvedModel } | { skip: true } | { refused: string } | undefined {
if (m.spec.interactive_only !== true) return undefined
const canonical = (ref: unknown): string | undefined => {
try {
return typeof ref === "string" && ref ? resolveModel(loaded, ref).ref : undefined
} catch {
return undefined
}
}
// A model that cannot take a summary's request is nowhere to go: its window is below what
// must be sent, or it takes no tools and the conversation is full of tool calls. A title is
// a few lines and fits anywhere.
const unfit =
call === "title"
? []
: loaded.refs
.filter((r) => {
const spec = loaded.connections[r.connection]?.models[r.id]
return spec?.tools === false || (needed !== undefined && typeof spec?.context === "number" && spec.context > 0 && spec.context < needed)
})
.map((r) => r.ref)
const r = background({ model: m.ref, models: listed(), defaults: [canonical(readRaw(globalConfigFile()).model), canonical(loaded.connections[m.connectionName]?.webui?.default)], call, unfit })
if (!("model" in r)) return r
const other = resolveModel(loaded, r.model)
return { client: clientFor(other), effort: startEffort(other), model: other }
}
// The directory's model (spec 3.9.0): written when a person's turn begins and when the person
// changes the model — never for a model borrowed for one prompt, a turn the harness started,
// a one-shot run or a schedule's session.
let kind: SessionKind = o.kind ?? "terminal"
let borrowed = false
/** The turn running now was started by the harness (a job's note), not by a person. */
let machineTurn = false
/** The one rule (`records`, conformance last_model `record`), asked with what is happening now. */
const remember = (what: "turn" | "change") => {
if (records({ session: kind, agent: "main", what: borrowed ? "command" : what, machine: machineTurn })) rememberModel(o.cwd, engine.model.ref)
}
bus.on((e) => {
if (e.type === "prompt") {
machineTurn = e.machine === true
remember("turn")
} else if (e.type === "task" && e.state === "end") machineTurn = false
})
/** Whether what runs now is scheduled work: a schedule's turn — or, in a session a schedule
* opened, anything that is not a person's own turn: a turn one of the run's jobs woke, a
* subagent started after the run's turn ended (interactive.md §2). */
const scheduledNow = () => automated || (kind === "scheduled" && (machineTurn || !turns.current))
/** A schedule's session keeps its own model with it (acp.md, *The run's model*). */
const keepModel = () => {
if (kind !== "scheduled" || borrowed || !store || !engine.sessionId) return
try {
store.setMeta(engine.sessionId, SCHEDULED_MODEL_META, engine.model.ref)
} catch {}
}
const switchModel = (ref: string, how?: "borrowed") => {
const m = resolveModel(loaded, ref)
// Within scheduled work; between turns the session's model is whoever configures it's to
// choose, and a scheduled turn on an interactive-only model is refused when it comes.
const no = automated || (kind === "scheduled" && machineTurn) ? notAutomated(m) : undefined
if (no) throw new InteractiveOnlyError(no)
borrowed = how === "borrowed"
engine.setModel(m, clientFor(m), startEffort(m))
}
const setIn = (key: string, value: unknown) => {
@@ -913,7 +1071,7 @@ export function createApp(o: AppOptions): App {
}
},
apply(key, v) {
if (key === "model") switchModel(String(v))
if (key === "model") (switchModel(String(v)), remember("change"), keepModel())
else if (key === "effort") engine.effort = v as Level
else if (key === "mode") engine.mode = v as Mode
else if (key === "limits.steps") engine.o.maxSteps = Number(v)
@@ -978,6 +1136,24 @@ export function createApp(o: AppOptions): App {
}
},
switchModel,
returnModel(prev) {
borrowed = false
if (engine.model.ref !== prev.model) switchModel(prev.model)
engine.effort = prev.effort
},
chooseModel(ref) {
switchModel(ref)
remember("change")
keepModel()
},
forgetful() {
kind = "scheduled"
keepModel()
},
setAutomated(on) {
automated = on
return on ? notAutomated(engine.model) : undefined
},
settings,
memory,
projectMemory,
@@ -999,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() {
@@ -1027,6 +1214,8 @@ export function createApp(o: AppOptions): App {
keepCwd(s?.id)
standIn = `local_${crypto.randomUUID().slice(0, 8)}`
teamRt.reset(newTeam())
// A new session is this app's own kind again, whatever the one before it was.
kind = o.kind ?? "terminal"
engine.newSession(s?.id)
turns.reset()
if (s) bus.emit({ type: "session", id: s.id, model: engine.model.ref, mode: engine.mode })
@@ -1041,7 +1230,29 @@ export function createApp(o: AppOptions): App {
frozen = freeze()
void readServerMemory()
teamRt.reset(newTeam())
// A session a schedule opened stays one wherever it is opened — in a terminal too
// (/sessions, -c): nothing in it becomes its directory's model.
try {
kind = store.meta(id, SCHEDULED_META) ? "scheduled" : (o.kind ?? "terminal")
} catch {
kind = o.kind ?? "terminal"
}
engine.resume(id, store.context(id))
// …and it is on its own model again, as it was — not on what a new session here would
// start on. One with no model kept leaves an interactive-only model for the start order's
// next that scheduled work may use.
if (kind === "scheduled") {
try {
const own = store.meta<string>(id, SCHEDULED_MODEL_META)
if (own) {
if (resolveModel(loaded, own).ref !== engine.model.ref) switchModel(own)
} else if (notAutomated(engine.model)) {
const again = startModel({ project: projectModel, directory: projectModel ? undefined : lastModel(o.cwd), global: projectModel ? undefined : loaded.config.model, served: listed().filter((m) => !m.interactive_only).map((m) => m.id) })
const m = resolveModel(loaded, again.model)
if (!notAutomated(m)) switchModel(m.ref)
}
} catch {}
}
// A session from before titles gets its first prompt's line now, and the model's after the next reply.
firstShown = ""
const row = store.session(id)
+24 -6
View File
@@ -87,7 +87,10 @@ Local mode:
start asks, and the answer is kept in the local directory.
Options for run:
-m, --model conn/model model to use (default: config.yaml \`model\`)
-m, --model conn/model model to use (default: the project's \`model\`, else the one last used in
this directory, else config.yaml \`model\`). With no terminal at
all (cron, a pipeline) a model for interactive use only is refused:
run it at a terminal (ssh -t), or name another model
--mode MODE manual | edit | auto | plan
-e, --effort LEVEL ${EFFORTS.join(" | ")} | off | default (one the model offers)
-y, --yes approve every ask (still never the hardline)
@@ -328,17 +331,32 @@ async function main() {
if (values.mode && !asMode(values.mode)) fail(`--mode must be one of ${MODES.join(", ")}`, 2)
if (values.effort && !isLevel(values.effort)) fail(`--effort must be one of ${EFFORTS.join(", ")}, off, default`, 2)
const app = createApp({
const { nobodyAtIt, RUN_HINT } = await import("./provider/interactive.ts")
const { InteractiveOnlyError } = await import("./app.ts")
const options = {
cwd: process.cwd(),
model: values.model,
mode: asMode(values.mode),
effort: values.effort,
asker: terminalAsker({ yes: values.yes ?? false, unattended: loadConfig().config.question?.unattended, theme: loadConfig().config.theme }),
unattended: !values.yes && !process.stdin.isTTY,
store: values["no-store"] ? false : undefined,
snapshots: false,
modelTitles: false,
})
store: values["no-store"] ? (false as const) : undefined,
snapshots: false as const,
modelTitles: false as const,
// A one-shot run starts on the directory's model and never becomes it (spec 3.9.0).
kind: "run" as const,
// With no terminal at all it is a batch job — a cron line, a pipeline — and never runs on an
// interactive-only model (harness interactive.md §2).
...(nobodyAtIt({ stdin: process.stdin.isTTY, stdout: process.stdout.isTTY, stderr: process.stderr.isTTY }) ? { automated: true as const } : {}),
}
let app: ReturnType<typeof createApp>
try {
app = createApp(options)
} catch (e) {
// The sentence, and the way forward.
if (e instanceof InteractiveOnlyError) fail(`${e.message}\n${RUN_HINT}`)
throw e
}
if (values.json) renderJson(app.bus)
else renderPlain(app.bus, { color: process.stderr.isTTY ?? false, showReasoning: values.reasoning ?? false, icons: app.loaded.config.icons, theme: app.loaded.config.theme })
process.on("SIGINT", () => app.engine.cancel())
+1
View File
@@ -56,6 +56,7 @@ export const ModelSpec = z.strictObject({
effort: z.union([z.enum(EFFORTS), z.literal("off"), z.literal("default")]).optional().describe("The level a conversation starts with, when the model offers it: an effort, `off` (thinking switched off, with thinking_switch) or `default` (nothing sent, for a model that takes no efforts)."),
effort_style: z.enum(["top", "kwargs", "both"]).optional().describe("Where the effort goes in a request: top-level, in chat_template_kwargs, or both (the default: llama.cpp drops top-level)."),
vision: z.boolean().optional().describe("The model reads images: @image files, pasted paths and view_image."),
interactive_only: z.boolean().optional().describe("The server's word that this model is for a person's own turns only (harness interactive.md): no scheduled work is sent to it, and a session's title and compaction are asked of another model."),
html_pages: z.boolean().optional().describe("The server's word that this model can write HTML pages (harness pages.md). Read and kept, never used here: a terminal's model is not offered pages."),
tools: z.boolean().optional().describe("false: a model without tool calls — it can only talk."),
headers: z.record(z.string(), z.string()).optional().describe("Extra HTTP headers for this model's requests."),
+5 -1
View File
@@ -124,6 +124,10 @@ export const LOOP: {
wrap_up: { message: string }
nudges: { max: number }
parallel: { max: number }
/** Interactive-only models (spec 3.9.0, harness/interactive.md): the field, the reason of a
* refused scheduled request, the two sentences, and what each background call does with
* nowhere to go. */
interactive: { field: string; reason: string; texts: { scheduled: string; compact: string }; background: Record<"title" | "compaction" | "auto_compaction", string> }
/** Background work (spec 2.0.0): the marks every note begins with, and the caps. */
jobs: {
marks: { command: string; subagent: string; message: string; to_subagent: string }
@@ -187,7 +191,7 @@ export const LOOP: {
sentinel: string
statuses: string[]
monitor: { timeout_seconds: { default: number; min: number; max: number }; excerpt_chars: number; output_max_bytes: number }
texts: Record<"off" | "plan" | "denied" | "monitor_asks" | "monitor_denied" | "no_reply", string>
texts: Record<"off" | "plan" | "denied" | "monitor_asks" | "monitor_denied" | "no_reply" | "terminal", string>
/** Spec 3.8.0 (reports.md): a schedule's notify-when — its values, the instruction texts,
* what report_write answers, the limits of the history line and of a made-up summary. */
notify: {
+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 }
}
+2
View File
@@ -65,6 +65,8 @@ export interface ServedModel {
vision?: boolean
/** Spec 3.8.0 (harness pages.md): the model can write HTML pages. */
html_pages?: boolean
/** Spec 3.9.0 (harness interactive.md): for a person's own turns only. Sent only when true. */
interactive_only?: boolean
tools?: boolean
notes?: string
capacity?: { group?: string; single_session?: boolean; parallel?: number }
+5 -1
View File
@@ -132,6 +132,10 @@ export function runStatus(r: Run): string {
return r.status
}
/** A schedule's type (harness acp.md, spec 3.9.0): Agentic when it runs on a linked computer —
* one device, one directory, the agent's tools there — else Chat. What `runs_on` says; no field. */
export const scheduleType = (s: Pick<Schedule, "runs_on">): "Chat" | "Agentic" => (s.runs_on ? "Agentic" : "Chat")
/** `/schedule` and `/schedule list`. */
export function listLines(all: Schedule[], now = new Date()): string[] {
if (!all.length) return ["no schedules yet — /schedule new <what, and when> (\"every weekday at 8 summarise the open issues\")"]
@@ -143,7 +147,7 @@ export function listLines(all: Schedule[], now = new Date()): string[] {
const watch = s.watch ? ` · watches ${s.watch.kind === "url" ? s.watch.url : s.watch.command}` : ""
const reports = s.notify ? ` · ${notifyWords(s.notify, s.notify_when)}` : ""
out.push(`${s.title} (${s.id}) — ${s.description || "no rule"}`)
out.push(` ${state}${last}${where}${watch}${reports}`)
out.push(` ${scheduleType(s)} · ${state}${last}${where}${watch}${reports}`)
}
out.push("", "/schedule new <words> · pause|resume|run|history <id or title>")
return out
+2
View File
@@ -101,6 +101,8 @@ export function specFor(m: ServedModel, connection: string): ModelSpec {
if (m.vision !== undefined) out.vision = m.vision
// Spec 3.8.0 (pages.md): kept as the server says it; nothing here offers pages.
if (m.html_pages !== undefined) out.html_pages = m.html_pages === true
// Spec 3.9.0 (interactive.md): the server's word; what is scheduled or background work is decided here.
if (m.interactive_only === true) out.interactive_only = true
if (m.tools !== undefined) out.tools = m.tools
if (m.notes) out.notes = m.notes.slice(0, 300)
if (m.capacity?.single_session) out.single_session = true
+7 -2
View File
@@ -93,14 +93,19 @@ export function ruleAction(permission: string, pattern: string, rules: Rule[]):
/** The rule that decides (harness permission/rules.md §2). The last matching rule is the
* candidate. One made after the written ones — a project's, an "always" answer, one set in a
* menu — gives way to whichever of these is stricter than it, the strictest deciding:
* a narrower written rule (`read: allow` leaves `read *.env: ask` asking); the person's own
* a narrower written rule (`read: allow` leaves `read *.env: ask` asking) — unless a later
* written rule narrows that one again, which then speaks for the case; the person's own
* answer (their config's last matching rule, of any breadth); and, for an "always" answer, a
* written deny. A candidate from the defaults or the person's own config decides as it is. */
function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule | undefined {
const matches = (r: Rule) => match(permission, r.permission) && match(pattern, r.pattern)
const hit = rules.findLast(matches)
if (!hit || !(hit.source === "project" || hit.learned)) return hit
const floors: Rule[] = rules.filter((r) => r !== hit && !r.learned && matches(r) && narrowerThan(r, hit))
// A narrower rule that a later one narrows again is set aside (spec 3.9.0): `read *.env.*: ask`
// gives way to `read *.env.example: allow` written after it, as it does without the candidate.
const narrower = rules.filter((r) => r !== hit && !r.learned && matches(r) && narrowerThan(r, hit))
// …or writes again: the same permission and pattern, later, is the rule as it stands now.
const floors: Rule[] = narrower.filter((r, i) => !narrower.slice(i + 1).some((later) => narrowerThan(later, r) || (later.permission === r.permission && later.pattern === r.pattern)))
const own = rules.findLast((r) => r.source === "global" && !r.learned && matches(r))
if (own) floors.push(own)
if (hit.learned) {
+54
View File
@@ -0,0 +1,54 @@
// Interactive-only models (harness interactive.md, spec 3.9.0): a model its provider allows for a
// person's own turns and nothing else. The server says which (`interactive_only` on a served
// model); it cannot tell what a request to its /v1 is for, so what is scheduled or background
// work is decided here. Three small rules (conformance/interactive.json).
import { LOOP } from "../harness.ts"
import { fillPrompt } from "../prompt/fill.ts"
export interface Listed {
id: string
interactive_only?: boolean
}
const only = (model: string, models: readonly Listed[]): boolean => models.find((m) => m.id === model)?.interactive_only === true
/** The same model on a connection that is not interactive-only: another served id with the same
* part after its first `/`, the first in the list's order. */
export function twin(model: string, models: readonly Listed[], fits: (id: string) => boolean = () => true): string | undefined {
const cut = model.indexOf("/")
if (cut < 0) return undefined
const name = model.slice(cut + 1)
return models.find((m) => m.id !== model && m.interactive_only !== true && m.id.indexOf("/") >= 0 && m.id.slice(m.id.indexOf("/") + 1) === name && fits(m.id))?.id
}
export type BackgroundCall = "title" | "compaction" | "auto_compaction"
/** Where a background call that would use `model` goes: the model itself when it is not
* interactive-only; else its twin; else the first default that is listed and is not; else
* nowhere — skipped (a title, automatic compaction) or refused in words (compaction asked for). */
export function background(o: { model: string; models: readonly Listed[]; defaults?: readonly (string | undefined)[]; call: BackgroundCall; unfit?: readonly string[] }): { model: string } | { skip: true } | { refused: string } {
if (!only(o.model, o.models)) return { model: o.model }
// A model that cannot take the call — a window below what must be sent, no tools for a
// conversation that has tool calls — is passed over like one that is not there.
const fits = (id: string) => !(o.unfit ?? []).includes(id)
const other = twin(o.model, o.models, fits) ?? (o.defaults ?? []).find((d): d is string => Boolean(d) && o.models.some((m) => m.id === d) && !only(d!, o.models) && fits(d!))
if (other) return { model: other }
return LOOP.interactive.background[o.call] === "refuse" ? { refused: LOOP.interactive.texts.compact } : { skip: true }
}
/** Why scheduled work may not use `model` — the spec's sentence — or undefined when it may. */
export function scheduledRefusal(model: string, models: readonly Listed[], label = model): string | undefined {
return only(model, models) ? fillPrompt(LOOP.interactive.texts.scheduled, { model: label }) : undefined
}
/** What `-32602` carries as `data.reason` for a scheduled request refused for it. */
export const INTERACTIVE_REASON = LOOP.interactive.reason
/** A one-shot run with nobody at it: none of its standard input, output and error is a terminal
* (a cron job, a pipeline). Somebody piping a prompt in at a terminal still has one. */
export function nobodyAtIt(streams: { stdin?: boolean; stdout?: boolean; stderr?: boolean }): boolean {
return !streams.stdin && !streams.stdout && !streams.stderr
}
/** What `lembas run` adds to the refusal: the way forward. */
export const RUN_HINT = "Run it at a terminal (over SSH: ssh -t), or name a model that is not interactive-only with -m."
+189 -13
View File
@@ -70,6 +70,10 @@ export interface EngineOptions {
/** Take a rule out of the project's config again; whether it was there. */
forgetRule?: (rule: Pick<Rule, "permission" | "pattern">) => boolean
compaction?: { autoAt?: number }
/** Where a compaction's summary is asked for when it may not be asked of the session's model
* (harness interactive.md §3): another model's client, skip it, or the refusal's words.
* Undefined, or absent: the session's own model, as ever. */
background?: (call: "compaction" | "auto_compaction", needed?: number) => { client: Client; effort: Level; model: ResolvedModel } | { skip: true } | { refused: string } | undefined
/** Starts a subagent for the task tool; absent in a subagent. */
spawn?: ToolContext["spawn"]
/** What a message sent mid-turn starts with: the user's words for a session, the main agent's for
@@ -99,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. */
@@ -148,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[] = []
@@ -177,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
@@ -244,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. */
@@ -374,11 +455,12 @@ export class Engine {
}
/** A request's usage, kept with the session (cached input tokens included, §10 rule 6). */
private recordUsage(usage: Usage, kind: "step" | "compaction") {
private recordUsage(usage: Usage, kind: "step" | "compaction", model = this.model.ref) {
this.lastRequest = { usage, kind }
if (this.o.store && this.sessionId)
try {
this.o.store.request(this.sessionId, { model: this.model.ref, kind, ...usage })
// Under the model that was asked: a summary asked of another model is that model's use.
this.o.store.request(this.sessionId, { model, kind, ...usage })
} catch {}
}
@@ -529,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()
@@ -547,7 +630,7 @@ export class Engine {
this.busy = true
this.abort = new AbortController()
try {
return await this.summarise(this.abort.signal)
return await this.summarise(this.abort.signal, "compaction")
} finally {
this.busy = false
}
@@ -556,13 +639,22 @@ export class Engine {
/** The summary, asked for as the next turn of this same conversation (harness context.md §7):
* the same system prompt and tools, every message as it is, then tasks/compact.md with an empty
* transcript and previous summary. Nothing of it is shown or stored as a turn; a tool call in the reply is not run. */
private async summarise(signal: AbortSignal): Promise<string> {
private async summarise(signal: AbortSignal, call: "compaction" | "auto_compaction"): Promise<string> {
// An interactive-only model is not asked for background work: the summary is another model's,
// of the same conversation, and comes back into this session (interactive.md §3).
const elsewhere = this.o.background?.(call, this.contextUsed())
if (elsewhere && "refused" in elsewhere) throw new Error(elsewhere.refused)
if (elsewhere && "skip" in elsewhere) throw new Error("skipped")
const client = elsewhere?.client ?? this.client
const effort = elsewhere?.effort ?? this.effort
// Said, with the model that is asked: its use is counted under that model, not the session's.
if (elsewhere) this.o.bus.emit({ type: "notice", level: "info", message: `the summary is asked of ${elsewhere.model.ref}: ${this.model.ref} is for interactive use only, and compacting is background work` })
// No previous summary in the ask: an earlier one is already the conversation's first message.
const ask: Message = { role: "user", parts: [{ type: "text", text: compactAsk() }] }
let summary = ""
for await (const ev of this.client.stream({ system: this.systemPrompt(), messages: mergeUsers([...this.messages, ask]), tools: this.toolSpecs(), effort: this.effort, signal })) {
for await (const ev of client.stream({ system: this.systemPrompt(), messages: mergeUsers([...this.messages, ask]), tools: this.toolSpecs(), effort, signal })) {
if (ev.type === "finish") summary = summaryOf(ev.message.parts)
else if (ev.type === "usage") this.recordUsage(ev.usage, "compaction")
else if (ev.type === "usage") this.recordUsage(ev.usage, "compaction", elsewhere?.model.ref)
}
if (!summary) throw new Error("the model returned an empty summary")
// The harness's own table of the reads still in the conversation (context.md §7), after the
@@ -603,6 +695,7 @@ export class Engine {
/** Before a step: past compaction.auto_at of the window, compact. Old tool results are never
* pruned in place (harness context.md: nothing already sent is rewritten — it would throw the
* prompt cache away from that point); compaction is the one deliberate break. */
private autoSkipSaid = false
private async manageContext(signal: AbortSignal): Promise<"stop" | void> {
const window = contextWindow(this.model)
// Spec 3.4.0 §9: a subagent of the tree does not compact; at pause_at it is paused instead.
@@ -630,11 +723,20 @@ export class Engine {
}
return
}
// Nowhere to ask for the summary (an interactive-only model with no twin and no usable
// default): skipped, said once, and the turn goes on (interactive.md §3).
// A skipped attempt is not an attempt: it does not count toward "compacted twice".
const where = this.o.background?.("auto_compaction", used)
if (where && !("client" in where)) {
if (!this.autoSkipSaid) this.o.bus.emit({ type: "notice", message: `context at ${Math.round((used / window) * 100)}% of ${window}, and not compacted: this session's model is for interactive use only and there is no other model to ask for the summary — switch model (/model), or start a new session` })
this.autoSkipSaid = true
return
}
this.autoCompactions++
this.o.bus.emit({ type: "notice", level: "info", message: `context at ${Math.round((used / window) * 100)}% of ${window}: compacting the conversation` })
this.progress.set({ phase: "compacting" })
try {
await this.summarise(signal)
await this.summarise(signal, "auto_compaction")
// The task is never left to the summary: the prompt that started this turn comes back word
// for word (found on a real run, where a small model's summary lost the task entirely).
// Its note is not: what it said may be out of date, and the new prompt's first user message
@@ -700,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. */
@@ -707,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
@@ -735,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. */
@@ -753,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
}
@@ -786,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
}
@@ -801,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"
}
@@ -951,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 })
+151
View File
@@ -0,0 +1,151 @@
// The model last used in a directory (harness acp.md, spec 3.9.0): one model per directory,
// remembered on this machine and nowhere else — not in the project, not in a session, not on the
// server — so that a new session in a directory starts on what was last used there, wherever it
// is started from. The rules are three small functions (conformance/last_model.json); the rest is
// one file in the state directory.
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
import { stat } from "node:fs/promises"
import { dirname, join, resolve } from "node:path"
import { paths } from "../config/paths.ts"
import { realPath } from "../permission/evaluate.ts"
export type StartSource = "asked" | "project" | "directory" | "global" | "default"
/** Which model a session of this device's own starts on: the first source that names one. Only
* the directory's is checked against what the login serves now — a model that has gone is
* skipped, silently; the others are taken as written, and a wrong one is theirs to report. */
export function startModel(o: { asked?: string; project?: string; directory?: string; global?: string; served: readonly string[]; default?: string }): { model: string | undefined; from: StartSource } {
if (o.asked) return { model: o.asked, from: "asked" }
if (o.project) return { model: o.project, from: "project" }
if (o.directory && o.served.includes(o.directory)) return { model: o.directory, from: "directory" }
if (o.global) return { model: o.global, from: "global" }
return { model: o.default, from: "default" }
}
export type SessionKind = "terminal" | "link" | "stdio" | "run" | "scheduled"
/** Whether something makes the session's model the directory's: a turn a person started, or the
* person changing the model — of the main agent, and never in a one-shot run or a session a
* schedule opened. `machine`: it happens in a turn the harness started (the turn itself, or a
* change made inside it — a model's own settings call is not the person's choice there). */
export function records(o: { session: SessionKind; agent: "main" | "subagent"; what: "turn" | "change" | "command"; machine?: boolean }): boolean {
if (o.agent !== "main" || o.session === "run" || o.session === "scheduled") return false
if (o.what === "command") return false
return o.machine !== true
}
/** The client's rule (LLeMbas applies it; kept here so both suites answer the same cases): the
* model a new agent chat on a device and directory, or a schedule's run there, starts on. */
export function clientModel(o: { named?: string; directory?: string; has: readonly string[]; default?: string; scheduled?: boolean; interactive_only?: readonly string[] }): { model: string | undefined; from: "named" | "directory" | "default" } {
if (o.named) return { model: o.named, from: "named" }
// A schedule's run never starts on an interactive-only model the directory remembers (interactive.md §2).
const usable = o.scheduled ? o.has.filter((m) => !(o.interactive_only ?? []).includes(m)) : o.has
if (o.directory && usable.includes(o.directory)) return { model: o.directory, from: "directory" }
return { model: o.default, from: "default" }
}
/** At most this many directories are kept; the ones used longest ago go first. */
export const MAX_DIRECTORIES = 500
/** A directory's model is written again — its time refreshed — when it was last used longer ago
* than this, so "used longest ago" is true to about an hour without a write every turn. */
export const REFRESH_MS = 60 * 60 * 1000
/** Directories that are gone are looked for at most this often, and never on a turn's path. */
export const PRUNE_EVERY_MS = 24 * 60 * 60 * 1000
/** How long one directory's stat may take before it is left alone (a hung mount). */
const STAT_TIMEOUT_MS = 300
interface Entry {
model: string
/** When it was last used, ms since the epoch (to REFRESH_MS). */
at: number
}
interface File {
version: 1
directories: Record<string, Entry>
/** When gone directories were last looked for. */
pruned?: number
}
/** `models.json` in the state directory (local mode: the local root's). */
export const lastModelFile = (): string => join(paths.state, "models.json")
/** A directory as the memory names it: absolute, symlinks followed, no trailing slash. */
export function directoryKey(dir: string): string {
return realPath(resolve(dir))
}
function read(): File {
try {
const v = JSON.parse(readFileSync(lastModelFile(), "utf8")) as File
if (v && typeof v === "object" && v.directories && typeof v.directories === "object") return { version: 1, directories: v.directories, ...(typeof v.pruned === "number" ? { pruned: v.pruned } : {}) }
} catch {}
return { version: 1, directories: {} }
}
/** The model last used in exactly `dir`, or undefined. Never a parent's, never a child's. */
export function lastModel(dir: string): string | undefined {
const e = read().directories[directoryKey(dir)]
return e && typeof e.model === "string" && e.model ? e.model : undefined
}
/** Every remembered directory's model, for many lookups at once (a listing). */
export function lastModels(): (dir: string) => string | undefined {
const all = read().directories
return (dir) => {
const e = all[directoryKey(dir)]
return e && typeof e.model === "string" && e.model ? e.model : undefined
}
}
function write(file: File) {
const path = lastModelFile()
if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
const tmp = `${path}.${process.pid}.tmp`
writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 })
renameSync(tmp, path)
}
/** Make `ref` the model of `dir`, or mark it used again. The file is read, changed and renamed
* into place: a reader never sees half a file, and nothing is locked — of two sessions writing
* in the same instant the later rename wins and the other's entry is written again at its next
* turn. Nothing here looks at the file system beyond the one file (no stat of the remembered
* directories: `pruneGone` does that, off the turn's path); over the cap, the ones used longest
* ago go. A failure is nobody's problem: the memory is a convenience, never in a turn's way. */
export function rememberModel(dir: string, ref: string, now = Date.now()): void {
if (!ref) return
try {
const key = directoryKey(dir)
const file = read()
const had = file.directories[key]
if (had?.model === ref && now - (had.at ?? 0) < REFRESH_MS) return
file.directories[key] = { model: ref, at: now }
const kept = Object.entries(file.directories)
.filter(([, e]) => e && typeof e.model === "string")
.sort((a, b) => (b[1].at ?? 0) - (a[1].at ?? 0))
.slice(0, MAX_DIRECTORIES)
write({ version: 1, directories: Object.fromEntries(kept), ...(file.pruned ? { pruned: file.pruned } : {}) })
if (now - (file.pruned ?? 0) >= PRUNE_EVERY_MS) void pruneGone(now)
} catch {}
}
/** Drop the directories that no longer exist. Asynchronous and unhurried: each is asked for with
* a short wait, and one that does not answer in time (a hung network mount) or fails for any
* reason but "not there" is kept. The file is read again before it is written, so what was
* remembered meanwhile stays. */
export async function pruneGone(now = Date.now()): Promise<string[]> {
const gone: string[] = []
try {
for (const dir of Object.keys(read().directories)) {
const there = await Promise.race([
stat(dir).then((s) => s.isDirectory(), (e: NodeJS.ErrnoException) => (e?.code === "ENOENT" || e?.code === "ENOTDIR" ? false : true)),
new Promise<true>((done) => setTimeout(() => done(true), STAT_TIMEOUT_MS).unref?.()),
])
if (!there) gone.push(dir)
}
const file = read()
for (const dir of gone) delete file.directories[dir]
write({ version: 1, directories: file.directories, pruned: now })
} catch {}
return gone
}
+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`
}
+7
View File
@@ -69,6 +69,13 @@ CREATE TABLE IF NOT EXISTS session_meta (
* acp/agent.ts, which re-exports it). Here, so the app can ask it too without importing the
* agent, which imports the app. */
export const REMOTE_META = "remote"
/** Meta: a schedule opened this session for its run (harness acp.md, *Scheduled work*) — how it
* was opened (its notify-when among it). Kept so that, opened from the store again, it still
* never becomes its directory's model and is still offered report_write. */
export const SCHEDULED_META = "scheduled"
/** Meta: the model a schedule's session is on, kept so that a continuing schedule's session
* opened from the store again is on its own model — not on whatever a new session would start on. */
export const SCHEDULED_MODEL_META = "scheduled_model"
/** The session_meta key holding the directory a session was started in: a session started
* in a subdirectory of its project is reopened there, not at the project's root. */
+2 -5
View File
@@ -514,7 +514,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
const sendAs = async (prompt: string, shown: string, opts: { model?: string; mode?: string; attachFrom?: string; given?: Parameters<typeof send>[3] } = {}) => {
const prev = { model: app.engine.model.ref, mode: app.engine.mode, effort: app.engine.effort }
try {
if (opts.model) app.switchModel(opts.model)
if (opts.model) app.switchModel(opts.model, "borrowed")
if (opts.mode && (MODES as readonly string[]).includes(opts.mode)) app.engine.mode = opts.mode as Mode
refresh()
return await send(prompt, shown, opts.attachFrom ?? prompt, opts.given)
@@ -523,10 +523,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
return "error"
} finally {
// The effort as it was too: switching back would set the model's default.
if (opts.model) {
app.switchModel(prev.model)
app.engine.effort = prev.effort
}
if (opts.model) app.returnModel(prev)
app.engine.mode = prev.mode
refresh()
}
+5 -3
View File
@@ -234,7 +234,7 @@ export const COMMANDS: Command[] = [
options: refs.map((r) => {
const known = c.app.loaded.refs.find((x) => x.ref === r)!
const spec = c.app.loaded.connections[known.connection]!.models[known.id]!
const bits = [spec.context ? `${Math.round(spec.context / 1024)}k ctx` : "", spec.vision ? "vision" : "", levelsFor(c.app.engine.model.ref === r ? c.app.engine.model : { ...c.app.engine.model, ref: r, spec }).control === "switch" ? "thinking switch" : spec.efforts?.length ? "effort" : ""].filter(Boolean).join(" · ")
const bits = [spec.context ? `${Math.round(spec.context / 1024)}k ctx` : "", spec.vision ? "vision" : "", levelsFor(c.app.engine.model.ref === r ? c.app.engine.model : { ...c.app.engine.model, ref: r, spec }).control === "switch" ? "thinking switch" : spec.efforts?.length ? "effort" : "", spec.interactive_only ? "interactive use only" : ""].filter(Boolean).join(" · ")
return { label: r, value: r, description: bits, current: r === c.app.engine.model.ref }
}),
onSelect: pick,
@@ -1112,8 +1112,10 @@ export const COMMANDS: Command[] = [
c.openDialog({
title: preview[0]!,
options: [
{ label: "Create it", value: "server", description: preview.slice(1).join(" · ") || "runs on the server" },
...(here ? [{ label: "Create it, to run on this computer", value: "here", description: `as an agent turn in ${cwd}, in Edit` }] : []),
// The two types (harness acp.md, spec 3.9.0). An Agentic one names no model: each run
// uses the model last used in this directory.
{ label: "Create it — Chat", value: "server", description: preview.slice(1).join(" · ") || "runs on the server" },
...(here ? [{ label: "Create it — Agentic, to run on this computer", value: "here", description: `as an agent turn in ${cwd}, in Edit, on the model last used here` }] : []),
{ label: "Cancel", value: "cancel" },
],
onSelect: (v) => {
+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"])
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 })
+30
View File
@@ -38,6 +38,11 @@ import { checkMode, requestRefusal, tighten, whoDecides, type Grant } from "../s
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>
/** Whether a path is at `ro` or above under `grants` (fs_access's rule: the most specific grant on
@@ -53,6 +58,31 @@ 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)
if (c.kind === "start") return startModel({ asked: str("asked"), project: str("project"), directory: str("directory"), global: str("global"), served: c.served as string[], default: str("default") })
if (c.kind === "record") return records({ session: c.session as SessionKind, agent: c.agent as "main" | "subagent", what: c.what as "turn" | "change" | "command", machine: c.machine === true })
if (c.kind === "client") return clientModel({ named: str("named"), directory: str("directory"), has: c.has as string[], default: str("default"), scheduled: c.scheduled === true, interactive_only: c.interactive_only as string[] | undefined })
throw new Error(`last_model: unknown kind ${String(c.kind)}`)
},
// Spec 3.9.0: interactive-only models (src/provider/interactive.ts).
interactive: (c) => {
const models = c.models as Listed[]
if (c.kind === "twin") return twin(c.model as string, models) ?? null
if (c.kind === "background") return background({ model: c.model as string, models, defaults: c.defaults as string[], call: c.call as BackgroundCall, unfit: c.unfit as string[] | undefined })
if (c.kind === "scheduled") {
const refused = scheduledRefusal(c.model as string, models)
return refused ? { refused } : { run: true }
}
throw new Error(`interactive: unknown kind ${String(c.kind)}`)
},
// Spec 3.5.0: scheduled work on a linked computer (src/acp/scheduled.ts).
scheduled: (c) => scheduledMode({ accept: c.accept === true, mode: c.mode, max_mode: c.max_mode as Mode, approval_wait_s: c.approval_wait_s }),
silent: (c) => ({ silent: isSilent(c.text as string), stripped: stripSentinel(c.text as string) }),
+29
View File
@@ -2,6 +2,7 @@
// ACP client on one side of the agent; a terminal's App and its Share are on the other, through a
// real Unix socket.
import { afterEach, expect, test } from "bun:test"
import { LOOP } from "../src/harness.ts"
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
@@ -507,3 +508,31 @@ test("a delete waits out another process's write instead of failing as locked",
expect(store.deleteSession(s.id)).toBe(true)
await child.exited
})
test("a schedule's run for a session open in a terminal is refused, never run there as a person's turn", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "typed here" })] }])
const root = project()
config(fake.url, "mode: edit\n")
const scheduled = { schedule_id: "sched1", run_id: "run7", title: "Check" }
const say = (id: string) => ({ sessionId: id, prompt: [{ type: "text", text: "check" }], _meta: { lembas: { turnId: "run7", scheduled } } })
const refusal = (p: Promise<unknown>) => p.then(() => undefined, (e) => ({ message: (e as Error).message, data: (e as { data?: unknown }).data }))
const { web, heard } = await linked(limitsFor(root, { enabled: true, scheduled: true }))
const { app } = await terminal(root)
const id = app.engine.sessionId!
await until(() => heard.some((h) => h.method === "_lembas/session/announce"), "the announcement")
expect(await refusal(web.request("session/prompt", say(id)))).toEqual({ message: LOOP.scheduled.texts.terminal, data: { reason: "terminal" } })
// Nothing was run in the terminal, and nothing was asked of a model.
expect(app.engine.messages).toHaveLength(0)
expect(fake.requests).toHaveLength(0)
})
test("…and with scheduled work off on the device, that refusal comes first", async () => {
fake = fakeProvider([])
const root = project()
config(fake.url, "mode: edit\n")
const { web, heard } = await linked(limitsFor(root, { enabled: true, scheduled: false }))
const { app } = await terminal(root)
await until(() => heard.some((h) => h.method === "_lembas/session/announce"), "the announcement")
const p = web.request("session/prompt", { sessionId: app.engine.sessionId!, prompt: [{ type: "text", text: "check" }], _meta: { lembas: { turnId: "run7", scheduled: { schedule_id: "sched1", run_id: "run7", title: "Check" } } } })
expect(await p.then(() => undefined, (e) => (e as { data?: unknown }).data)).toEqual({ reason: "scheduled_off" })
})
+331
View File
@@ -0,0 +1,331 @@
// Interactive-only models (harness spec 3.9.0, interactive.md): the field as the server sends it,
// scheduled work that never runs on such a model, and a session's background calls — its title,
// its compaction — asked of another model. A fake LLeMbas is the client; the model is a scripted
// endpoint that records which model each request named.
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent, type Limits } from "../src/acp/agent.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { createApp, InteractiveOnlyError } from "../src/app.ts"
import { paths } from "../src/config/paths.ts"
import { LOOP } from "../src/harness.ts"
import { nobodyAtIt, RUN_HINT } from "../src/provider/interactive.ts"
import { specFor } from "../src/lembas/webui.ts"
import { setTrust } from "../src/project/root.ts"
import { rememberModel, lastModelFile } from "../src/session/lastmodel.ts"
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
let fake: Fake | undefined
const closing: (() => unknown)[] = []
afterEach(async () => {
for (const c of closing.splice(0)) await c()
fake?.stop()
rmSync(lastModelFile(), { force: true })
})
/** A plan's model, its pay-as-you-go twin, and one more — or without the twin. */
function config(url: string, o: { model?: string; twin?: boolean; other?: boolean; extra?: string; window?: number; twinWindow?: number; otherTools?: boolean } = {}) {
mkdirSync(paths.config, { recursive: true })
const models = [`plan/coder: { interactive_only: true${o.window ? `, context: ${o.window}` : ""} }`, "plan/max: { interactive_only: true }", ...(o.twin === false ? [] : [`payg/coder: {${o.twinWindow ? ` context: ${o.twinWindow} ` : ""}}`]), ...(o.other === false ? [] : [`open/flash: {${o.otherTools === false ? " tools: false " : ""}}`])]
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${url}\n models:\n${models.map((m) => ` ${m}`).join("\n")}\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), `model: ${o.model ?? "plan/coder"}\n${o.extra ?? ""}`)
}
function project(): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-interactive-")))
Bun.spawnSync(["git", "init", "-q", dir])
setTrust(dir, "trusted")
return dir
}
const asker = { ask: async () => ({ action: "deny" as const }) } as never
function app(cwd: string, extra: Record<string, unknown> = {}) {
const a = createApp({ cwd, asker, snapshots: false, ...extra })
closing.push(() => a.close())
return a
}
const reply = (text = "ok") => ({ chunks: [delta({ content: text })] })
const asked = () => fake!.requests.map((r) => r.model as string)
const SENTENCE = (model: string) => LOOP.interactive.texts.scheduled.replace("{{model}}", model)
test("the field: read from /v1/models only when the server says true", () => {
expect(specFor({ id: "plan/coder", interactive_only: true }, "f").interactive_only).toBe(true)
expect("interactive_only" in specFor({ id: "payg/coder" }, "f")).toBe(false)
expect("interactive_only" in specFor({ id: "payg/coder", interactive_only: false }, "f")).toBe(false)
})
test("a person's turn runs on the interactive-only model; its title is asked of the twin", async () => {
fake = fakeProvider([reply("Hello."), reply("A greeting")])
config(fake.url)
const a = app(project())
const notices: string[] = []
a.bus.on((e) => e.type === "notice" && notices.push(e.message))
await a.turns.prompt("hello there")
for (let i = 0; i < 100 && fake.requests.length < 2; i++) await Bun.sleep(10)
expect(asked()).toEqual(["plan/coder", "payg/coder"])
expect(notices.filter((n) => n.includes("title is asked of payg/coder"))).toHaveLength(1)
})
test("no twin: the title goes to the default that is not interactive-only; with none, it is not asked for at all", async () => {
fake = fakeProvider([reply("Hello."), reply("A greeting")])
// The session is on plan/max (asked for); the global setting is a model that may take it.
config(fake.url, { model: "open/flash" })
const a = app(project(), { model: "plan/max" })
await a.turns.prompt("hello there")
for (let i = 0; i < 100 && fake.requests.length < 2; i++) await Bun.sleep(10)
expect(asked()).toEqual(["plan/max", "open/flash"])
fake.stop()
fake = fakeProvider([reply("Hello.")])
config(fake.url, { twin: false, other: false })
const root = project()
const b = app(root)
await b.turns.prompt("hello there")
await Bun.sleep(150)
expect(asked()).toEqual(["plan/coder"])
// The name made from the first prompt stays.
expect(b.store!.session(b.engine.sessionId!)!.title).toBe("hello there")
})
test("compaction the person asks for is the twin's work, and the session stays on its model", async () => {
fake = fakeProvider([reply("Hello."), reply("We said hello."), reply("Carrying on.")])
config(fake.url)
const a = app(project(), { modelTitles: false })
await a.turns.prompt("hello there")
const notices: string[] = []
a.bus.on((e) => e.type === "notice" && notices.push(e.message))
expect(await a.engine.compact()).toContain("We said hello.")
expect(a.engine.model.ref).toBe("plan/coder")
// The model that was asked is named, and its tokens are counted under it.
expect(notices.filter((n) => n.includes("the summary is asked of payg/coder"))).toHaveLength(1)
expect(a.store!.requests(a.engine.sessionId!).map((r) => `${r.kind} ${r.model}`)).toEqual(["step plan/coder", "compaction payg/coder"])
await a.turns.prompt("and now?")
expect(asked()).toEqual(["plan/coder", "payg/coder", "plan/coder"])
})
test("with nowhere to go, compaction asked for is refused in the spec's words and nothing is sent", async () => {
fake = fakeProvider([reply("Hello.")])
config(fake.url, { twin: false, other: false })
const a = app(project(), { modelTitles: false })
await a.turns.prompt("hello there")
await expect(a.engine.compact()).rejects.toThrow(LOOP.interactive.texts.compact)
expect(asked()).toEqual(["plan/coder"])
expect(a.engine.messages.length).toBeGreaterThan(1)
})
test("automatic compaction with nowhere to go is skipped, said once, and the turn goes on", async () => {
const long = "word ".repeat(2500)
fake = fakeProvider([{ chunks: [delta({ content: long })] }, reply("Second."), reply("Third.")])
// A window the system prompt alone overflows: every step is past the automatic threshold.
config(fake.url, { twin: false, other: false, window: 2000 })
const a = app(project(), { modelTitles: false })
const notices: string[] = []
a.bus.on((e) => e.type === "notice" && notices.push(e.message))
await a.turns.prompt("one")
await a.turns.prompt("two")
await a.turns.prompt("three")
expect(asked()).toEqual(["plan/coder", "plan/coder", "plan/coder"])
expect(notices.filter((n) => n.includes("interactive use only"))).toHaveLength(1)
expect(notices.some((n) => n.includes("compacting the conversation"))).toBe(false)
})
test("automatic compaction with a twin is the twin's work", async () => {
fake = fakeProvider([reply("First."), reply("A summary of it."), reply("Second.")])
config(fake.url, { window: 2000 })
const a = app(project(), { modelTitles: false })
await a.turns.prompt("one")
await a.turns.prompt("two")
expect(asked().slice(0, 3)).toEqual(["plan/coder", "payg/coder", "plan/coder"])
expect(a.engine.model.ref).toBe("plan/coder")
})
test("a subagent's own automatic compaction goes the same way: the twin's work; with nowhere to go, skipped and said once to the session", async () => {
const task = { chunks: [toolCall(0, "t1", "task", JSON.stringify({ agent: "general", description: "look", prompt: "look around" }))] }
const step = { chunks: [toolCall(0, "g1", "glob", JSON.stringify({ pattern: "*" }))] }
fake = fakeProvider([task, step, reply("The subagent's summary."), reply("Found nothing."), reply("The session's summary."), reply("Done.")])
config(fake.url, { window: 2000 })
const a = app(project(), { modelTitles: false, mode: "auto" })
await a.turns.prompt("have a subagent look")
// The session's step, the subagent's first, its summary on the twin, its second, then the
// session's own summary on the twin and its reply.
expect(asked()).toEqual(["plan/coder", "plan/coder", "payg/coder", "plan/coder", "payg/coder", "plan/coder"])
fake.stop()
fake = fakeProvider([task, step, reply("Found nothing."), reply("Done.")])
config(fake.url, { twin: false, other: false, window: 2000 })
const b = app(project(), { modelTitles: false, mode: "auto" })
const notices: string[] = []
b.bus.on((e) => e.type === "notice" && notices.push(e.message))
await b.turns.prompt("have a subagent look")
expect(asked()).toEqual(["plan/coder", "plan/coder", "plan/coder", "plan/coder"])
expect(notices.filter((n) => n.includes("the subagent general is not compacting"))).toHaveLength(1)
})
test("a model that cannot take the summary is nowhere to go: a twin with too small a window and a default without tools", async () => {
fake = fakeProvider([reply("Hello.")])
// The twin's window is far below the conversation; the default takes no tools.
config(fake.url, { twinWindow: 50, otherTools: false })
const a = app(project(), { modelTitles: false })
await a.turns.prompt("hello there")
await expect(a.engine.compact()).rejects.toThrow(LOOP.interactive.texts.compact)
expect(asked()).toEqual(["plan/coder"])
})
test("what a schedule's session does when no person's turn runs is the schedule's: a subagent, a turn a job wakes", async () => {
fake = fakeProvider([])
config(fake.url, { model: "open/flash" })
const a = app(project(), { kind: "scheduled", modelTitles: false })
// Between turns the session's model is changed to the plan's (as a person may in the run's chat).
a.chooseModel("plan/coder")
const notices: string[] = []
a.bus.on((e) => e.type === "notice" && notices.push(e.message))
// A subagent started with no turn running — one of the run's jobs carrying on — is the run's.
await expect(a.engine.o.spawn!("general", "look around", { description: "look", background: true } as never)).rejects.toThrow(SENTENCE("plan/coder"))
// A turn a job's note would wake is not started on it.
a.wake("[job j1 finished]", "[job j1 finished]")
await Bun.sleep(50)
expect(fake.requests).toHaveLength(0)
expect(notices.filter((n) => n.includes(SENTENCE("plan/coder")))).toHaveLength(1)
})
test("a one-shot run with no terminal at all is scheduled work; any terminal makes it a person's", () => {
expect(nobodyAtIt({ stdin: false, stdout: false, stderr: false })).toBe(true)
expect(nobodyAtIt({})).toBe(true)
// A prompt piped in at a terminal, output redirected: stderr is still the terminal.
expect(nobodyAtIt({ stdin: false, stdout: false, stderr: true })).toBe(false)
expect(nobodyAtIt({ stdin: true, stdout: false, stderr: false })).toBe(false)
})
test("lembas run with no terminal refuses an interactive-only model, and says the way forward", async () => {
fake = fakeProvider([reply("Hi.")])
config(fake.url)
const dir = project()
const run = async (...args: string[]) => {
const p = Bun.spawn(["bun", join(import.meta.dir, "../src/cli.ts"), "run", "--no-store", ...args, "hello"], { cwd: dir, env: { ...process.env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" })
const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited])
return { out, err, code }
}
const no = await run()
expect(no.code).toBe(1)
expect(no.err).toContain(SENTENCE("plan/coder"))
expect(no.err).toContain(RUN_HINT)
expect(fake.requests).toHaveLength(0)
// The way forward it names works.
const yes = await run("-m", "open/flash")
expect(yes.code).toBe(0)
expect(yes.out).toBe("Hi.\n")
}, 60_000)
// ── scheduled work ──────────────────────────────────────────────────────────────────────────
test("scheduled work never starts on one: asked for, it is refused; remembered for the directory, it is skipped", () => {
fake = fakeProvider([])
config(fake.url, { model: "open/flash" })
const root = project()
expect(() => app(root, { model: "plan/coder", automated: true })).toThrow(SENTENCE("plan/coder"))
expect(() => app(root, { model: "plan/coder", automated: true })).toThrow(InteractiveOnlyError)
rememberModel(root, "plan/coder")
expect(app(root, { automated: true }).engine.model.ref).toBe("open/flash")
// A person's session there starts on it.
expect(app(root).engine.model.ref).toBe("plan/coder")
// And scheduled work cannot switch to one.
const a = app(root, { automated: true })
expect(() => a.switchModel("plan/max")).toThrow(SENTENCE("plan/max"))
expect(a.engine.model.ref).toBe("open/flash")
})
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, other: typeof a): Transport => ({
send: (t) => queueMicrotask(() => other.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), other.end()),
})
return [side(a, b), side(b, a)]
}
const limitsFor = (root: string): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true })
async function client(limits: Limits) {
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limits, "f")
const c = new Peer(tb)
c.on("_lembas/event", () => {})
c.on("session/update", () => {})
c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
return c
}
const refusal = async (p: Promise<unknown>) => p.then(() => undefined, (e) => ({ message: (e as Error).message, data: (e as { data?: unknown }).data }))
const scheduled = { schedule_id: "sched1", run_id: "run7", title: "Check" }
const say = (sessionId: string, text: string, lembas: Record<string, unknown> = {}) => ({ sessionId, prompt: [{ type: "text", text }], _meta: { lembas } })
test("a scheduled session on an interactive-only model is refused by the device, with the sentence and the reason; an agent chat on it is not", async () => {
fake = fakeProvider([reply("Hello.")])
config(fake.url, { model: "open/flash" })
const root = project()
const c = await client(limitsFor(root))
const no = await refusal(c.request("session/new", { cwd: root, _meta: { lembas_model: "plan/coder", lembas: { scheduled } } }))
expect(no).toEqual({ message: SENTENCE("plan/coder"), data: { reason: "interactive_only" } })
expect(fake.requests).toHaveLength(0)
// A person's agent chat on the same model: theirs to use.
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "plan/coder" } })
expect(s._meta.lembas.model).toBe("plan/coder")
await c.request("session/prompt", say(s.sessionId, "hello"))
expect(asked()).toEqual(["plan/coder"])
})
test("a continuing schedule whose session has since come to be on one: the scheduled turn is refused before anything is sent, the person's own turn runs", async () => {
fake = fakeProvider([reply("Checked."), reply("It was fine.")])
config(fake.url, { model: "open/flash" })
const root = project()
const c = await client(limitsFor(root))
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "open/flash", lembas: { scheduled } } })
await c.request("session/prompt", say(s.sessionId, "check", { scheduled, turnId: "run7" }))
// Between runs the chat's model is changed to the plan's.
await c.request("_lembas/configure", { sessionId: s.sessionId, model: "plan/coder" })
const no = await refusal(c.request("session/prompt", say(s.sessionId, "check", { scheduled: { ...scheduled, run_id: "run8" }, turnId: "run8" })))
expect(no).toEqual({ message: SENTENCE("plan/coder"), data: { reason: "interactive_only" } })
expect(asked()).toEqual(["open/flash"])
await c.request("session/prompt", say(s.sessionId, "what did you find?"))
expect(asked()).toEqual(["open/flash", "plan/coder"])
})
test("a scheduled run's subagent is not started on one: the call answers the sentence and the run goes on", async () => {
fake = fakeProvider([
{ chunks: [toolCall(0, "t1", "task", JSON.stringify({ agent: "general", description: "look", prompt: "look around", model: "plan/coder" }))] },
reply("Done without it."),
])
config(fake.url, { model: "open/flash" })
const root = project()
const c = await client(limitsFor(root))
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "open/flash", lembas: { scheduled: { ...scheduled, mode: "auto" } } } })
const r: any = await c.request("session/prompt", say(s.sessionId, "use plan/coder for a subagent and check", { scheduled: { ...scheduled, mode: "auto" }, turnId: "run7" }))
expect(r._meta.lembas.scheduled.status).toBe("ok")
expect(asked()).toEqual(["open/flash", "open/flash"])
const result = JSON.stringify(fake.requests[1].messages.at(-1))
expect(result).toContain("for interactive use only")
})
test("a command's own model in a scheduled prompt, when it is interactive-only: the same refusal with its reason, and the session is as it was", async () => {
fake = fakeProvider([reply("It was fine.")])
config(fake.url, { model: "open/flash" })
const root = project()
mkdirSync(join(root, ".agent", "commands"), { recursive: true })
writeFileSync(join(root, ".agent", "config.yaml"), "")
writeFileSync(join(root, ".agent", "commands", "quick.md"), "---\nmodel: plan/coder\n---\nQuick.")
const c = await client(limitsFor(root))
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "open/flash", lembas: { scheduled } } })
const no = await refusal(c.request("session/prompt", say(s.sessionId, "/quick", { scheduled, turnId: "run7" })))
expect(no).toEqual({ message: SENTENCE("plan/coder"), data: { reason: "interactive_only" } })
expect(fake.requests).toHaveLength(0)
// The person's own turn afterwards runs, on the session's model.
await c.request("session/prompt", say(s.sessionId, "what happened?"))
expect(asked()).toEqual(["open/flash"])
})
+365
View File
@@ -0,0 +1,365 @@
// The model last used in a directory (harness spec 3.9.0, acp.md): the file on this machine, how a
// session starts from it, what writes it and what never does, and what `_lembas/directories` says
// of it. A fake LLeMbas is the client; the model is a scripted endpoint.
import { afterEach, beforeEach, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent, type Limits } from "../src/acp/agent.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { createApp } from "../src/app.ts"
import { paths, setLocalRoot } from "../src/config/paths.ts"
import { setTrust } from "../src/project/root.ts"
import { directoryKey, lastModel, lastModelFile, MAX_DIRECTORIES, pruneGone, REFRESH_MS, rememberModel } from "../src/session/lastmodel.ts"
import { SCHEDULED_META } from "../src/session/store.ts"
import { plan } from "../src/uninstall.ts"
import { delta, fakeProvider, type Fake } from "./fake-provider.ts"
let fake: Fake | undefined
const closing: (() => unknown)[] = []
beforeEach(() => rmSync(lastModelFile(), { force: true }))
afterEach(async () => {
for (const c of closing.splice(0)) await c()
fake?.stop()
rmSync(lastModelFile(), { force: true })
})
function config(url: string, model: string | undefined = "f/m") {
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${url}\n models: { f/m: {}, f/big: {}, f/small: {} }\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), model ? `model: ${model}\n` : "")
}
function project(): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-lastmodel-")))
Bun.spawnSync(["git", "init", "-q", dir])
setTrust(dir, "trusted")
return dir
}
const asker = { ask: async () => ({ action: "deny" as const }) } as never
function app(cwd: string, extra: Record<string, unknown> = {}) {
const a = createApp({ cwd, asker, snapshots: false, modelTitles: false, ...extra })
closing.push(() => a.close())
return a
}
const reply = (text = "ok") => ({ chunks: [delta({ content: text })] })
// ── the file ────────────────────────────────────────────────────────────────────────────────
test("one model per directory: exactly that directory, never its parent's nor its child's", () => {
const root = project()
const sub = join(root, "sub")
mkdirSync(join(sub, "deeper"), { recursive: true })
rememberModel(sub, "f/big")
expect(lastModel(sub)).toBe("f/big")
expect(lastModel(root)).toBeUndefined()
expect(lastModel(join(sub, "deeper"))).toBeUndefined()
// A trailing slash and a link name the same directory.
expect(lastModel(`${sub}/`)).toBe("f/big")
symlinkSync(sub, join(root, "link"))
expect(directoryKey(join(root, "link"))).toBe(sub)
expect(lastModel(join(root, "link"))).toBe("f/big")
rememberModel(sub, "f/small")
expect(lastModel(sub)).toBe("f/small")
})
test("the file is this machine's: in the state directory, private, and nowhere in the project", () => {
const root = project()
rememberModel(root, "f/big")
expect(lastModelFile()).toBe(join(paths.state, "models.json"))
expect(statSync(lastModelFile()).mode & 0o777).toBe(0o600)
expect(JSON.parse(readFileSync(lastModelFile(), "utf8"))).toMatchObject({ version: 1, directories: { [root]: { model: "f/big" } } })
expect(existsSync(join(root, ".agent"))).toBe(false)
})
test("a write looks at no directory; the gone ones are dropped apart from it, and what cannot be looked at is kept", async () => {
const root = project()
const gone = join(root, "gone")
mkdirSync(gone)
rememberModel(gone, "f/big", 1)
rmSync(gone, { recursive: true })
const dirs = Array.from({ length: 3 }, (_, i) => join(root, `d${i}`))
for (const d of dirs) mkdirSync(d)
dirs.forEach((d, i) => rememberModel(d, "f/m", 10 + i))
const kept = () => Object.keys(JSON.parse(readFileSync(lastModelFile(), "utf8")).directories).sort()
// The gone one is still there after three writes: writing stats nothing.
expect(kept()).toEqual([...dirs, gone].sort())
expect(await pruneGone(100)).toEqual([gone])
expect(kept()).toEqual(dirs)
expect(JSON.parse(readFileSync(lastModelFile(), "utf8")).pruned).toBe(100)
expect(MAX_DIRECTORIES).toBe(500)
// A broken file is no memory, and is written over.
writeFileSync(lastModelFile(), "{ not json")
expect(lastModel(dirs[0]!)).toBeUndefined()
rememberModel(dirs[0]!, "f/big")
expect(lastModel(dirs[0]!)).toBe("f/big")
})
test("a directory's time is refreshed as it is used, within the hour not rewritten: the ones used longest ago are the ones that go", () => {
const root = project()
const at = () => JSON.parse(readFileSync(lastModelFile(), "utf8")).directories[root].at
rememberModel(root, "f/big", 1000)
rememberModel(root, "f/big", 1000 + REFRESH_MS - 1)
expect(at()).toBe(1000)
rememberModel(root, "f/big", 1000 + REFRESH_MS)
expect(at()).toBe(1000 + REFRESH_MS)
// Another model is written at once.
rememberModel(root, "f/small", 1000 + REFRESH_MS + 5)
expect(at()).toBe(1000 + REFRESH_MS + 5)
})
test("local mode keeps it in the local root; uninstall --purge takes it with the state, a plain one keeps it", () => {
const root = project()
rememberModel(root, "f/big")
const file = lastModelFile()
expect(plan({ purge: true, binary: join(root, "lembas") }).remove.some((d) => file.startsWith(`${d}/`))).toBe(true)
const plain = plan({ binary: join(root, "lembas") })
expect(plain.remove.some((d) => file.startsWith(`${d}/`))).toBe(false)
expect(plain.kept.some((d) => file.startsWith(`${d}/`))).toBe(true)
const local = join(root, ".lembas-local")
setLocalRoot(local)
try {
expect(lastModelFile()).toBe(join(local, "state", "models.json"))
expect(lastModel(root)).toBeUndefined()
} finally {
setLocalRoot(undefined)
}
})
// ── how a session starts ────────────────────────────────────────────────────────────────────
test("a session starts on the model last used in its directory, over the global setting", () => {
fake = fakeProvider([])
config(fake.url)
const root = project()
expect(app(root).engine.model.ref).toBe("f/m")
rememberModel(root, "f/big")
expect(app(root).engine.model.ref).toBe("f/big")
// Another directory is not this one — a subdirectory included.
mkdirSync(join(root, "sub"))
expect(app(join(root, "sub")).engine.model.ref).toBe("f/m")
expect(app(project()).engine.model.ref).toBe("f/m")
})
test("the model asked for and the project's setting come before it; a model no longer served is skipped and kept", () => {
fake = fakeProvider([])
config(fake.url)
const root = project()
rememberModel(root, "f/big")
expect(app(root, { model: "f/small" }).engine.model.ref).toBe("f/small")
mkdirSync(join(root, ".agent"))
writeFileSync(join(root, ".agent", "config.yaml"), "model: f/small\n")
expect(app(root).engine.model.ref).toBe("f/small")
rmSync(join(root, ".agent"), { recursive: true })
expect(app(root).engine.model.ref).toBe("f/big")
rememberModel(root, "f/withdrawn")
expect(app(root).engine.model.ref).toBe("f/m")
expect(lastModel(root)).toBe("f/withdrawn")
})
// ── what writes it ──────────────────────────────────────────────────────────────────────────
test("a person's turn makes the session's model the directory's; a turn the harness started does not", async () => {
fake = fakeProvider([reply(), reply()])
config(fake.url)
const root = project()
const a = app(root, { model: "f/big" })
// Starting is not using.
expect(lastModel(root)).toBeUndefined()
await a.turns.prompt("[job j1 finished]", [], "[job j1 finished]", { machine: true })
expect(lastModel(root)).toBeUndefined()
await a.turns.prompt("hello")
expect(lastModel(root)).toBe("f/big")
})
test("changing the model is remembered at once; a command's own model, borrowed for one prompt, is not", async () => {
fake = fakeProvider([reply(), reply()])
config(fake.url)
const root = project()
const a = app(root)
a.settings.set("model", "f/big")
expect(lastModel(root)).toBe("f/big")
a.switchModel("f/small", "borrowed")
await a.turns.prompt("a command's prompt")
expect(lastModel(root)).toBe("f/big")
a.switchModel("f/big")
a.chooseModel("f/small")
expect(lastModel(root)).toBe("f/small")
})
test("a session that does not remember — a one-shot run — starts on the directory's model and leaves it alone", async () => {
fake = fakeProvider([reply()])
config(fake.url)
const root = project()
rememberModel(root, "f/big")
const a = app(root, { model: "f/small", kind: "run" })
await a.turns.prompt("hello")
a.settings.set("model", "f/m")
expect(lastModel(root)).toBe("f/big")
expect(app(root, { kind: "run" }).engine.model.ref).toBe("f/big")
})
test("a command whose model is the session's own leaves nothing borrowed: the next prompt is remembered", async () => {
fake = fakeProvider([reply(), reply()])
config(fake.url)
const root = project()
const a = app(root, { model: "f/big" })
const prev = { model: a.engine.model.ref, effort: a.engine.effort }
a.switchModel("f/big", "borrowed")
await a.turns.prompt("a command's prompt")
expect(lastModel(root)).toBeUndefined()
a.returnModel(prev)
await a.turns.prompt("hello")
expect(lastModel(root)).toBe("f/big")
})
test("a change of model inside a turn the harness started is not remembered", async () => {
fake = fakeProvider([reply()])
config(fake.url)
const root = project()
const a = app(root)
const off = a.bus.on((e) => {
// What a model's settings call would do, mid-turn.
if (e.type === "prompt") a.settings.set("model", "f/big")
})
await a.turns.prompt("[job j1 finished]", [], "[job j1 finished]", { machine: true })
off()
expect(a.engine.model.ref).toBe("f/big")
expect(lastModel(root)).toBeUndefined()
})
test("a schedule's session opened in a terminal is still the schedule's: nothing in it is remembered, and a new session after it is the terminal's again", async () => {
fake = fakeProvider([reply(), reply()])
config(fake.url)
const root = project()
const a = app(root, { model: "f/big" })
const first = a.engine.sessionId!
a.newSession()
a.store!.setMeta(first, SCHEDULED_META, { scheduleId: "sched1", runId: "run7", title: "Check", mode: "edit", waitMs: 1000 })
a.resume(first)
await a.turns.prompt("what did the run find?")
a.settings.set("model", "f/small")
expect(lastModel(root)).toBeUndefined()
a.newSession()
await a.turns.prompt("hello")
expect(lastModel(root)).toBe("f/small")
})
// ── the link ────────────────────────────────────────────────────────────────────────────────
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, other: typeof a): Transport => ({
send: (t) => queueMicrotask(() => other.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), other.end()),
})
return [side(a, b), side(b, a)]
}
const limitsFor = (root: string, extra: Partial<Limits> = {}): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true, ...extra })
async function client(limits: Limits) {
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limits, "f")
const c = new Peer(tb)
c.on("_lembas/event", () => {})
c.on("session/update", () => {})
const init: any = await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
return { c, init }
}
const say = (sessionId: string, text: string, lembas: Record<string, unknown> = {}) => ({ sessionId, prompt: [{ type: "text", text }], _meta: { lembas } })
test("_lembas/directories says each directory's model, and `list: false` answers for one directory alone", async () => {
fake = fakeProvider([])
config(fake.url)
const home = realpathSync(mkdtempSync(join(tmpdir(), "ph-lastmodel-dirs-")))
const work = join(home, "project")
const notes = join(home, "notes")
for (const d of [join(work, "src"), notes]) mkdirSync(d, { recursive: true })
setTrust(home, "trusted")
rememberModel(work, "f/big")
const { c, init } = await client(limitsFor(home))
expect(init._meta.lembas.capabilities).toContain("directory_model")
const listed: any = await c.request("_lembas/directories", { path: home })
expect(listed.model).toBeUndefined()
expect(listed.entries).toEqual([
{ path: notes, name: "notes", accepted: true },
{ path: work, name: "project", accepted: true, model: "f/big" },
])
expect(await c.request<unknown>("_lembas/directories", { path: work, list: false })).toEqual({ path: work, name: "project", accepted: true, model: "f/big", parent: home })
expect(await c.request<unknown>("_lembas/directories", { path: notes, list: false })).toEqual({ path: notes, name: "notes", accepted: true, parent: home })
// Listed, the answered directory carries its own; a child does not inherit it.
const inside: any = await c.request("_lembas/directories", { path: work })
expect(inside.model).toBe("f/big")
expect(inside.entries).toEqual([{ path: join(work, "src"), name: "src", accepted: true }])
// The places too.
rememberModel(home, "f/small")
expect(((await c.request("_lembas/directories", {})) as any).places).toEqual([{ path: home, name: basenameOf(home), accepted: true, model: "f/small" }])
// `list: false` is still judged as any path.
await expect(c.request("_lembas/directories", { path: "/somewhere/else", list: false })).rejects.toThrow("outside the directories")
})
const basenameOf = (p: string) => p.split("/").pop()!
test("a directory no session may be opened in says no model", async () => {
fake = fakeProvider([])
config(fake.url)
const root = realpathSync(mkdtempSync(join(tmpdir(), "ph-lastmodel-untrusted-")))
rememberModel(root, "f/big")
const { c } = await client(limitsFor(root))
const one: any = await c.request("_lembas/directories", { path: root, list: false })
expect(one.accepted).toBe(false)
expect(one.model).toBeUndefined()
})
test("a chat's turn on the link makes its model the directory's, and so does a change of the chat's model", async () => {
fake = fakeProvider([reply()])
config(fake.url)
const root = project()
const { c } = await client(limitsFor(root))
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "f/big" } })
expect(lastModel(root)).toBeUndefined()
await c.request("session/prompt", say(s.sessionId, "hello"))
expect(lastModel(root)).toBe("f/big")
await c.request("_lembas/configure", { sessionId: s.sessionId, model: "f/small" })
expect(lastModel(root)).toBe("f/small")
// A session opened with no model starts on it.
const next: any = await c.request("session/new", { cwd: root })
expect(next._meta.lembas.model).toBe("f/small")
})
test("a scheduled run uses the directory's model and never becomes it — not its turn, a model change, or the person's turn in its chat", async () => {
fake = fakeProvider([reply("Done."), reply("And again."), reply("Nothing new.")])
config(fake.url)
const root = project()
rememberModel(root, "f/big")
const { c } = await client(limitsFor(root))
const scheduled = { schedule_id: "sched1", run_id: "run7", title: "Check" }
const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "f/small", lembas: { scheduled } } })
expect(s._meta.lembas.model).toBe("f/small")
await c.request("session/prompt", say(s.sessionId, "check", { scheduled, turnId: "run7" }))
expect(lastModel(root)).toBe("f/big")
await c.request("_lembas/configure", { sessionId: s.sessionId, model: "f/m" })
expect(lastModel(root)).toBe("f/big")
await c.request("session/prompt", say(s.sessionId, "what did you find?"))
expect(lastModel(root)).toBe("f/big")
// Opened from the store again by another link (a restart): still a schedule's session.
const again = await client(limitsFor(root))
await again.c.request("session/prompt", say(s.sessionId, "and now?"))
expect(lastModel(root)).toBe("f/big")
// …on the model it had (changed to f/m above), not on the directory's: kept with the session.
expect(fake.requests.map((r) => r.model)).toEqual(["f/small", "f/m", "f/m"])
// A schedule that names no model: the session starts on the directory's.
const follows: any = await c.request("session/new", { cwd: root, _meta: { lembas: { scheduled: { ...scheduled, run_id: "run8" } } } })
expect(follows._meta.lembas.model).toBe("f/big")
})
+25
View File
@@ -273,3 +273,28 @@ test("notify never, and a server that says no notify at all: the tool is not in
expect(bare(fake.requests[4].messages.at(-1).content)).toBe(TOOL_SPECS.report_write!.unavailable!)
expect(mine._meta.lembas.scheduled).toBeUndefined()
})
test("a continuing schedule's session opened from the store again — the service restarted — is still offered report_write", async () => {
fake = fakeProvider([
{ chunks: [delta({ content: "Nothing to tell." })] },
{ chunks: [toolCall(0, "c1", "report_write", R())] },
{ chunks: [delta({ content: "Filed." })] },
{ chunks: [delta({ content: "It was the disk." })] },
])
config(fake.url)
const root = project()
const scheduled = sched({ notify: "when" })
const first = await client(limitsFor(root))
const s: any = await first.c.request("session/new", { cwd: root, _meta: { lembas: { scheduled } } })
await first.c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check" }], _meta: { lembas: { turnId: "run7", scheduled } } })
expect(toolNames(0)).toContain("report_write")
// Another link, with nothing in memory: the session comes from the store.
const again = await client(limitsFor(root))
const next = sched({ notify: "when", run_id: "run8" })
const r: any = await again.c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "check" }], _meta: { lembas: { turnId: "run8", scheduled: next } } })
expect(toolNames(1)).toContain("report_write")
expect(r._meta.lembas.scheduled.report).toMatchObject({ title: "Disk almost full" })
// …and the person's own turn in it still finds the tool there, and unavailable.
await again.c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "what was it?" }] })
expect(toolNames(3)).toContain("report_write")
})
+3 -1
View File
@@ -88,7 +88,9 @@ test("list, pause, run now and history go to the schedule routes with the device
const lines = listLines(all, now)
expect(lines[0]).toBe("Waybread check (sched1) — On the second Monday of each month at 07:30")
expect(lines[1]).toContain("· last ok")
expect(lines[3]).toBe(" paused")
expect(lines[3]).toBe(" Chat · paused")
// Spec 3.9.0: the two types — Agentic is a schedule that runs on a linked computer.
expect(listLines([{ ...SCHED, enabled: false, last_run: null, runs_on: { device: "dev1", device_name: "workstation", cwd: "/home/user/project", mode: "edit" } }], now)[1]).toBe(" Agentic · paused · on workstation in /home/user/project")
expect((await pauseSchedule("sched1")).enabled).toBe(false)
expect((await runSchedule("sched1")).id).toBe("run9")
const h = await scheduleRuns("sched1")