Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7a9037ed3
|
||
|
|
55706542a4
|
||
|
|
18e9117ed3
|
||
|
|
4d878b303e
|
||
|
|
90cccac8bc
|
||
|
|
22143b1199
|
||
|
|
d44fd46c00
|
||
|
|
2add5695a6
|
||
|
|
62148c5f81
|
||
|
|
89e9e47ecc
|
No files matched your search
@@ -4,6 +4,85 @@ 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.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
|
||||
|
||||
Harness spec 3.8.1: the text that tells a model when to write a page and when to show a file.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Harness spec 3.8.1: a page for what is to be seen, a shown file for what has to run.** The
|
||||
text a model is given when HTML pages are on (`harness/prompts/blocks/html-pages.md`) now says
|
||||
that something the person asks to see in the answer is written as a page, not as an HTML file
|
||||
opened with `show`; and that a page is static, so anything that has to run — a calculator, a
|
||||
game, something that reacts to a click — is not a page: the model says so and, where it can,
|
||||
writes an HTML file and shows that. A text only; the CLI is never offered pages and behaves
|
||||
as before.
|
||||
|
||||
## [2.0.0-beta.10] — 2026-11-13
|
||||
|
||||
Harness spec 3.8.0: reports from scheduled runs, HTML pages in answers, which permission rule decides.
|
||||
|
||||
+70
-3
@@ -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) |
|
||||
|
||||
## Vocabulary
|
||||
|
||||
@@ -78,6 +79,72 @@ 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.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
|
||||
showing HTML is for what: **something the person asks to see in the answer is a page** — not
|
||||
an HTML file written and opened with `show`, which is what a model did when nothing said
|
||||
otherwise, leaving a card to open where the drawing was asked for — and **something that has to
|
||||
run is not a page**: a page is static, so for a calculator, a game or anything that reacts to a
|
||||
click the model says a page cannot do it and, where it has `write` and `show`, writes an HTML
|
||||
file and shows that. Nothing else changes: no tool, rule, field or conformance case; the CLI is
|
||||
never offered pages, so its behaviour is the same.
|
||||
|
||||
## 3.8.0
|
||||
|
||||
Written ahead of the implementations; the CLI carries it in the same round.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.8.0
|
||||
3.9.0
|
||||
+173
-8
@@ -68,6 +68,7 @@ change to the protocol is a change here first, then in both projects.
|
||||
| `agents` | spec 3.4.0: the session's Subagents setting `{ min, max }` is read from `_meta.lembas.agents` on `session/new`, `session/prompt` and `_lembas/configure` (*Subagents in an agent chat*, below) |
|
||||
| `tree` | spec 3.4.0 (`subagents.md` §5–§13): the `team` event; `_lembas/team`, `_lembas/team/transcript`, `_lembas/team/findings`, `_lembas/team/stop`; `subagent` on `session/request_permission` |
|
||||
| `scheduled` | spec 3.5.0 (*Scheduled work on a linked computer*, below): `scheduled` in `_meta.lembas` of `session/new` and `session/prompt` read, and the run's outcome in the prompt's answer; `scheduled` on `session/request_permission`; `_lembas/monitor`; `limits.scheduled` in `_lembas/hello` and `initialize`. Listed by every build that has it, whatever the setting says: whether this device *accepts* scheduled work is `limits.scheduled` |
|
||||
| `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 |
|
||||
| `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 +134,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.
|
||||
@@ -334,6 +338,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 +392,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" }`):
|
||||
@@ -449,8 +496,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 +530,85 @@ 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.)
|
||||
|
||||
## `_lembas/*` methods
|
||||
|
||||
Direction is who sends it. "→ result" marks a request; the others are notifications.
|
||||
@@ -540,10 +673,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
|
||||
|
||||
@@ -815,7 +977,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 +1046,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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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",
|
||||
|
||||
@@ -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": {
|
||||
|
||||
+6
-1
@@ -40,7 +40,12 @@ A page is a fenced code block whose info string begins with the word **`html-vie
|
||||
## 2. What the model is told
|
||||
|
||||
`prompts/blocks/html-pages.md`, as bullets of the system prompt when pages are offered (§4) —
|
||||
in short: the answer stays Markdown and must make sense without the page; a page is a complete
|
||||
in short: the answer stays Markdown and must make sense without the page; **what the person
|
||||
asks to see in the answer is a page, not an HTML file opened with `show`** (3.8.1: without
|
||||
this a model wrote a file and showed it, and the person got a card to open instead of the thing
|
||||
they asked for); **what has to run is not a page** — the model says a page cannot run anything
|
||||
and, where it has `write` and `show`, writes an HTML file and shows that, which a client runs
|
||||
in its sealed viewer; a page is a complete
|
||||
document in an `html-view` fence with a short title, one page per fence; it is **static** — HTML,
|
||||
CSS and inline SVG, nothing that runs and nothing loaded from anywhere; a chart is inline SVG the
|
||||
model writes out, shapes and numbers it worked out itself; tables and layout are CSS; colours
|
||||
|
||||
@@ -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,8 +1,10 @@
|
||||
<!-- Spec 3.8.0 (pages.md). Offered only when the instance, the model and the chat all say so; never
|
||||
<!-- Spec 3.8.0 (pages.md); 3.8.1: a page for what is to be seen, a shown file for what has to run. Offered only when the instance, the model and the chat all say so; never
|
||||
to a subagent, the phone assistant or an agent chat. The fence word, the variables and what a
|
||||
static page may hold are loop.json `pages`. -->
|
||||
- Your answer is Markdown, as always. Where seeing answers better than reading — a chart, a comparison laid out as a table with colour, a diagram, a timeline — you may add a page to it: a complete, self-contained HTML document in a fenced block whose info string is `html-view` followed by a short title, for example ```html-view Monthly sales. One page per block. It is shown at that place in your answer, in a sealed frame of a fixed height that scrolls.
|
||||
- When the user asks to see something in your answer — "show me", "draw", "visualise", a chart, a diagram, a table laid out — and it can be drawn without running anything, write it as a page here. Do not write it to an HTML file and open that with `show` instead: a page is what appears in the conversation, at the place you put it, and stays there when the conversation is opened again.
|
||||
- A page is static: HTML, CSS and inline SVG only. Nothing in it runs and nothing is loaded: no `<script>` and no event handlers; no `<link>`, `<meta>`, `<base>`, frames, objects, audio, video, canvas or forms; no address anywhere except `#fragment` and an inline `data:image/…` picture. Anything else is removed before the page is shown.
|
||||
- So a page cannot be interactive. When what is asked for has to run — a calculator, a game, a clock, an animation driven by script, anything that reacts to a click or to typing — do not write it as a page, and do not pretend one can do it: say in a sentence that a page in an answer cannot run anything, and, if you have the `write` and `show` tools, write it as an HTML file and open that with `show`, where the user can run it in a sealed viewer.
|
||||
- Draw a chart as inline SVG you write out yourself: work the numbers out first, then write the bars, lines or slices as SVG shapes with their labels. Lay out and style tables and text with CSS in a `<style>` element — no `@import`, no `url(…)` to anywhere.
|
||||
- Follow the reader's light or dark theme with the frame's CSS variables, always with a fallback: --page-bg (background), --page-ink (text), --page-muted (secondary text), --page-accent (the accent colour) and --page-line (rules and borders) — for example `color: var(--page-ink, #222)`.
|
||||
- If the page itself contains a line of three backticks, open and close its block with four.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "lembas-cli",
|
||||
"version": "2.0.0-beta.10",
|
||||
"version": "2.0.0-beta.12",
|
||||
"description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
|
||||
@@ -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"
|
||||
|
||||
+73
-22
@@ -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"
|
||||
@@ -39,13 +40,14 @@ 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 { 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:
|
||||
@@ -295,6 +297,9 @@ 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",
|
||||
] as const
|
||||
export const STOP: Record<string, string> = { stop: "end_turn", steps: "max_turn_requests", budget: "max_tokens", cancelled: "cancelled", error: "end_turn" }
|
||||
|
||||
@@ -570,14 +575,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 +598,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 +615,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 +641,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 +660,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 +731,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 +773,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)
|
||||
@@ -1029,6 +1063,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])
|
||||
@@ -1052,13 +1093,29 @@ 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) => {
|
||||
@@ -1105,7 +1162,7 @@ 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,
|
||||
@@ -1116,10 +1173,7 @@ export class AcpAgent {
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -1159,16 +1213,13 @@ 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()
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -604,7 +604,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()
|
||||
|
||||
+182
-7
@@ -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"
|
||||
@@ -30,7 +30,7 @@ import type { Client, ResolvedModel } from "./provider/types.ts"
|
||||
import { modelTitle, firstReply, promptTitle } from "./session/title.ts"
|
||||
import { Turns } from "./session/turns.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 +51,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 +81,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 +122,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
|
||||
@@ -225,7 +253,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 +499,9 @@ 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) return void bus.emit({ type: "notice", level: "warn", message: `a job's note did not start a turn: ${no}` })
|
||||
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 })
|
||||
@@ -490,6 +539,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 +604,7 @@ export function createApp(o: AppOptions): App {
|
||||
return o.asker.plan
|
||||
},
|
||||
})
|
||||
let compactionSkipSaid = false
|
||||
const child = new Engine({
|
||||
bus: childBus,
|
||||
asker: askerFor(),
|
||||
@@ -566,6 +619,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 +754,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),
|
||||
@@ -853,7 +917,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 +938,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 +1046,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 +1111,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,
|
||||
@@ -1027,6 +1178,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 +1194,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
@@ -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())
|
||||
|
||||
@@ -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
@@ -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: {
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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."
|
||||
+31
-7
@@ -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
|
||||
@@ -374,11 +378,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 {}
|
||||
}
|
||||
|
||||
@@ -547,7 +552,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 +561,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 +617,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 +645,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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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) => {
|
||||
|
||||
+1
-1
@@ -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"])
|
||||
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 })
|
||||
|
||||
@@ -38,6 +38,9 @@ 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 { 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 +56,25 @@ function readableUnder(grants: Record<string, string> | undefined, path: string)
|
||||
}
|
||||
|
||||
export const AREAS: Record<string, (c: Case) => unknown> = {
|
||||
// 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) }),
|
||||
|
||||
@@ -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" })
|
||||
})
|
||||
@@ -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"])
|
||||
})
|
||||
@@ -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")
|
||||
})
|
||||
@@ -93,3 +93,20 @@ test("the old `prototypes: true` setting is dropped with a line saying so, never
|
||||
else writeFileSync(file, before)
|
||||
}
|
||||
})
|
||||
|
||||
// Spec 3.8.1: with nothing said, a model asked to "show" a chart wrote an HTML file and opened it
|
||||
// with `show` — a card to open where the drawing was asked for. The block says which is for what.
|
||||
test("the block says a page is for what is to be seen and a shown file for what has to run", async () => {
|
||||
const block = await Bun.file(new URL("../harness/prompts/blocks/html-pages.md", import.meta.url)).text()
|
||||
const bullets = block.split("\n").filter((line) => line.startsWith("- "))
|
||||
const seen = bullets.find((line) => line.includes("asks to see something in your answer"))
|
||||
expect(seen).toBeDefined()
|
||||
expect(seen).toContain("Do not write it to an HTML file and open that with `show`")
|
||||
const runs = bullets.find((line) => line.includes("a page cannot be interactive"))
|
||||
expect(runs).toBeDefined()
|
||||
expect(runs).toContain("a page in an answer cannot run anything")
|
||||
expect(runs).toContain("open that with `show`")
|
||||
// The static rule comes between the two: what a page is, then what follows from it.
|
||||
const order = [seen, bullets.find((line) => line.startsWith("- A page is static")), runs].map((line) => bullets.indexOf(line as string))
|
||||
expect(order).toEqual([...order].sort((a, b) => a - b))
|
||||
})
|
||||
@@ -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")
|
||||
})
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user