diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bf0ed2..e8e739d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,8 +42,19 @@ Harness spec 3.9.0: the model last used in a directory, the two types of schedul (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 diff --git a/harness/README.md b/harness/README.md index f9bdf56..5a0a741 100644 --- a/harness/README.md +++ b/harness/README.md @@ -109,7 +109,10 @@ a field, a rule amended, no tool and no text for a model. 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. + 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 @@ -121,7 +124,15 @@ a field, a rule amended, no tool and no text for a model. 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. + 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 diff --git a/harness/acp.md b/harness/acp.md index 613924a..a741abe 100644 --- a/harness/acp.md +++ b/harness/acp.md @@ -409,12 +409,16 @@ which the device says too, should such a turn reach it (`data.reason: "interacti 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 is linked whenever this is asked — a run whose +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 (`kind: record`). Otherwise a schedule that names a small +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` @@ -493,8 +497,14 @@ client's to decide from this answer (`reports.md` §4). A device without the cap - **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`, and from spec 3.9.0 - `interactive_only` — the session's model is one, `interactive.md` §2) lets the client say - what to change. Not retried. + `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 @@ -538,15 +548,17 @@ server. Capability `directory_model`; conformance area `last_model`. 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 — and a directory that no - longer exists is dropped when the file is next written. + 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); a + 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. @@ -566,7 +578,8 @@ The first of these that names a model (`kind: start`): 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; so does a one-shot `lembas run`, which records nothing. +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 @@ -681,11 +694,11 @@ directory is not accepted (*The model last used in a directory*). ← { "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": "deepseek/deepseek-flash" } ] } + { "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": "deepseek/deepseek-flash", "parent": "/home/user" } + "model": "open/flash", "parent": "/home/user" } → { "path": "/home/user/notes", "list": false } ← { "path": "/home/user/notes", "name": "notes", "accepted": true, "parent": "/home/user" } diff --git a/harness/conformance/interactive.json b/harness/conformance/interactive.json index 3c6abba..a624f27 100644 --- a/harness/conformance/interactive.json +++ b/harness/conformance/interactive.json @@ -1,35 +1,35 @@ { - "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. → `{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.", + "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/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder" + "id": "payg/coder" }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], - "expect": "payg/qwen3-coder" + "expect": "payg/coder" }, { "about": "No other provider serves it.", "kind": "twin", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "expect": null @@ -37,14 +37,14 @@ { "about": "A twin that is itself interactive-only is none.", "kind": "twin", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "other-plan/qwen3-coder", + "id": "other-plan/coder", "interactive_only": true } ], @@ -53,17 +53,17 @@ { "about": "The part after the first slash is compared whole: a longer name is another model.", "kind": "twin", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder-plus" + "id": "payg/coder-plus" }, { - "id": "payg/org/qwen3-coder" + "id": "payg/org/coder" } ], "expect": null @@ -71,128 +71,128 @@ { "about": "The first in the list's order.", "kind": "twin", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "b/qwen3-coder" + "id": "b/coder" }, { - "id": "a/qwen3-coder" + "id": "a/coder" } ], - "expect": "b/qwen3-coder" + "expect": "b/coder" }, { "about": "A model that is not interactive-only is asked itself, as before.", "kind": "background", "call": "title", - "model": "deepseek/deepseek-flash", + "model": "open/flash", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder" + "id": "payg/coder" }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "defaults": [ - "payg/qwen3-coder" + "payg/coder" ], "expect": { - "model": "deepseek/deepseek-flash" + "model": "open/flash" } }, { "about": "A title for a session on a plan's model goes to the twin.", "kind": "background", "call": "title", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder" + "id": "payg/coder" }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "defaults": [ - "deepseek/deepseek-flash" + "open/flash" ], "expect": { - "model": "payg/qwen3-coder" + "model": "payg/coder" } }, { "about": "No twin: the default that is not interactive-only.", "kind": "background", "call": "compaction", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "defaults": [ - "deepseek/deepseek-flash" + "open/flash" ], "expect": { - "model": "deepseek/deepseek-flash" + "model": "open/flash" } }, { "about": "The first default is interactive-only too, the second is not.", "kind": "background", "call": "auto_compaction", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "plan/qwen3-max", + "id": "plan/max", "interactive_only": true }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "defaults": [ - "plan/qwen3-max", - "deepseek/deepseek-flash" + "plan/max", + "open/flash" ], "expect": { - "model": "deepseek/deepseek-flash" + "model": "open/flash" } }, { "about": "A default the list does not have is passed over.", "kind": "background", "call": "title", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "plan/qwen3-max", + "id": "plan/max", "interactive_only": true } ], @@ -207,19 +207,19 @@ "about": "Nowhere to go: a title is skipped.", "kind": "background", "call": "title", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "plan/qwen3-max", + "id": "plan/max", "interactive_only": true } ], "defaults": [ - "plan/qwen3-max" + "plan/max" ], "expect": { "skip": true @@ -229,19 +229,19 @@ "about": "Nowhere to go: compaction the person asked for is refused in words.", "kind": "background", "call": "compaction", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "plan/qwen3-max", + "id": "plan/max", "interactive_only": true } ], "defaults": [ - "plan/qwen3-coder" + "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." @@ -251,14 +251,14 @@ "about": "Nowhere to go: automatic compaction is skipped and the turn goes on.", "kind": "background", "call": "auto_compaction", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "plan/qwen3-max", + "id": "plan/max", "interactive_only": true } ], @@ -268,19 +268,102 @@ } }, { - "about": "A scheduled run on a pay-as-you-go model.", - "kind": "scheduled", - "model": "payg/qwen3-coder", + "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/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder" + "id": "payg/coder" }, { - "id": "deepseek/deepseek-flash" + "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": { @@ -290,21 +373,21 @@ { "about": "A scheduled run whose model is interactive-only fails with the sentence — never quietly on its twin.", "kind": "scheduled", - "model": "plan/qwen3-coder", + "model": "plan/coder", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder" + "id": "payg/coder" }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "expect": { - "refused": "plan/qwen3-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." + "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." } }, { @@ -313,14 +396,14 @@ "model": "new/model", "models": [ { - "id": "plan/qwen3-coder", + "id": "plan/coder", "interactive_only": true }, { - "id": "payg/qwen3-coder" + "id": "payg/coder" }, { - "id": "deepseek/deepseek-flash" + "id": "open/flash" } ], "expect": { diff --git a/harness/conformance/last_model.json b/harness/conformance/last_model.json index cdab8ef..45bffb7 100644 --- a/harness/conformance/last_model.json +++ b/harness/conformance/last_model.json @@ -1,110 +1,110 @@ { - "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 person changes the session's model: /model, a setting, _lembas/configure) 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.", + "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": [ - "deepseek/deepseek-flash", - "qwen/qwen3" + "open/flash", + "open/large" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "default" } }, { "about": "The global setting — what a login writes — over the instance's default.", "kind": "start", - "global": "qwen/qwen3", + "global": "open/large", "served": [ - "deepseek/deepseek-flash", - "qwen/qwen3" + "open/flash", + "open/large" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "qwen/qwen3", + "model": "open/large", "from": "global" } }, { "about": "The model last used in this directory over the global setting.", "kind": "start", - "directory": "mistral/devstral", - "global": "qwen/qwen3", + "directory": "other/coder", + "global": "open/large", "served": [ - "deepseek/deepseek-flash", - "qwen/qwen3", - "mistral/devstral" + "open/flash", + "open/large", + "other/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "mistral/devstral", + "model": "other/coder", "from": "directory" } }, { "about": "The project's setting over the directory's memory: it is written down on purpose.", "kind": "start", - "project": "qwen/qwen3", - "directory": "mistral/devstral", - "global": "deepseek/deepseek-flash", + "project": "open/large", + "directory": "other/coder", + "global": "open/flash", "served": [ - "deepseek/deepseek-flash", - "qwen/qwen3", - "mistral/devstral" + "open/flash", + "open/large", + "other/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "qwen/qwen3", + "model": "open/large", "from": "project" } }, { "about": "The model asked for over everything.", "kind": "start", - "asked": "deepseek/deepseek-flash", - "project": "qwen/qwen3", - "directory": "mistral/devstral", - "global": "qwen/qwen3", + "asked": "open/flash", + "project": "open/large", + "directory": "other/coder", + "global": "open/large", "served": [ - "deepseek/deepseek-flash", - "qwen/qwen3", - "mistral/devstral" + "open/flash", + "open/large", + "other/coder" ], - "default": "qwen/qwen3", + "default": "open/large", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "asked" } }, { "about": "The remembered model is no longer served: skipped, the global setting decides.", "kind": "start", - "directory": "mistral/devstral", - "global": "qwen/qwen3", + "directory": "other/coder", + "global": "open/large", "served": [ - "deepseek/deepseek-flash", - "qwen/qwen3" + "open/flash", + "open/large" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "qwen/qwen3", + "model": "open/large", "from": "global" } }, { "about": "…and with no global setting, the instance's default.", "kind": "start", - "directory": "mistral/devstral", + "directory": "other/coder", "served": [ - "deepseek/deepseek-flash", - "qwen/qwen3" + "open/flash", + "open/large" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "default" } }, @@ -113,9 +113,9 @@ "kind": "start", "global": "old/model", "served": [ - "deepseek/deepseek-flash" + "open/flash" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { "model": "old/model", "from": "global" @@ -210,45 +210,62 @@ "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": "mistral/devstral", + "directory": "other/coder", "has": [ - "deepseek/deepseek-flash", - "mistral/devstral" + "open/flash", + "other/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "mistral/devstral", + "model": "other/coder", "from": "directory" } }, { "about": "The person chose a model: theirs, whatever the directory remembers.", "kind": "client", - "named": "deepseek/deepseek-flash", - "directory": "mistral/devstral", + "named": "open/flash", + "directory": "other/coder", "has": [ - "deepseek/deepseek-flash", - "mistral/devstral" + "open/flash", + "other/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "named" } }, { "about": "The person no longer has the remembered model: as before.", "kind": "client", - "directory": "mistral/devstral", + "directory": "other/coder", "has": [ - "deepseek/deepseek-flash" + "open/flash" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "default" } }, @@ -256,55 +273,55 @@ "about": "An older device, or one that remembers nothing there: as before.", "kind": "client", "has": [ - "deepseek/deepseek-flash", - "mistral/devstral" + "open/flash", + "other/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "default" } }, { "about": "An Agentic schedule that names no model follows the directory.", "kind": "client", - "directory": "qwen/qwen3", + "directory": "open/large", "has": [ - "deepseek/deepseek-flash", - "qwen/qwen3" + "open/flash", + "open/large" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "qwen/qwen3", + "model": "open/large", "from": "directory" } }, { "about": "A schedule that names one runs on it.", "kind": "client", - "named": "deepseek/deepseek-flash", - "directory": "qwen/qwen3", + "named": "open/flash", + "directory": "open/large", "has": [ - "deepseek/deepseek-flash", - "qwen/qwen3" + "open/flash", + "open/large" ], - "default": "qwen/qwen3", + "default": "open/large", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "named" } }, { "about": "The directory's model is compared exactly: another spelling is not the model.", "kind": "client", - "directory": "Mistral/Devstral", + "directory": "Other/Coder", "has": [ - "deepseek/deepseek-flash", - "mistral/devstral" + "open/flash", + "other/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "default" } }, @@ -312,48 +329,48 @@ "about": "A schedule's run: an interactive-only model remembered for the directory does not count.", "kind": "client", "scheduled": true, - "directory": "plan/qwen3-coder", + "directory": "plan/coder", "has": [ - "plan/qwen3-coder", - "deepseek/deepseek-flash" + "plan/coder", + "open/flash" ], "interactive_only": [ - "plan/qwen3-coder" + "plan/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "default" } }, { "about": "…while a person's new chat there starts on it: that is interactive.", "kind": "client", - "directory": "plan/qwen3-coder", + "directory": "plan/coder", "has": [ - "plan/qwen3-coder", - "deepseek/deepseek-flash" + "plan/coder", + "open/flash" ], "interactive_only": [ - "plan/qwen3-coder" + "plan/coder" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "plan/qwen3-coder", + "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/qwen3-coder", - "global": "deepseek/deepseek-flash", + "directory": "plan/coder", + "global": "open/flash", "served": [ - "deepseek/deepseek-flash" + "open/flash" ], - "default": "deepseek/deepseek-flash", + "default": "open/flash", "expect": { - "model": "deepseek/deepseek-flash", + "model": "open/flash", "from": "global" } } diff --git a/harness/conformance/rules.json b/harness/conformance/rules.json index 0395185..29edffb 100644 --- a/harness/conformance/rules.json +++ b/harness/conformance/rules.json @@ -429,6 +429,123 @@ }, "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, diff --git a/harness/interactive.md b/harness/interactive.md index c5789bb..36562b7 100644 --- a/harness/interactive.md +++ b/harness/interactive.md @@ -51,7 +51,10 @@ once (the CLI's commit-message draft). 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. +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 @@ -72,6 +75,16 @@ When the model a background call would use is interactive-only, the call goes to | 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 diff --git a/harness/loop.json b/harness/loop.json index 03e7adb..d1e82b7 100644 --- a/harness/loop.json +++ b/harness/loop.json @@ -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": [ diff --git a/harness/permission/rules.md b/harness/permission/rules.md index 45f76df..663b9ad 100644 --- a/harness/permission/rules.md +++ b/harness/permission/rules.md @@ -41,12 +41,18 @@ than it (`deny` over `ask` over `allow`) — the strictest of them decides: **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 — that later rule is what was written for the case. The defaults say `read *.env.*: ask` + 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. + *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. diff --git a/src/acp/agent.ts b/src/acp/agent.ts index f4ab78d..0378d1c 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -47,7 +47,7 @@ import type { Hub } from "./hub.ts" import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts" import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts" import { isNote } from "../session/prefix.ts" -import { 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: @@ -642,7 +642,7 @@ export class AcpAgent { const effort = effortOf(p?._meta?.effort) try { // 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 } : {}), ...(scheduled ? { remember: false as const, automated: true as const } : {}) }) + 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) { // 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) @@ -666,6 +666,8 @@ export class AcpAgent { // 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) @@ -771,7 +773,8 @@ 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 @@ -780,7 +783,6 @@ export class AcpAgent { // after a restart of the service was not offered the tool its prompt told it to call. try { const kept = session.app.store?.meta(id, SCHEDULED_META) - if (kept) session.app.forgetful() if (kept && typeof kept === "object") session.opened = kept } catch {} session.app.setScope(id) @@ -1061,6 +1063,13 @@ export class AcpAgent { private async prompt(p: any): Promise { 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]) @@ -1084,18 +1093,25 @@ export class AcpAgent { const run = async (started: () => void): Promise => { 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), s.app.forgetful() - else delete s.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. + // 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. @@ -1157,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 } } @@ -1206,10 +1219,7 @@ export class AcpAgent { 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 } } diff --git a/src/app.ts b/src/app.ts index eef1ce7..5d5cddb 100644 --- a/src/app.ts +++ b/src/app.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,14 +51,14 @@ 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, rememberModel, startModel } from "./session/lastmodel.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 {} -import { TeamRuntime, type MemberHandle } from "./team/runtime.ts" export interface AppOptions { cwd: string @@ -81,9 +81,11 @@ 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 - /** false: this session's model is never made its directory's (harness acp.md, *The model last - * used in a directory*): a one-shot run, a session a schedule opened. It still starts on it. */ - remember?: false + /** 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 @@ -120,12 +122,16 @@ export interface App { /** A ref in any form it may be written in (the old `/` too) as the ref the * model has now; the ref itself when it names nothing. */ canonicalRef(ref: string): string - /** `borrowed`: for one prompt only (a command's own model) — not the directory's model. */ + /** `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 - /** Stop remembering this session's model for its directory (a schedule's session). */ + /** 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. */ @@ -493,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 }) @@ -531,7 +540,7 @@ export function createApp(o: AppOptions): App { 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 = automated ? notAutomated(m) : undefined + 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) { @@ -612,8 +621,8 @@ export function createApp(o: AppOptions): App { 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) => { - const where = backgroundFor(child.model, call) + 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` }) @@ -745,7 +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) => backgroundFor(engine.model, call), + 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), @@ -914,6 +923,8 @@ export function createApp(o: AppOptions): App { 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) @@ -930,7 +941,7 @@ export function createApp(o: AppOptions): App { /** 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): { client: Client; effort: Level; model: ResolvedModel } | { skip: true } | { refused: string } | undefined { + 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 { @@ -939,7 +950,19 @@ export function createApp(o: AppOptions): App { return undefined } } - const r = background({ model: m.ref, models: listed(), defaults: [canonical(readRaw(globalConfigFile()).model), canonical(loaded.connections[m.connectionName]?.webui?.default)], call }) + // 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 } @@ -947,15 +970,36 @@ export function createApp(o: AppOptions): App { // 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 remembers = o.remember !== false + let kind: SessionKind = o.kind ?? "terminal" let borrowed = false - const remember = () => { - if (remembers && !borrowed) rememberModel(o.cwd, engine.model.ref) + /** 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 {} } - bus.on((e) => e.type === "prompt" && !e.machine && remember()) const switchModel = (ref: string, how?: "borrowed") => { const m = resolveModel(loaded, ref) - const no = automated ? notAutomated(m) : undefined + // 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)) @@ -1002,7 +1046,7 @@ export function createApp(o: AppOptions): App { } }, apply(key, v) { - if (key === "model") (switchModel(String(v)), remember()) + 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) @@ -1067,12 +1111,19 @@ 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() + remember("change") + keepModel() }, forgetful() { - remembers = false + kind = "scheduled" + keepModel() }, setAutomated(on) { automated = on @@ -1127,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 }) @@ -1141,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(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) diff --git a/src/cli.ts b/src/cli.ts index 99c531e..b310972 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -88,7 +88,9 @@ Local mode: Options for run: -m, --model conn/model model to use (default: the project's \`model\`, else the one last used in - this directory, else config.yaml \`model\`) + 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) @@ -329,22 +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). - remember: false, + 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). - ...(!process.stdin.isTTY && !process.stdout.isTTY && !process.stderr.isTTY ? { automated: true as const } : {}), - }) + ...(nobodyAtIt({ stdin: process.stdin.isTTY, stdout: process.stdout.isTTY, stderr: process.stderr.isTTY }) ? { automated: true as const } : {}), + } + let app: ReturnType + 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()) diff --git a/src/harness.ts b/src/harness.ts index e180730..b7d3861 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -191,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: { diff --git a/src/permission/evaluate.ts b/src/permission/evaluate.ts index 28c492e..425c1e3 100644 --- a/src/permission/evaluate.ts +++ b/src/permission/evaluate.ts @@ -104,7 +104,8 @@ function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule | // 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)) - const floors: Rule[] = narrower.filter((r, i) => !narrower.slice(i + 1).some((later) => narrowerThan(later, r))) + // …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) { diff --git a/src/provider/interactive.ts b/src/provider/interactive.ts index 45176c3..5df0601 100644 --- a/src/provider/interactive.ts +++ b/src/provider/interactive.ts @@ -14,11 +14,11 @@ const only = (model: string, models: readonly Listed[]): boolean => models.find( /** 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[]): string | undefined { +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)?.id + 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" @@ -26,9 +26,12 @@ 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 }): { model: string } | { skip: true } | { refused: string } { +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 } - const other = twin(o.model, o.models) ?? (o.defaults ?? []).find((d): d is string => Boolean(d) && o.models.some((m) => m.id === d) && !only(d!, o.models)) + // 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 } } @@ -40,3 +43,12 @@ export function scheduledRefusal(model: string, models: readonly Listed[], label /** 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." diff --git a/src/session/engine.ts b/src/session/engine.ts index 234fa84..690405b 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -73,7 +73,7 @@ export interface EngineOptions { /** 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") => { client: Client; effort: Level } | { skip: true } | { refused: string } | undefined + 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 @@ -378,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 {} } @@ -563,17 +564,19 @@ export class Engine { private async summarise(signal: AbortSignal, call: "compaction" | "auto_compaction"): Promise { // 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) + 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 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 @@ -644,7 +647,8 @@ export class Engine { } // 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). - const where = this.o.background?.("auto_compaction") + // 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 diff --git a/src/session/lastmodel.ts b/src/session/lastmodel.ts index d9fec32..2d8fe5b 100644 --- a/src/session/lastmodel.ts +++ b/src/session/lastmodel.ts @@ -3,7 +3,8 @@ // 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, statSync, writeFileSync } from "node:fs" +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" @@ -25,11 +26,12 @@ 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. */ + * 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.what === "turn" && o.machine === true) + return o.machine !== true } /** The client's rule (LLeMbas applies it; kept here so both suites answer the same cases): the @@ -45,14 +47,24 @@ export function clientModel(o: { named?: string; directory?: string; has: readon /** 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 written, ms since the epoch. */ + /** When it was last used, ms since the epoch (to REFRESH_MS). */ at: number } interface File { version: 1 directories: Record + /** When gone directories were last looked for. */ + pruned?: number } /** `models.json` in the state directory (local mode: the local root's). */ @@ -66,7 +78,7 @@ export function directoryKey(dir: string): string { 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 } + 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: {} } } @@ -86,32 +98,54 @@ export function lastModels(): (dir: string) => string | undefined { } } -const isDirectory = (p: string): boolean => { - try { - return statSync(p).isDirectory() - } catch { - return false - } +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`. Written atomically, read first, so two sessions writing for two - * directories keep both; directories that are gone are dropped, and the oldest beyond the cap. - * A failure is nobody's problem: the memory is a convenience, never in a turn's way. */ +/** 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() - if (file.directories[key]?.model === ref) return + 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(([d, e]) => e && typeof e.model === "string" && (d === key || isDirectory(d))) + .filter(([, e]) => e && typeof e.model === "string") .sort((a, b) => (b[1].at ?? 0) - (a[1].at ?? 0)) .slice(0, MAX_DIRECTORIES) - const path = lastModelFile() - if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true, mode: 0o700 }) - const tmp = `${path}.${process.pid}.tmp` - writeFileSync(tmp, `${JSON.stringify({ version: 1, directories: Object.fromEntries(kept) }, null, 2)}\n`, { mode: 0o600 }) - renameSync(tmp, path) + 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 { + 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((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 +} diff --git a/src/session/store.ts b/src/session/store.ts index d58a449..1f51032 100644 --- a/src/session/store.ts +++ b/src/session/store.ts @@ -73,6 +73,9 @@ export const REMOTE_META = "remote" * 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. */ diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 399e207..3cb7b2d 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -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() } diff --git a/tests/conformance.ts b/tests/conformance.ts index 4ea2b36..5b3cfeb 100644 --- a/tests/conformance.ts +++ b/tests/conformance.ts @@ -68,7 +68,7 @@ export const AREAS: Record unknown> = { 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 }) + 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 } diff --git a/tests/hub.test.ts b/tests/hub.test.ts index 3ffd50c..f2b4895 100644 --- a/tests/hub.test.ts +++ b/tests/hub.test.ts @@ -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) => 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" }) +}) diff --git a/tests/interactive.test.ts b/tests/interactive.test.ts index 66aafe2..0b8bd8f 100644 --- a/tests/interactive.test.ts +++ b/tests/interactive.test.ts @@ -11,6 +11,7 @@ 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" @@ -25,9 +26,9 @@ afterEach(async () => { }) /** 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 } = {}) { +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.other === false ? [] : ["open/flash: {}"])] + 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 ?? ""}`) } @@ -59,9 +60,12 @@ test("a person's turn runs on the interactive-only model; its title is asked of 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 () => { @@ -90,8 +94,13 @@ test("compaction the person asks for is the twin's work, and the session stays o 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"]) }) @@ -154,6 +163,61 @@ test("a subagent's own automatic compaction goes the same way: the twin's work; 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", () => { @@ -248,3 +312,20 @@ test("a scheduled run's subagent is not started on one: the call answers the sen 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"]) +}) diff --git a/tests/lastmodel.test.ts b/tests/lastmodel.test.ts index 07731c4..feab8b5 100644 --- a/tests/lastmodel.test.ts +++ b/tests/lastmodel.test.ts @@ -10,7 +10,8 @@ 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, rememberModel } from "../src/session/lastmodel.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" @@ -74,7 +75,7 @@ test("the file is this machine's: in the state directory, private, and nowhere i expect(existsSync(join(root, ".agent"))).toBe(false) }) -test("a directory that is gone is dropped at the next write, and the oldest beyond the cap", () => { +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) @@ -83,8 +84,12 @@ test("a directory that is gone is dropped at the next write, and the oldest beyo 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) - expect(kept.sort()).toEqual(dirs) + 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") @@ -93,6 +98,19 @@ test("a directory that is gone is dropped at the next write, and the oldest beyo 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") @@ -177,11 +195,57 @@ test("a session that does not remember — a one-shot run — starts on the dire config(fake.url) const root = project() rememberModel(root, "f/big") - const a = app(root, { model: "f/small", remember: false }) + 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, { remember: false }).engine.model.ref).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 ──────────────────────────────────────────────────────────────────────────────── @@ -293,6 +357,8 @@ test("a scheduled run uses the directory's model and never becomes it — not it 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")