Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec1095940d
|
||
|
|
ff51eb5323
|
||
|
|
cd4dab2a19
|
||
|
|
3ffd2ac999
|
||
|
|
a302f22957
|
||
|
|
591198c48f
|
||
|
|
7804909413
|
||
|
|
026e4f3219
|
||
|
|
87b9a711d9
|
||
|
|
ead689301a
|
||
|
|
22368bec1a
|
||
|
|
94a9db294a
|
||
|
|
9945b76f74
|
||
|
|
299bac55b0
|
||
|
|
83e51137c8
|
||
|
|
6f3ba47ad6
|
||
|
|
95706bc46c
|
||
|
|
cc42bbc390
|
||
|
|
4a2a97ffc7
|
||
|
|
99081c4ed4
|
No files matched your search
+151
@@ -6,6 +6,157 @@ All notable changes to LLeMbas CLI. The format follows
|
||||
|
||||
## Unreleased
|
||||
|
||||
## [2.0.0-beta.21] — 2026-12-03
|
||||
|
||||
### Security
|
||||
|
||||
- **A shell command is judged by what it will touch, not by how it is spelled (harness spec
|
||||
3.15.0, `permission/rules.md` §5).** In manual mode a command the default rules allow — `cat`,
|
||||
`head`, `wc`, `grep`, `rg`, `git blame` — could read a file the `read` rules ask about, or one
|
||||
outside the project, when the file was written through a brace list, another user's `~name`,
|
||||
a variable, or inside an option. Now the words are read as the shell expands them, a path
|
||||
riding on an option is a path, and **a word that cannot be resolved makes the command ask**:
|
||||
it is never "allowed by rules". Ordinary commands are unchanged; one with a variable of your
|
||||
own in it (`cat "$f"`) now asks.
|
||||
- **The protected paths hold for commands in every mode.** In auto mode a command could write
|
||||
under `~/.ssh` or `~/.gnupg`, which the write tools always refused. A redirection into a
|
||||
protected path, or a command naming one that is not known to only read (`cp`, `tee`, `sed -i`,
|
||||
through `sudo`, `bash -c` or a `cd` too), is refused in every mode. Reading there is asked as
|
||||
before.
|
||||
- **A command longer than 32 KiB is asked about in every mode, auto included**, without being
|
||||
analysed: a very long line could keep the permission check — and with it the whole program —
|
||||
busy for many seconds.
|
||||
- **The `grep` tool no longer returns lines of a file `read` would ask about.** A search of a
|
||||
directory was judged for the directory only, so the lines of a `.env` in it came back unasked
|
||||
— in plan mode too. Such files are now left out of the result, which says how many and which,
|
||||
so the model can ask to `read` one. Names are not content: `glob` and `list` still show them.
|
||||
- **A custom command's `` !`…` `` is a `bash` call of the session, and its arguments are data.**
|
||||
The shell line in a command file ran with only the floor checked, with the arguments pasted
|
||||
into it — also for a prompt that arrived over the link from the web, whatever the remote
|
||||
limits said. It now runs only when the session would run that line as a `bash` call without
|
||||
asking (its mode, its rules, the remote limits); otherwise the model is told it was not run.
|
||||
The arguments reach the line as `$1…` and `$ARGUMENTS` of the shell, never as part of it, and
|
||||
a `$` typed in the arguments is no longer rewritten. A substitution is stopped after ten
|
||||
seconds. **A command of yours whose `` !`…` `` is not on the allowed list no longer runs by
|
||||
itself in manual mode** — allow it with a rule, or let the model run it.
|
||||
- **`lembas remote disable` stops what is open.** The remote limits were judged when a session
|
||||
was opened; a session already open — in the service, or a terminal's shared under the limits
|
||||
— kept accepting prompts after remote work was turned off, its folder removed from the roots,
|
||||
the mode lowered or trust withdrawn, and a web terminal stayed open after
|
||||
`lembas remote terminal off`. The limits are now judged on every request and applied within
|
||||
seconds of a change: such a session is refused in words, its running turn and background
|
||||
commands are stopped, its mode is lowered, the terminal is closed. Stopping, asking for status
|
||||
and deleting always work.
|
||||
- **Over the link, only sessions the web UI was shown or that lie in the allowed folders can be
|
||||
listed, asked about or renamed.** A list of the whole machine's sessions, the plan and jobs of
|
||||
any session by its id, and a rename of any session were answered, with remote work off too.
|
||||
- **A project cannot open the settings tool by a rule that merely matches its name.** Only a
|
||||
project rule keyed exactly `settings` was ignored; a trusted project's `sett*` or a rule for
|
||||
every tool let the model change your settings without asking. Only your own configuration
|
||||
decides that tool now.
|
||||
- **The web file manager treats `.lembas/` like `.agent/`.** Where `.agent` is somebody else's
|
||||
directory the project's agent directory is `.lembas`, and with `remote files-that-run-code`
|
||||
off the web could still write its config (MCP servers), commands, agents and skills. Edit mode
|
||||
and the file manager now read one list of the files that run code.
|
||||
- **Your sessions are no longer readable by other users of the computer.** The data and state
|
||||
directories took whatever mode the first program to write them gave them, and the session
|
||||
database was created readable by everyone on the machine. Both directories are now made — and,
|
||||
when they already exist, set — readable by you alone, and so are the session and library
|
||||
databases and the prompt history.
|
||||
- **`get.sh` refuses a signed release list that does not name its version**, as the updater
|
||||
does: an older release's signed files could be served under a newer tag and its binary run
|
||||
before the mismatch was noticed. Both now follow one rule, tested against the same cases.
|
||||
- **A named pipe in an allowed folder can no longer stop the service.** Asking the web file
|
||||
manager to open one made the service wait for a writer — every session and the link with it.
|
||||
Only regular files are opened now; anything else is refused as not a file.
|
||||
- **`--terminal-context` and `/terminal-context` no longer delete what they refuse.** A file was
|
||||
removed once read, whatever it held, and the accepted folders took in the CLI's own data —
|
||||
a wrong path could delete the session database. A file is now removed only once it has read as
|
||||
a terminal context; one that does not is left where it is, and the CLI's own folders are
|
||||
refused outright.
|
||||
- **Autocomplete in a LLeMbas terminal no longer sends a line that holds a password or a key.**
|
||||
`lembas complete --shell` sent the line being typed as it was — `export API_KEY=…`,
|
||||
`mysql -p…`, `curl -u user:pass` included; only the history was filtered. Such a line is now
|
||||
not sent at all, and the same check, widened, applies to the history and to the commands a
|
||||
terminal context hands the model (the command is replaced by a placeholder, its output left
|
||||
out).
|
||||
- **What a remote shell says about itself is no longer taken as fact.** A pane over SSH reports
|
||||
its state through the terminal, and any program printing there can imitate that report. Such
|
||||
a report alone no longer makes the prompt count as empty for a command to be placed or typed —
|
||||
the pane is read instead — and a command's end that only it reports is told to the model as
|
||||
"reported by the remote shell; not verified".
|
||||
- A folder whose name begins with two dots (`..cache`) inside an allowed folder is inside it.
|
||||
- **The force-push floor reads the push.** It refused any forced push with "main" somewhere in
|
||||
it (`feature/main-menu`) and missed deleting the branch (`git push origin :main`,
|
||||
`--delete main`), a forced `--all`/`--mirror`, and a bare `git push -f` while on main. The
|
||||
push is now read by its refspecs.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`lembas run` can be stopped, and leaves nothing behind.** While it waited for a background
|
||||
job, Ctrl+C did nothing — a run whose model had started a server never ended — and SIGTERM or
|
||||
SIGHUP ended the run but not the commands it had started. Now the first Ctrl+C stops the turn
|
||||
and the wait, says which jobs it stops, and exits 130; a second Ctrl+C, or one SIGTERM/SIGHUP,
|
||||
ends it at once (143/129). A run whose prompt failed no longer waits for its jobs.
|
||||
- **Nothing a command started outlives lembas.** Every command runs in a process group of its
|
||||
own; whatever is left in one when the program ends — by `/quit`, the end of a run or a signal —
|
||||
gets TERM, then KILL. A foreground command that ends but leaves a program running
|
||||
(`server &`) says so in its result. A program that must outlive lembas has to leave the
|
||||
group (`setsid`); `nohup … &` alone does not.
|
||||
- **Texts that named what does not exist.** The prompt for Claude-family models told them to
|
||||
use a `todo` tool with statuses the plan does not have (it is `plan_write`/`plan_update`,
|
||||
`doing` and `done`); a question answered with a question told the model to "call question
|
||||
again" (the tool is `ask_user`); `--help` showed `--model conn/model` (2.0 has no connection
|
||||
prefix: a model is named by its id); `SECURITY.md` spoke of an `unrestricted` mode (`auto`).
|
||||
A check now fails when a prompt, a tool description or a tool's result names a tool that does
|
||||
not exist.
|
||||
- **`/trust` makes the project directory** when the project has none — `/tasks`, `/decisions`
|
||||
and `/decide` said "/trust creates it", and it did not — and says `/reload` loads the
|
||||
project's config (it said to restart).
|
||||
- A command that could not be started says why instead of "stopped (SIGTERM)".
|
||||
- **One name for the server.** Texts said "LLeMbas instance" in some places and "LLeMbas server"
|
||||
in others — one screen used both — and still spoke of 1.x's "connections" and "webui
|
||||
connections". They now say "LLeMbas server" and "sign-in"; `lembas logout [name]`. "Forge" is
|
||||
gone from what a person reads. `lembas remote --help` lists `files_that_run_code` in its JSON.
|
||||
- A folder named like `..cache` in the project is shown relative to the project in the prompt,
|
||||
in approvals and in the editor, as any other folder.
|
||||
- **In a LLeMbas terminal an answer is bound to the approval it was given for.** What the display
|
||||
asks now carries a number (`approval#12 yn …`); `/approve 12`, `/always 12` and `/deny 12`
|
||||
decide only that approval, and an answer meant for one that has since closed is refused in
|
||||
words instead of approving the next. Without a number they work as before, and so does
|
||||
`/answer <n>`. A line too long for the terminal's ask line ends in "…". `lembas --version
|
||||
--json` lists `terminal_ask_id`.
|
||||
- **"Always" on a file outside the project now holds.** It remembered the file for its tool but
|
||||
not that the file may be reached outside the project, so the next identical call asked again.
|
||||
The outside path is now remembered too, for the session only — it is never written into the
|
||||
project's configuration. "Always in this project" no longer fails the approved call when the
|
||||
project's configuration cannot be written; the rule then holds for the session.
|
||||
- **The updater never moves to a new major version by itself.** The newest release of the
|
||||
version's own major is installed; a later major (which may need a newer LLeMbas server) is
|
||||
named — in `lembas update` and once an hour at most in the TUI — and installed only when you
|
||||
name it: `lembas update v3.0.0`.
|
||||
- **A version you chose stays.** After `lembas update vX.Y.Z` or `lembas update --rollback` the
|
||||
next start installed the newest release again. Automatic updates now pause until you run
|
||||
`lembas update` yourself, and both commands say so.
|
||||
- **A slow connection no longer fails every update.** A download had 30 seconds in all — too
|
||||
little for the release binary below about 11 Mbit/s; the limit is now 30 seconds of silence.
|
||||
- `lembas update` says an ordinary failure (no network, nothing kept to roll back to) in one
|
||||
line instead of printing a program stack.
|
||||
|
||||
### Terminal — LLeMbas TTY is now LLeMbas TERM
|
||||
|
||||
- **The terminal was renamed, and the names it gives the CLI with it (harness spec 3.15.0,
|
||||
terminal contract 4).** A LLeMbas terminal now sets `LLEMBAS_TERM`, `LLEMBAS_TERM_PANE`,
|
||||
`LLEMBAS_TERM_EXECUTABLE` and `LLEMBAS_TERM_STATUS_DIR`; a pane's status record starts
|
||||
`llembas-term-status=1`, the input mark `llembas-term-input=1`, and the default status
|
||||
directory is `llembas-term`. Nothing else changes.
|
||||
- **A terminal from before the rename keeps working unchanged**: `LLEMBAS_TTY…`,
|
||||
`llembas-tty-status=1`, `llembas-tty-input=1` and the `llembas-tty` directory are still read.
|
||||
One family of names at a time, the new one first — a renamed terminal started from inside an
|
||||
older one is never given the older one's pane.
|
||||
- `lembas --version --json` says `terminal_contract: 4` and the capability `terminal_names_2`,
|
||||
which a terminal that exports only the new names checks.
|
||||
|
||||
## [2.0.0-beta.20] — 2026-12-02
|
||||
|
||||
### Terminal — you run the command, and the terminal remembers what you chose
|
||||
|
||||
+2
-2
@@ -32,7 +32,7 @@ untrusted. A report is most useful when it shows one of these:
|
||||
- secrets — API keys, OAuth tokens — written somewhere readable, logged, or sent to a host other
|
||||
than the one they belong to.
|
||||
|
||||
A model doing something unwise **with** the user's approval, or in `unrestricted` mode, is how
|
||||
A model doing something unwise **with** the user's approval, or in `auto` mode, is how
|
||||
LLeMbas CLI is meant to work, not a vulnerability; ways to make that clearer are still welcome as
|
||||
ordinary issues ([GitHub Issues](https://github.com/LLeMbas/LLeMbas-CLI/issues)).
|
||||
|
||||
@@ -54,4 +54,4 @@ ssh-keygen -Y verify -f allowed -I lembas-release -n lembas-release -s SHA256SUM
|
||||
sha256sum -c --ignore-missing SHA256SUMS
|
||||
```
|
||||
|
||||
Tags and commits are signed too (SSH signatures, shown as verified on the forge).
|
||||
Tags and commits are signed too (SSH signatures, shown as verified where the repository is hosted).
|
||||
@@ -11,19 +11,19 @@
|
||||
# stops and says so — it does not quietly build whatever the main branch holds instead.
|
||||
#
|
||||
# Environment:
|
||||
# LEMBAS_FORGE where releases come from (default https://github.com); a Gitea or Forgejo
|
||||
# (https://git.example.org) is told apart by its API
|
||||
# LEMBAS_FORGE the server releases come from (default https://github.com); a Gitea or
|
||||
# Forgejo server (https://git.example.org) is told apart by its API
|
||||
# LEMBAS_SLUG owner/name of the repository (default LLeMbas/LLeMbas-CLI)
|
||||
# LEMBAS_CHANNEL stable (default) or beta: also vX.Y.Z-beta.N, whichever is newest
|
||||
# LEMBAS_REF a release tag (v1.2.3) to install instead of the newest; or a branch (main),
|
||||
# which is built from source
|
||||
# LEMBAS_PUBKEY the ssh-ed25519 key SHA256SUMS.sig must be signed with (a build of your own)
|
||||
# LEMBAS_VERIFY signature (default) or checksum: no signature asked for (an unsigned source)
|
||||
# LEMBAS_TOKEN for a private repository on the forge
|
||||
# LEMBAS_TOKEN for a private repository
|
||||
# LEMBAS_FROM source: clone and build instead (needs git; fetches Bun if it is missing)
|
||||
# LEMBAS_REPO what to clone for a source build (default: the forge's <slug>.git)
|
||||
# LEMBAS_REPO what to clone for a source build (default: <LEMBAS_FORGE>/<slug>.git)
|
||||
# LEMBAS_SRC where a source build keeps the source (default ~/.local/share/lembas/src)
|
||||
# LEMBAS_API the releases API, when it is not where the forge's name says
|
||||
# LEMBAS_API the releases API, when it is not where LEMBAS_FORGE says
|
||||
#
|
||||
# A release needs curl, sha256sum, gzip and ssh-keygen (openssh-client). Nothing runs as root.
|
||||
# Linux only: x86-64 and arm64.
|
||||
@@ -123,10 +123,19 @@ check_signature() {
|
||||
# The signed list says which version it is for: an old release's files under a new tag are refused.
|
||||
local version
|
||||
version="$(sed -n -E 's/^# lembas (.*)$/\1/p' "$dir/SHA256SUMS" | head -n1)"
|
||||
if [ -n "$version" ] && [ "v$version" != "$tag" ]; then
|
||||
echo "get.sh: release $tag carries the files of $version — nothing installed" >&2
|
||||
return 1
|
||||
fi
|
||||
version_line_ok "$VERIFY" "$version" "$tag"
|
||||
}
|
||||
|
||||
# The list's version line against the tag — the updater's rule (src/update/index.ts
|
||||
# versionLineRefusal; both are tested against tests/fixtures/release-version.json). A signed list
|
||||
# must name the version tagged; with LEMBAS_VERIFY=checksum a list without the line is taken, one
|
||||
# naming another version never is.
|
||||
version_line_ok() {
|
||||
local verify="$1" listed="$2" tag="$3"
|
||||
[ "v$listed" = "$tag" ] && return 0
|
||||
[ -z "$listed" ] && [ "$verify" = checksum ] && return 0
|
||||
echo "get.sh: release $tag carries the files of ${listed:-an unnamed version} — nothing installed" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# Fetch a release's SHA256SUMS (+ signature) and the named files into $TMP, and check them all.
|
||||
|
||||
+100
-2
@@ -22,7 +22,7 @@ page *Harness-parity* in LLeMbas CLI's wiki.
|
||||
| `permission/defaults.json` | The rules every session starts from |
|
||||
| `permission/modes.json` | The four modes — manual, edit, auto, plan — as what each does with each risk class |
|
||||
| `models/schema.json` | Model metadata: context, output limit, efforts and the thinking switch, vision, tools, notes, capacity (`parallel`); `levels` — the effort levels a chat offers and what each sends |
|
||||
| `loop.json` | How one prompt runs: the step backstop, budgets, wrap-up, nudges, parallel calls, capacity; `jobs` — background work, its marks and limits; `subagents` — the model refusals, what names a model, the setting's label; `team` — a team's size, names, marks, refusals and texts; `progress` — the phases' texts; `context` — result ids, stubs, the output cap, the compaction table, the environment lines, the session notes; `scheduled` (3.5.0) — scheduled work on a linked computer: the setting, the modes, the approval wait, the sentinel, the watch command's limits and the refusals; `phone` (3.6.0) — phone actions: the capability, each action's fields, what is required and checked, the wait and the texts; `display` (3.7.0) — a call's title keys, states and facts, the blocks, the cards' actions; `scheduled.notify` (3.8.0) — notify-when and its texts; `pages` (3.8.0) — the fence word, the frame's variables, the note and the projection; `interactive` (3.9.0) — interactive-only models: the field, the two sentences, what each background call does with nowhere to go; `editor` (3.11.0) — autocomplete, rewrite, the editor block, diff items and buffers: their limits; `files` (3.11.0) — device files and `show`: chunk, listing, upload and size limits; `terminal` (3.12.0) — a terminal as the client: the environment, the user vars, the context file and its block, the two tools, and a shell line completed; 3.13.0, contract 2 — the display, the tool profile, the status record and the wait, what is new of a context, the two models; 3.14.0, contract 3 — a command placed at the prompt, the settings store |
|
||||
| `loop.json` | How one prompt runs: the step backstop, budgets, wrap-up, nudges, parallel calls, capacity; `jobs` — background work, its marks and limits; `subagents` — the model refusals, what names a model, the setting's label; `team` — a team's size, names, marks, refusals and texts; `progress` — the phases' texts; `context` — result ids, stubs, the output cap, the compaction table, the environment lines, the session notes; `scheduled` (3.5.0) — scheduled work on a linked computer: the setting, the modes, the approval wait, the sentinel, the watch command's limits and the refusals; `phone` (3.6.0) — phone actions: the capability, each action's fields, what is required and checked, the wait and the texts; `display` (3.7.0) — a call's title keys, states and facts, the blocks, the cards' actions; `scheduled.notify` (3.8.0) — notify-when and its texts; `pages` (3.8.0) — the fence word, the frame's variables, the note and the projection; `interactive` (3.9.0) — interactive-only models: the field, the two sentences, what each background call does with nowhere to go; `editor` (3.11.0) — autocomplete, rewrite, the editor block, diff items and buffers: their limits; `files` (3.11.0) — device files and `show`: chunk, listing, upload and size limits; `terminal` (3.12.0) — a terminal as the client: the environment, the user vars, the context file and its block, the two tools, and a shell line completed; 3.13.0, contract 2 — the display, the tool profile, the status record and the wait, what is new of a context, the two models; 3.14.0, contract 3 — a command placed at the prompt, the settings store; 3.15.0, contract 4 — the terminal renamed LLeMbas TERM: the names, and the ones from before the rename that are also read |
|
||||
| `filesystem.md` | The file system a session works in: paths, node kinds, the four access levels, errors, listings, search and indexing by tokens, stacked instruction files, skills, memory |
|
||||
| `context.md` | Context hygiene: what happens to a tool result when it is inserted, and never afterwards; the prefix that stays still; reasoning sent back during its turn; no absolute paths in the prompt; the `<terminal>` block (3.12.0) |
|
||||
| `team.md` | Teams: a lead and the members it adds, the size setting, the room, who receives what, reports, a manager's refusals, capacity, stopping |
|
||||
@@ -37,7 +37,7 @@ page *Harness-parity* in LLeMbas CLI's wiki.
|
||||
| `quirks.json` | What real servers do, and how both harnesses cope |
|
||||
| `connection.md`, `connection.json` | LLeMbas connection 1: how every LLeMbas product connects to another — the one address rule and which address is stored (the typed one, normalised), discovery and its outcomes, `min_clients`, how a product names itself (`llembas-<product>/<version>`), versions judged both ways, a refused token, the link's handshake, close codes (4409: replaced) and liveness, the one reconnect schedule, state between programs as codes, and the table of conditions → code → sentence. The numbers, names and words are the JSON; `conformance/address.json`, `version.json` and `errors.json` are its cases |
|
||||
| `conformance/<area>.json` | Cases with their expected results, run by both test suites |
|
||||
| `acp.md` | The link between them: ACP plus every `_lembas/*` method, field and capability; scheduled work on a linked computer (3.5.0) and the two types of schedule, Chat and Agentic (3.9.0); the model last used in a directory (3.9.0); a turn the harness starts by itself, over the link (3.10.0); an editor as the client, device files, and files that are not text shown in the chat (3.11.0); a terminal as the client (3.12.0), the terminal's display, contract 2 (3.13.0), and a command placed at the prompt and the terminal's settings, contract 3 (3.14.0) |
|
||||
| `acp.md` | The link between them: ACP plus every `_lembas/*` method, field and capability; scheduled work on a linked computer (3.5.0) and the two types of schedule, Chat and Agentic (3.9.0); the model last used in a directory (3.9.0); a turn the harness starts by itself, over the link (3.10.0); an editor as the client, device files, and files that are not text shown in the chat (3.11.0); a terminal as the client (3.12.0), the terminal's display, contract 2 (3.13.0), and a command placed at the prompt and the terminal's settings, contract 3 (3.14.0); the terminal renamed LLeMbas TERM, contract 4 (3.15.0) |
|
||||
|
||||
## Vocabulary
|
||||
|
||||
@@ -80,6 +80,104 @@ page *Harness-parity* in LLeMbas CLI's wiki.
|
||||
approval in plan mode and answers its `unavailable` text outside it. Their permission key is
|
||||
`plan` (`permission/defaults.json`), which a rule written for the former `todo` key still reaches.
|
||||
|
||||
## 3.15.0
|
||||
|
||||
- **The terminal is renamed LLeMbas TERM: terminal contract 4** (`acp.md`, *Recognising the
|
||||
terminal*, *The names before the rename*; `loop.json` `terminal.env`, `status`, `place.input`).
|
||||
No behaviour changes; every name the terminal gives the CLI does: `LLEMBAS_TERM`,
|
||||
`LLEMBAS_TERM_PANE`, `LLEMBAS_TERM_EXECUTABLE`, `LLEMBAS_TERM_STATUS_DIR`; a status record's
|
||||
first line `llembas-term-status=1`, an input mark's `llembas-term-input=1`; the default status
|
||||
directory `llembas-term`; the remote route's user var `llembas_term_status`. These are THE
|
||||
names. **The names from before the rename are also read** (`LLEMBAS_TTY…`, `llembas-tty-…`,
|
||||
`terminal.env.before` and the `…_before` keys), so the terminal's releases 1.0.0-beta.1 to 5
|
||||
work unchanged: a whole family at a time, the new one first, never a mix; a file's first line
|
||||
in either spelling.
|
||||
- `lembas --version --json`: `terminal_contract: 4`, capability **`terminal_names_2`** — what a
|
||||
terminal that exports only the new names checks first.
|
||||
- `connection.json` `products`: `term` — `llembas-term/<version>`, "LLeMbas TERM"; `tty` stays
|
||||
known for the terminal's releases before the rename.
|
||||
- **What a command touches is a rule, and it fails closed** (`permission/rules.md` §5;
|
||||
`permission/hardline.json` `commands`). A command's words are read as the shell will expand
|
||||
them — brace lists, `~`, `$HOME`/`$PWD`, globs — and a word that cannot be resolved (`~name`,
|
||||
any other variable, a sequence, a substitution) makes the line *unresolved*: never allowed by
|
||||
a rule, asked instead. A path riding on an option (`--opt=PATH`, `-fPATH`) or behind `name=`
|
||||
is a path; a quoted `>` is not a redirection; a `cd` moves where later paths are read.
|
||||
**Both implementations must change**: before, `cat .en{v,}`, `cat ~name/.ssh/key`,
|
||||
`wc --files0-from=.env` and `rg -f.env x` were allowed where `cat .env` asks.
|
||||
- **The protected paths hold for commands** (`rules.md` §5.5; `hardline.json`
|
||||
`commands.readers`): a redirection into one, or a command naming one whose program is not
|
||||
known to only read, is refused in every mode — `cp x ~/.ssh/authorized_keys` in auto mode
|
||||
was allowed.
|
||||
- **A line over `commands.max_bytes` (32 KiB) is not analysed and is asked about in every
|
||||
mode** (`rules.md` §5.6): the floor's patterns are quadratic on hostile input.
|
||||
- **`force-push-main` reads a push by its refspecs** (`hardline.json`: `check: git_push`, no
|
||||
pattern). No longer refused: a forced push to `feature/main-menu`. Now refused: `:main`,
|
||||
`--delete main`, `-d`, a forced `--all`/`--mirror`, and a forced push naming no branch when
|
||||
the current branch is known to be main or master. `conformance/hardline.json` has `branch`.
|
||||
- **A search does not read what `read` would ask about** (`filesystem.md`): `grep` returns no
|
||||
line of a file whose `read` is not allowed at that moment, and names the files left out;
|
||||
`glob` and `list` are names, not content, and unchanged. **Both implementations.**
|
||||
- **A custom command's `` !`…` `` is a `bash` call of the session** (`permission/rules.md` §6;
|
||||
the CLI's alone): judged in the session's mode, run only on `allow`, the arguments positional.
|
||||
- **The device's limits are judged on every request of an open session** (`acp.md`, *The
|
||||
device's limits*, *Which sessions a client may reach*; new area `conformance/limits.json`):
|
||||
a session that no longer fits is refused and stopped, one that fits is lowered to `max_mode`,
|
||||
an open terminal is closed; `cancel`, `status` and `delete` are always answered. Sessions the
|
||||
client was never shown and that lie outside the roots are out of reach of `sessions/list`,
|
||||
`session/status` and `session/title`. The device's alone; the server sees refusals it did not
|
||||
see before, and `_lembas/terminal/exit` may carry `code: null` with a `reason`.
|
||||
- **The settings tool is the person's alone** (`permission/rules.md` §1, `defaults.json`
|
||||
`user_only`; `conformance/rules.json`): for a call of a user-only permission only the
|
||||
`default` and `user` layers are read. A project's key that matches it — `settings`, `sett*`,
|
||||
`*` — and a rule made in the session are not read for it. **Both implementations**: before,
|
||||
a trusted project's `sett*: {"session *": allow}` opened it.
|
||||
- **Files that run code: both names of the project's directory** (`loop.json`
|
||||
`files.runs_code.project_dirs`, was `project_dir`; `acp.md`, *Files that run code*;
|
||||
`conformance/device_files.json`): `.lembas` as well as `.agent`. With
|
||||
`remote.files_that_run_code` off, `_lembas/fs/*` wrote `.lembas/config.yaml` and its commands.
|
||||
The CLI's edit mode reads the same list (one definition). **Both implementations; the key was
|
||||
renamed**, so a reader of `project_dir` must read `project_dirs`.
|
||||
- **"Always" makes what the card asked about** (`permission/rules.md` §3; `conformance/rules.json`
|
||||
`call`): a call asked about because it reaches outside the project is remembered with an
|
||||
`external_directory` rule for each such path as well, for the session only and never saved to
|
||||
a project. **Both implementations**: before, "always" on a file outside the project left the
|
||||
next identical call asked.
|
||||
- **Device files open regular files only** (`acp.md`, `_lembas/fs/read`): a named pipe, a device
|
||||
or a socket is refused `not_a_file` without being opened — opening a pipe waited for a writer
|
||||
and stopped the service. **Both implementations** (the server's file manager reads its own
|
||||
files the same way).
|
||||
- **A terminal context is removed only once it reads as one, and never from the CLI's own
|
||||
directories** (`acp.md`, *Terminal context*; `loop.json` `terminal.context.refusals.own`,
|
||||
the other refusals now say the file is left where it is; `conformance/terminal.json` `kind:
|
||||
file` takes `own`). **A context with no command and no screen is valid**, nothing attached
|
||||
(`texts.chip_empty`; `refusals.empty` is gone). **`lembas terminal` starts with a refused
|
||||
context** and says so. The CLI's alone.
|
||||
- **Shell lines that look as if they hold a secret: one table** (`loop.json` `terminal.secrets`,
|
||||
replacing `terminal.complete.history_secret`; `acp.md`; `conformance/terminal.json` `kind:
|
||||
secret`, with a list of ordinary commands that must not match). `lembas complete --shell`
|
||||
sends no such typed line (status 0, nothing printed, `texts.secret` on standard error); a
|
||||
terminal context's block with such a command reaches the model as `placeholder`, its output
|
||||
left out. Wider than before: assignments and `set`/`setenv` of a key-, token-, secret-,
|
||||
password- or credential-named variable, client passwords (`-p…`, `--password`, `--token`,
|
||||
`--api-key`, `--secret`, `-u user:pass`), `Authorization`/`Bearer`/`Basic`, `user:pass@` in an
|
||||
address, known key beginnings, long random words. The CLI's alone; the table is data for the
|
||||
terminal too.
|
||||
- **A status record that came by user var is never sole evidence** (`acp.md`, *The user var
|
||||
route*; `loop.json` `terminal.run.texts.unverified`; `conformance/terminal.json` `prompt`,
|
||||
`answer`): an end it alone reports is said as the remote shell's word, its exit status not
|
||||
given as known; it never makes a prompt free for placing or typing (the pane is read). The
|
||||
CLI's alone.
|
||||
- **Approvals bind to what was shown** (`acp.md`, `lembas_ask`; `loop.json`
|
||||
`terminal.surface.ask_id`, `texts.wrong_id`; capability **`terminal_ask_id`**;
|
||||
`conformance/terminal.json` `kind: ask_id`): `lembas_ask` is `approval#12 yn …` (the id 1–9
|
||||
digits), `/approve 12`, `/always 12`, `/deny 12` decide only for the id they name; `/answer
|
||||
<n>` as before (`/answer <id> <n>` bound too); no id, as before. A `lembas_ask` cut to fit ends
|
||||
in `…`. The CLI's alone.
|
||||
- **One answer to "inside a directory"** (`conformance/paths.json`, `op: within`): by whole names;
|
||||
a child named `..cache` is a child.
|
||||
- Conformance: every case of `conformance/terminal.json` is in the new names; cases of `env`,
|
||||
`status`, `status_dir` and `prompt` in the old ones; `errors.json` for the product `term`.
|
||||
|
||||
## 3.14.0
|
||||
|
||||
**Terminal contract 3**, written first for the round after the terminal was used for a day. The
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.14.0
|
||||
3.15.0
|
||||
+154
-43
@@ -1055,9 +1055,9 @@ the server's answer as it is. The server's refusal is `-32602` with its sentence
|
||||
`unknown_model`, `not_allowed`, `invalid`); a server before spec 3.11.0 is `unsupported`. The editor's own quick switch is the `model`
|
||||
of `_lembas/complete` and is saved nowhere.
|
||||
|
||||
## A terminal as the client (spec 3.12.0; contract 2: spec 3.13.0; contract 3: spec 3.14.0)
|
||||
## A terminal as the client (spec 3.12.0; contract 2: spec 3.13.0; contract 3: spec 3.14.0; contract 4: spec 3.15.0)
|
||||
|
||||
LLeMbas TTY is a terminal emulator with LLeMbas built in. **The agent is the CLI, unchanged in its
|
||||
LLeMbas TERM (LLeMbas TTY in its releases 1.0.0-beta.1 to 5, before it was renamed) is a terminal emulator with LLeMbas built in. **The agent is the CLI, unchanged in its
|
||||
role**: the terminal draws bars, splits panes and offers a prompt line, and for everything a
|
||||
model does it runs `lembas`. Its own layer is a script inside the terminal, which can start
|
||||
programs and panes, read a pane's text and type into one — but cannot hold a streaming connection.
|
||||
@@ -1074,7 +1074,7 @@ file and never publishes user vars. Nothing here changes the hardline, the modes
|
||||
tool.
|
||||
|
||||
Numbers and texts: `loop.json` `terminal`. Conformance: `conformance/terminal.json`.
|
||||
Contract version: **3** (`terminal.contract`). Contract 1 (spec 3.12.0) was: the environment, the
|
||||
Contract version: **4** (`terminal.contract`). Contract 1 (spec 3.12.0) was: the environment, the
|
||||
user vars, the context file of version 1, the two tools — `terminal_run` typing without waiting
|
||||
— and `lembas complete --shell`, with **the CLI's TUI in a split pane** as what the person saw.
|
||||
Contract 2 (spec 3.13.0) keeps every part of it working and adds *The terminal's display*,
|
||||
@@ -1086,7 +1086,12 @@ own Enter is the approval (*A command placed at the prompt*); and **the terminal
|
||||
one store on this machine, machine-wide and per working directory** (*The terminal's settings*),
|
||||
which the display and `lembas complete --shell` use. **A terminal written for contract 1 or 2 is
|
||||
served as before**: every byte it sends still means what it meant; what a contract 2 terminal
|
||||
sees differently is said under *A terminal written for contract 2*.
|
||||
sees differently is said under *A terminal written for contract 2*. Contract 4 (spec 3.15.0)
|
||||
changes no behaviour: **the terminal is renamed LLeMbas TERM, and every name it gives the CLI is
|
||||
renamed with it** — the variables, the first line of a status record and of an input mark, the
|
||||
default status directory and the remote route's user var. The names in this section are THE
|
||||
names; the ones from before the rename are **also read, from terminals before the rename**
|
||||
(*The names before the rename*).
|
||||
|
||||
### Recognising the terminal
|
||||
|
||||
@@ -1094,19 +1099,59 @@ The terminal sets, in the environment of every pane:
|
||||
|
||||
| Variable | Value |
|
||||
|---|---|
|
||||
| `LLEMBAS_TTY` | the terminal's version (`1.0.0`); any non-empty value |
|
||||
| `LLEMBAS_TTY_PANE` | the pane's id, decimal (`7`) |
|
||||
| `LLEMBAS_TTY_EXECUTABLE` | the absolute path of the terminal's command-line program |
|
||||
| `LLEMBAS_TTY_STATUS_DIR` | contract 2, optional: the absolute path of the directory the panes' status records are in (*A command typed, and how it ended*) |
|
||||
| `LLEMBAS_TERM` | the terminal's version (`1.0.0`); any non-empty value |
|
||||
| `LLEMBAS_TERM_PANE` | the pane's id, decimal (`7`) |
|
||||
| `LLEMBAS_TERM_EXECUTABLE` | the absolute path of the terminal's command-line program — the CLI runs this path and never a program by name |
|
||||
| `LLEMBAS_TERM_STATUS_DIR` | contract 2, optional: the absolute path of the directory the panes' status records are in (*A command typed, and how it ended*) |
|
||||
|
||||
**Without `LLEMBAS_TTY`, nothing in this section applies and the CLI behaves exactly as before,
|
||||
**Without `LLEMBAS_TERM`, nothing in this section applies and the CLI behaves exactly as before,
|
||||
byte for byte**: no user var is written, the two tools are not in any tool list, and a context
|
||||
file named on the command line is refused in words and left where it is. The other two are read
|
||||
only with it: a `LLEMBAS_TTY_PANE` that is not a decimal number, or a
|
||||
`LLEMBAS_TTY_EXECUTABLE` that is not an absolute path of plain text, is taken as absent
|
||||
only with it: a `LLEMBAS_TERM_PANE` that is not a decimal number, or a
|
||||
`LLEMBAS_TERM_EXECUTABLE` that is not an absolute path of plain text, is taken as absent
|
||||
(`kind: env`). The environment is the person's: a project's configuration cannot set any of
|
||||
this.
|
||||
|
||||
#### The names before the rename (contract 4, spec 3.15.0)
|
||||
|
||||
The terminal's releases 1.0.0-beta.1 to 5 were named LLeMbas TTY and say everything above in
|
||||
their own names. **The CLI reads both, the new first**, so those terminals keep working
|
||||
unchanged, and a renamed terminal exports only the new names:
|
||||
|
||||
| What | The name | Also read, from terminals before the rename |
|
||||
|---|---|---|
|
||||
| the version variable | `LLEMBAS_TERM` | `LLEMBAS_TTY` |
|
||||
| the pane | `LLEMBAS_TERM_PANE` | `LLEMBAS_TTY_PANE` |
|
||||
| the program | `LLEMBAS_TERM_EXECUTABLE` | `LLEMBAS_TTY_EXECUTABLE` |
|
||||
| the status directory | `LLEMBAS_TERM_STATUS_DIR` | `LLEMBAS_TTY_STATUS_DIR` |
|
||||
| the default status directory's name | `llembas-term` | `llembas-tty` |
|
||||
| a status record's first line | `llembas-term-status=1` | `llembas-tty-status=1` |
|
||||
| an input mark's first line | `llembas-term-input=1` | `llembas-tty-input=1` |
|
||||
| the remote route's user var (the terminal reads it) | `llembas_term_status` | `llembas_tty_status` |
|
||||
|
||||
(`loop.json` `terminal.env.before`, `status.magic_before`, `status.dir_name_before`,
|
||||
`status.uservar_before`, `place.input.magic_before`.) The rules, each with its conformance case:
|
||||
|
||||
1. **A whole family, never a mix.** When `LLEMBAS_TERM` is set and not empty, the four variables
|
||||
are read in the new names only. Otherwise, when `LLEMBAS_TTY` is set and not empty, in the old
|
||||
names only. A renamed terminal started from inside an older one inherits the older one's
|
||||
variables: its pane and its program must never be completed from them — a pane id of another
|
||||
terminal is a command typed into the wrong place.
|
||||
2. **The default status directory follows the family**: `llembas-term` for the new names,
|
||||
`llembas-tty` in a terminal that spoke the old ones, under the same two parents. A directory
|
||||
the terminal named in its family's variable is taken as before.
|
||||
3. **The first line of a status record and of an input mark is read in either spelling**,
|
||||
whichever family the environment spoke: the file says what it is by itself, and nothing else
|
||||
of it differs.
|
||||
4. **What the CLI says is said in the new names**: its sentences name `LLEMBAS_TERM`, except the
|
||||
one that names the program's variable, which names the one that was read.
|
||||
5. Everything the CLI itself is named by is unchanged — the user vars `lembas_*`, the context
|
||||
file, `lembas terminal`, `lembas complete --shell`.
|
||||
|
||||
A terminal that exports only the new names checks **`terminal_names_2`** in `capabilities`
|
||||
(below) before it relies on them: a CLI without it reads only the names from before the rename
|
||||
and would not know it runs in a terminal at all.
|
||||
|
||||
A terminal multiplexer between the CLI and the terminal (`TMUX`, `STY` or `ZELLIJ` set —
|
||||
`terminal.env.multiplexers`) keeps escape sequences to itself and hands on the variables of the
|
||||
pane it was started in. There the user vars are not written; a context file is still read (it
|
||||
@@ -1116,10 +1161,11 @@ names its pane itself).
|
||||
exits 0:
|
||||
|
||||
```json
|
||||
{ "name": "lembas", "version": "2.0.0", "harness_spec": "3.14.0", "terminal_contract": 3,
|
||||
{ "name": "lembas", "version": "2.0.0", "harness_spec": "3.15.0", "terminal_contract": 4,
|
||||
"capabilities": ["terminal_state", "terminal_context", "terminal_tools", "complete_shell",
|
||||
"terminal_surface", "terminal_await", "terminal_context_2", "terminal_models",
|
||||
"terminal_settings", "terminal_placed"] }
|
||||
"terminal_settings", "terminal_placed", "terminal_names_2",
|
||||
"terminal_ask_id"] }
|
||||
```
|
||||
|
||||
**A terminal decides by this, not by the version number**: the CLI is new enough when
|
||||
@@ -1134,7 +1180,9 @@ vars; `terminal_await` — a typed command waited for by the pane's status recor
|
||||
`terminal_settings` — the settings store, `lembas terminal settings` and its use by the display
|
||||
and by `lembas complete` (with `--debug`); `terminal_placed` — manual mode places a command at
|
||||
the prompt, the `placed` kind of `lembas_ask`, the `ran` key of a status record and the input
|
||||
mark. A CLI from before this
|
||||
mark; and from contract 4 `terminal_names_2` — the names of LLeMbas TERM are read (*The names
|
||||
before the rename*); `terminal_ask_id` (spec 3.15.0) — `lembas_ask` carries the id of what is
|
||||
asked (`approval#12 …`), and `/approve`, `/always`, `/deny` (and `/answer` with two words) take it. A CLI from before this
|
||||
section prints its bare version for the same arguments — one line that is not JSON — which is
|
||||
how a terminal tells it is too old. `lembas --version` alone is unchanged.
|
||||
|
||||
@@ -1155,7 +1203,7 @@ environment to the terminal's program when it runs it.
|
||||
|
||||
### Session state for the terminal's bars: user vars
|
||||
|
||||
When `LLEMBAS_TTY` is set, standard output is a terminal and no multiplexer is in between, the
|
||||
When `LLEMBAS_TERM` is set, standard output is a terminal and no multiplexer is in between, the
|
||||
interactive TUI publishes its state by setting **user vars** on its pane:
|
||||
|
||||
```
|
||||
@@ -1232,8 +1280,11 @@ terminal does not know; `output` the end of what the command printed. `screen` i
|
||||
visible screen, for a terminal that has no command blocks to offer or a person who chose the
|
||||
screen.
|
||||
|
||||
**The CLI reads the file once and removes it** — whatever it then makes of the content — so what
|
||||
a screen showed does not stay on disk. Before it opens it (`kind: file`):
|
||||
**The CLI reads the file once, and removes it once it has read as a context** — the format's
|
||||
`version` known, the rest whatever it holds — so what a screen showed does not stay on disk. A
|
||||
file that does not read as one (too large, not JSON, another version) is not used **and left
|
||||
where it is**: a wrong path is never a way to delete a file (spec 3.15.0; before, a file was
|
||||
removed whatever it held). Before it opens it (`kind: file`):
|
||||
|
||||
- the path is made absolute (from the working directory) and must lie, with links in its
|
||||
directories followed, inside one of the person's own **runtime, temporary, state or data
|
||||
@@ -1242,6 +1293,8 @@ a screen showed does not stay on disk. Before it opens it (`kind: file`):
|
||||
last because a terminal's runtime directory is there on a system without `XDG_RUNTIME_DIR`.
|
||||
A path anywhere else is refused: **not read and not removed**, so the option cannot be turned
|
||||
into a way to delete a file of the person's;
|
||||
- **nor one of the CLI's own directories** — its configuration, data and state (`own`, spec
|
||||
3.15.0): its session database and sign-in lie inside the data and state directories above;
|
||||
- the file itself must be **a regular file, not a link**, **owned by the person**, and writable
|
||||
by nobody else. Refused otherwise, and left where it is.
|
||||
|
||||
@@ -1261,16 +1314,23 @@ byte, and removed. What was read is checked (`kind: context`):
|
||||
rest counted; a `command` is trimmed and keeps its first `command_max_chars`; an `exit` that is not a whole
|
||||
number is `null`; an `output` that is not a string is absent, and one that is keeps its **last**
|
||||
`output_max_lines` lines and `output_max_chars` characters, the lines left out counted;
|
||||
- **a block whose command looks as if it holds a secret** (`terminal.secrets`, the entries
|
||||
without `only`; spec 3.15.0): its `command` becomes `terminal.secrets.placeholder` and its
|
||||
`output` is left out, so neither reaches the model; its `exit` stays;
|
||||
- `screen`: a string, its last `screen_max_lines` lines and `screen_max_chars` characters;
|
||||
- **strings only, and plain**: escape sequences (CSI, OSC and the other `ESC` forms) are taken
|
||||
out of every text, then every control character but the line break and the tab; a carriage
|
||||
return ends its line like a line break; lines lose the white space at their end, and blank
|
||||
lines at the end of a text are dropped;
|
||||
- unknown fields are ignored; a file with no block and no screen left is refused as empty.
|
||||
- unknown fields are ignored. **A file with no block and no screen left is a context with
|
||||
nothing in it** (spec 3.15.0; it was refused as empty): accepted and removed, nothing is
|
||||
attached, and the transcript says `chip_empty`.
|
||||
|
||||
Each refusal is one sentence (`terminal.context.refusals`). On the command line it ends the
|
||||
command with status 2 before anything is started; in a running TUI it is a warning line and the
|
||||
session goes on.
|
||||
command with status 2 before anything is started — except `lembas terminal`, the display, which
|
||||
starts all the same and shows the sentence as a warning (spec 3.15.0): a context the terminal got
|
||||
wrong never leaves it without its display. In a running TUI it is a warning line and the session
|
||||
goes on.
|
||||
|
||||
**What is done with it.** The context is attached to the **next message the person sends** —
|
||||
the prompt of `lembas run`; in the TUI the next message that starts a turn — as **one
|
||||
@@ -1296,7 +1356,7 @@ Two tools (`tools/terminal_run.json`, `tools/terminal_read.json`), the main agen
|
||||
|
||||
- **could ever be met** — so the tools are in the session's list (`context.md` §10 rule 4) — when
|
||||
the session is a terminal's own (the TUI or `lembas run`, never one on the link or an
|
||||
editor's), `LLEMBAS_TTY` is set and `LLEMBAS_TTY_EXECUTABLE` names the terminal's program;
|
||||
editor's), `LLEMBAS_TERM` is set and `LLEMBAS_TERM_EXECUTABLE` names the terminal's program;
|
||||
- **is met** once a terminal context **naming a pane** has been received in this session. Until
|
||||
then a call answers the tool's `unavailable` text. The pane both tools act on is the pane of
|
||||
**the context received last** — the one the person showed. (The display is told a pane as it
|
||||
@@ -1311,8 +1371,8 @@ environment the CLI has, and wait at most `terminal.tools.timeout_seconds` (`kin
|
||||
|
||||
| Tool | Runs | Standard input |
|
||||
|---|---|---|
|
||||
| `terminal_run { command, why }` | `<LLEMBAS_TTY_EXECUTABLE> cli send-text --pane-id <pane> --no-paste` | the command, then one carriage return (U+000D) — what the Enter key sends. **Placed** (contract 3, the display's manual mode): the command alone, no carriage return |
|
||||
| `terminal_read { lines? }` | `<LLEMBAS_TTY_EXECUTABLE> cli get-text --pane-id <pane> --start-line -<lines>` | none |
|
||||
| `terminal_run { command, why }` | `<LLEMBAS_TERM_EXECUTABLE> cli send-text --pane-id <pane> --no-paste` | the command, then one carriage return (U+000D) — what the Enter key sends. **Placed** (contract 3, the display's manual mode): the command alone, no carriage return |
|
||||
| `terminal_read { lines? }` | `<LLEMBAS_TERM_EXECUTABLE> cli get-text --pane-id <pane> --start-line -<lines>` | none |
|
||||
|
||||
- **`terminal_run` types.** In contract 1 that was all: the answer said the command was typed
|
||||
and entered (`terminal.tools.texts.typed`). From contract 2 it then **waits for the command to
|
||||
@@ -1399,7 +1459,7 @@ Every row is one line of a known width — the pane's columns less the row's own
|
||||
does not fit is cut with `…`: nothing lines up by the length of a text. It is made for a third of
|
||||
a terminal, 30 to 60 columns.
|
||||
|
||||
- **Only in a LLeMbas terminal** (`LLEMBAS_TTY`), with standard input and output a terminal:
|
||||
- **Only in a LLeMbas terminal** (`LLEMBAS_TERM`), with standard input and output a terminal:
|
||||
else it ends with status 2 and the sentence (`terminal.surface.texts.not_terminal`, `no_tty`).
|
||||
- **`--window <id>`** names the terminal window (or tab) the display belongs to — 1 to 64 of
|
||||
`A–Z a–z 0–9 . _ -` (`surface.window_pattern`); needed. **One conversation per id**, below.
|
||||
@@ -1472,7 +1532,7 @@ The user vars of *Session state*, above, with two more (`terminal.state.surface_
|
||||
| Var | Value |
|
||||
|---|---|
|
||||
| `lembas_surface` | `display` — the pane is the terminal's display, not the CLI's TUI |
|
||||
| `lembas_ask` | empty; or what is asked now, one line: the kind (`approval` or `question`), the keys that answer it (`yn`, `yan`, `1-3n`), then the text — `approval yn terminal_run: make test`. A terminal shows it at its ask line, and sends the key the person presses there while the focus stays in their shell. Contract 3, a kind with **no keys**: **`placed <command>`** — a command stands at the person's prompt, placed by the agent and not run; nothing is to be sent for it: the terminal may hint at the person's cursor that Enter runs it and Ctrl+C dismisses it. A terminal takes a kind it does not know as nothing asked. |
|
||||
| `lembas_ask` | empty; or what is asked now, one line: the kind (`approval` or `question`), from spec 3.15.0 with the **id** of what is asked after a `#` (`terminal.surface.ask_id`: a whole number of 1 to 9 digits, new for each approval and each question of a card), the keys that answer it (`yn`, `yan`, `1-3n`), then the text — `approval#12 yn terminal_run: make test`. **An answer is bound to what was shown**: `/approve 12`, `/always 12`, `/deny 12` decide only while 12 is the id asked; another id decides nothing and is refused in words (`texts.wrong_id`). `/answer <n>` takes the option alone, as before (`/answer 13 2`, the id first, is bound too). Without an id the commands answer what is asked now, as before. A keypress carries no id; a terminal that showed one sends the command with it. **A value cut to fit `state.max_bytes` ends in `…`** (`ask_id.ellipsis`): the rest is in the display (`kind: ask_id`). Contract 3, a kind with **no keys**: **`placed <command>`** — a command stands at the person's prompt, placed by the agent and not run; nothing is to be sent for it: the terminal may hint at the person's cursor that Enter runs it and Ctrl+C dismisses it. A terminal takes a kind it does not know as nothing asked. |
|
||||
|
||||
- **`lembas_state` is `idle` only while a question would be taken as a new turn** — the session
|
||||
is up and nothing runs. `asking` while an approval or a question is open, **and while a call
|
||||
@@ -1555,17 +1615,17 @@ small **status record** for its pane.
|
||||
**The file route.** The record is the file
|
||||
|
||||
```
|
||||
<status directory>/pane-<LLEMBAS_TTY_PANE>.status
|
||||
<status directory>/pane-<LLEMBAS_TERM_PANE>.status
|
||||
```
|
||||
|
||||
where the status directory is `$LLEMBAS_TTY_STATUS_DIR` when the terminal set it (an absolute
|
||||
path), else `$XDG_RUNTIME_DIR/llembas-tty`, else `$XDG_STATE_HOME/llembas-tty`
|
||||
(`~/.local/state/llembas-tty`). The file is the person's own, mode `0600`, a regular file and
|
||||
where the status directory is `$LLEMBAS_TERM_STATUS_DIR` when the terminal set it (an absolute
|
||||
path), else `$XDG_RUNTIME_DIR/llembas-term`, else `$XDG_STATE_HOME/llembas-term`
|
||||
(`~/.local/state/llembas-term`). The file is the person's own, mode `0600`, a regular file and
|
||||
not a link, at most `status.max_bytes`, written whole (a temporary file in the same directory,
|
||||
then renamed over it). It is text, a `key=value` line each, the first line the format:
|
||||
|
||||
```
|
||||
llembas-tty-status=1
|
||||
llembas-term-status=1
|
||||
id=4242.1700000000
|
||||
seq=17
|
||||
state=prompt
|
||||
@@ -1578,7 +1638,7 @@ cwd=/home/user/project
|
||||
|
||||
| Key | Value |
|
||||
|---|---|
|
||||
| `llembas-tty-status` | `1`, the first line; a file that starts otherwise, or names another version, is no record |
|
||||
| `llembas-term-status` | `1`, the first line (`llembas-tty-status=1` from a terminal before the rename is the same line); a file that starts otherwise, or names another version, is no record |
|
||||
| `id` | the shell this record is of: 1 to 64 of `A–Z a–z 0–9 . _ : -`, the same for the life of that shell and different for another (its process id and start time) — needed |
|
||||
| `seq` | a whole number that goes **up by one at every prompt** — needed |
|
||||
| `state` | `prompt`: the shell stands at its prompt; `running`: a command was started and has not ended (written as a command starts, where the shell can — `seq` unchanged). Absent: `prompt` |
|
||||
@@ -1595,12 +1655,16 @@ record unreadable, and an unreadable record is no record (`kind: status`). A rec
|
||||
|
||||
**The user var route — a pane on another machine.** In a shell reached over SSH the file would
|
||||
be on the other machine. There the shell integration publishes the same text as the user var
|
||||
**`llembas_tty_status`** (`OSC 1337 ; SetUserVar`, base64, as *Session state*), and **the
|
||||
**`llembas_term_status`** (`OSC 1337 ; SetUserVar`, base64, as *Session state*), and **the
|
||||
terminal writes it to the pane's status file on this machine**, having dropped any `via` and
|
||||
`pid` line it held and added `via=uservar`. So the CLI reads one file, whichever route filled
|
||||
it. A record that came by user var is what the pane said of itself — any program printing to
|
||||
the pane can say it — so nothing is decided by it alone that matters: the password guard below
|
||||
never relies on it.
|
||||
never relies on it. **It is never sole evidence** (spec 3.15.0): an end, or a placed command's
|
||||
run, that only such a record reports is said with `run.texts.unverified` ("reported by the
|
||||
remote shell; not verified") and its exit status is not given as known; and it never makes a
|
||||
prompt count as free — the input mark is not read under it, the pane's last line is (*Only at an
|
||||
empty prompt*). It may still say a command runs: a refusal to type costs nothing.
|
||||
|
||||
**Before typing** (`kind: ready`):
|
||||
|
||||
@@ -1666,7 +1730,7 @@ certain first:
|
||||
`place.input.max_bytes`, written whole:
|
||||
|
||||
```
|
||||
llembas-tty-input=1
|
||||
llembas-term-input=1
|
||||
id=4242.1700000000
|
||||
seq=17
|
||||
typed=0
|
||||
@@ -1979,8 +2043,16 @@ suggestion for the terminal to show.
|
||||
of at most `history_line_max_chars`, read from the file's last `history_read_bytes` in the
|
||||
form the shell writes (bash: a line each, `#<time>` lines skipped; zsh: `: <time>:<n>;` taken
|
||||
off, a command continued over lines joined; fish: the `- cmd: ` lines). **A line that looks as
|
||||
if it holds a secret is left out** (`history_secret`: a password, a token, a key by name or by
|
||||
its well-known beginning), and so is one that repeats the line before it.
|
||||
if it holds a secret is left out** (`terminal.secrets`, every entry, `only: history` ones too;
|
||||
spec 3.15.0 — it was `history_secret`), and so is one that repeats the line before it.
|
||||
- **The typed line is checked first** (spec 3.15.0; `kind: secret`): one that looks as if it
|
||||
holds a secret by `terminal.secrets` — a variable named for a key, token, secret, password or
|
||||
credential being set; a password on a client's command line (`-p<value>`, `--password`,
|
||||
`--token`, `--api-key`, `--secret`, `-u user:pass`); an `Authorization:`, `Bearer` or `Basic`
|
||||
value; an address with `user:pass@`; a key by its well-known beginning; a long random word —
|
||||
is **not sent**: no request, nothing on standard output, status 0, the line `texts.secret` on
|
||||
standard error, and with `--debug` the name of the entry that matched (never the line). The
|
||||
table is data so a terminal can decide the same before it asks.
|
||||
- **The suggestion is model output** (`kind: suggestion`): escape sequences are taken out whole,
|
||||
everything from the first line break on is dropped, the control characters left are taken out,
|
||||
a repeat of the typed line at its start is taken off, it is cut to `suggestion_max_chars`, the
|
||||
@@ -2086,7 +2158,7 @@ Which paths they are is data, in one place — `loop.json` `files.runs_code`:
|
||||
| Key | What it names |
|
||||
|---|---|
|
||||
| `segments` (`.git`) | any path with a directory of that name in it: git's own directory and all in it. A repository as a whole is a folder like any other |
|
||||
| `project_dir` (`.agent`) and `project` (`config.yaml`, `agents`, `commands`, `skills`) | those names under a project's agent directory — its rules, its MCP servers, its commands, agents and skills — and the directory itself, which moved or copied into place would bring them all. Its other files (plans, notes) are documents |
|
||||
| `project_dirs` (`.agent`, `.lembas`) and `project` (`config.yaml`, `agents`, `commands`, `skills`) | those names under a project's agent directory — whichever of the names it goes by (spec 3.15.0: `.lembas` was not among them) — its rules, its MCP servers, its commands, agents and skills — and the directory itself, which moved or copied into place would bring them all. Its other files (plans, notes) are documents |
|
||||
| `home` | those paths under the home directory of the device's user: the shells' start-up files, the session's and git's own configuration, autostart entries. Also a folder that holds one |
|
||||
|
||||
Judged on the path given and on where it really is, like everything else. The list cannot be
|
||||
@@ -2108,7 +2180,7 @@ as above. A part file of an upload under way is never listed or found.
|
||||
|---|---|---|
|
||||
| `_lembas/fs/list` | `{ path?, hidden?: boolean }` | without `path`: `{ path: "", entries }`, the roots. With one: `{ path, parent, entries: Entry[], truncated? }` — directories first, then by name; names starting with a dot only with `hidden: true`; at most `files.list_max` (`truncated: true` beyond). `parent` is `""` at a root |
|
||||
| `_lembas/fs/stat` | `{ path, hash?: boolean }` | `Entry`, with `hash` (`sha256:` and the hex digest of the content) for a file when asked |
|
||||
| `_lembas/fs/read` | `{ path, offset?, length? }` | `{ path, size, mtime, offset, data: <base64>, eof, hash? }` — at most `files.chunk_max_bytes` an answer (the default `length`); `hash` when the answer is the whole file. A client reads a large file by `offset` until `eof`, and checks `size` and `mtime` stayed the same |
|
||||
| `_lembas/fs/read` | `{ path, offset?, length? }` | `{ path, size, mtime, offset, data: <base64>, eof, hash? }` — at most `files.chunk_max_bytes` an answer (the default `length`); `hash` when the answer is the whole file. A client reads a large file by `offset` until `eof`, and checks `size` and `mtime` stayed the same. Only a regular file is read: anything else — a named pipe, a device, a socket — is refused `not_a_file` without being opened (spec 3.15.0: opening a named pipe waited for a writer and stopped the device's service). The same for `hash` in `fs/stat` and for the file a `base` is checked against |
|
||||
| `_lembas/fs/write` | `{ path, data: <base64>, base?: string \| null, overwrite?: boolean, more?: boolean }`, then `{ upload, data, more? }` | the last or only part: `{ path, size, mtime, hash }`; a part with `more: true`: `{ upload, received }` |
|
||||
| `_lembas/fs/mkdir` | `{ path }` | `{ path }` — parents made; a directory already there is done |
|
||||
| `_lembas/fs/move` | `{ from, to, overwrite?: boolean }` | `{ path }` — `exists` when `to` is there and `overwrite` is not said; a directory is never overwritten |
|
||||
@@ -2176,11 +2248,50 @@ roots, it says `limits.roots: []` here and in `initialize`, and refuses every `s
|
||||
a directory outside its roots — so the client can tell a device that allows no folder yet from one
|
||||
that is not linked.
|
||||
|
||||
The device's limits apply to every request as they are at that moment. When what the hello and
|
||||
`initialize` said changes (the device's `remote:` block was edited — a folder added, remote work
|
||||
turned on), the device closes the link once no session is working — no turn runs or waits, and no
|
||||
session has work out (*A session that still has work out*) — and dials again at once, so the
|
||||
client hears the new limits.
|
||||
The device's limits apply to every request as they are at that moment — **to a session that is
|
||||
already open as to a new one** (spec 3.15.0 says how; `conformance/limits.json`). Every request
|
||||
that names a session is judged first by the rule a new session in that session's directory is
|
||||
judged by — remote work on, inside the roots, trusted:
|
||||
|
||||
- **A session that no longer fits is refused** (`-32602`, the sentence `session/new` there would
|
||||
get) from then on, whatever it was opened under — and **what it was doing is stopped**: its
|
||||
turn, the prompts waiting behind it, its subagents and its background commands. Turning remote
|
||||
work off at the device (`lembas remote disable`), taking a folder out of the roots, or
|
||||
withdrawing a project's trust is a stop, not a setting for the next session.
|
||||
- **A session that fits runs no looser than `max_mode`**: its mode is lowered before the request
|
||||
is acted on, so a session opened in `auto` runs its next tool call in `plan` once the device
|
||||
says `plan`.
|
||||
- **`session/cancel`, `_lembas/session/status` and `_lembas/session/delete` are always answered.**
|
||||
Stopping, asking and deleting are never refused for a limit (a delete has its own rule for
|
||||
sessions the client was never shown).
|
||||
- **A terminal's session** shared under the device's limits is judged the same way on every
|
||||
request that reaches it through the hub; one shared **by name** (`/remote`) is the person's own
|
||||
act and is reached whatever the limits say.
|
||||
- **An open terminal** (`_lembas/terminal/*`) is judged like `_lembas/terminal/open` whenever
|
||||
something is typed into it: with `remote.terminal` off, or its folder no longer accepted, it is
|
||||
closed — `_lembas/terminal/exit` with `code: null` and a `reason` sentence — and the input is
|
||||
dropped.
|
||||
|
||||
**The device does not wait for a request to do this.** It looks at its limits every few seconds;
|
||||
when they changed, it applies them at once to everything open — sessions stopped, modes lowered,
|
||||
terminals closed. Then, when what the hello and `initialize` said has changed, the device closes
|
||||
the link once no session is working — no turn runs or waits, and no session has work out (*A
|
||||
session that still has work out*) — and dials again at once, so the client hears the new limits.
|
||||
|
||||
### Which sessions a client may reach
|
||||
|
||||
Spec 3.15.0. On the link a client reaches the sessions it holds, the ones a terminal shares, the
|
||||
ones it was once shown (the device marks them), and — with remote work on — the ones stored under
|
||||
the roots. No request reaches any other, with remote work on or off:
|
||||
|
||||
- `_lembas/sessions/list` needs `cwd`, judged as `session/new` there; without one it is refused
|
||||
(`-32602`). It never lists the machine.
|
||||
- `_lembas/session/status` for a session out of reach answers as for one that does not exist:
|
||||
`exists: false`, no title, no plan, no jobs.
|
||||
- `_lembas/session/title` for one answers `-32602` "no such session" and renames nothing.
|
||||
|
||||
An editor on `serve --stdio` is the person's own program on their own machine: it has no limits
|
||||
and reaches every session.
|
||||
|
||||
### `_lembas/event` — agent → client
|
||||
|
||||
|
||||
@@ -1166,6 +1166,140 @@
|
||||
"expect": {
|
||||
"refused": "changed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Spec 3.15.0: the project's agent directory by its other name, .lembas — its config names MCP servers to run.",
|
||||
"kind": "path",
|
||||
"roots": [
|
||||
"/home/user"
|
||||
],
|
||||
"home": "/home/user",
|
||||
"own": [
|
||||
"/home/user/.config/lembas"
|
||||
],
|
||||
"protected": [
|
||||
"/home/user/.ssh"
|
||||
],
|
||||
"enabled": true,
|
||||
"max_mode": "auto",
|
||||
"links": {},
|
||||
"op": "write",
|
||||
"path": "/home/user/work/app/.lembas/config.yaml",
|
||||
"expect": {
|
||||
"refused": "runs_code"
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": "path",
|
||||
"roots": [
|
||||
"/home/user"
|
||||
],
|
||||
"home": "/home/user",
|
||||
"own": [
|
||||
"/home/user/.config/lembas"
|
||||
],
|
||||
"protected": [
|
||||
"/home/user/.ssh"
|
||||
],
|
||||
"enabled": true,
|
||||
"max_mode": "auto",
|
||||
"links": {},
|
||||
"op": "write",
|
||||
"path": "/home/user/work/app/.lembas/commands/deploy.md",
|
||||
"expect": {
|
||||
"refused": "runs_code"
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": "path",
|
||||
"roots": [
|
||||
"/home/user"
|
||||
],
|
||||
"home": "/home/user",
|
||||
"own": [
|
||||
"/home/user/.config/lembas"
|
||||
],
|
||||
"protected": [
|
||||
"/home/user/.ssh"
|
||||
],
|
||||
"enabled": true,
|
||||
"max_mode": "auto",
|
||||
"links": {},
|
||||
"op": "remove",
|
||||
"path": "/home/user/work/app/.lembas",
|
||||
"expect": {
|
||||
"refused": "runs_code"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Its documents are documents.",
|
||||
"kind": "path",
|
||||
"roots": [
|
||||
"/home/user"
|
||||
],
|
||||
"home": "/home/user",
|
||||
"own": [
|
||||
"/home/user/.config/lembas"
|
||||
],
|
||||
"protected": [
|
||||
"/home/user/.ssh"
|
||||
],
|
||||
"enabled": true,
|
||||
"max_mode": "auto",
|
||||
"links": {},
|
||||
"op": "write",
|
||||
"path": "/home/user/work/app/.lembas/plans/next.md",
|
||||
"expect": {
|
||||
"ok": true,
|
||||
"real": "/home/user/work/app/.lembas/plans/next.md"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Read, as any file.",
|
||||
"kind": "path",
|
||||
"roots": [
|
||||
"/home/user"
|
||||
],
|
||||
"home": "/home/user",
|
||||
"own": [
|
||||
"/home/user/.config/lembas"
|
||||
],
|
||||
"protected": [
|
||||
"/home/user/.ssh"
|
||||
],
|
||||
"enabled": true,
|
||||
"max_mode": "auto",
|
||||
"links": {},
|
||||
"op": "read",
|
||||
"path": "/home/user/work/app/.lembas/config.yaml",
|
||||
"expect": {
|
||||
"ok": true,
|
||||
"real": "/home/user/work/app/.lembas/config.yaml"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "With the device's setting on they are changed like any file.",
|
||||
"kind": "path",
|
||||
"roots": [
|
||||
"/home/user"
|
||||
],
|
||||
"home": "/home/user",
|
||||
"own": [
|
||||
"/home/user/.config/lembas"
|
||||
],
|
||||
"protected": [
|
||||
"/home/user/.ssh"
|
||||
],
|
||||
"enabled": true,
|
||||
"max_mode": "auto",
|
||||
"links": {},
|
||||
"op": "write",
|
||||
"path": "/home/user/work/app/.lembas/config.yaml",
|
||||
"files_that_run_code": true,
|
||||
"expect": {
|
||||
"ok": true,
|
||||
"real": "/home/user/work/app/.lembas/config.yaml"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -885,6 +885,21 @@
|
||||
"text": "This LLeMbas for Neovim needs LLeMbas CLI (a newer version) or later, and found 2.0.0-beta.3. Update LLeMbas CLI."
|
||||
}
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"kind": "state",
|
||||
"code": "client_too_old"
|
||||
},
|
||||
"vars": {
|
||||
"product": "term",
|
||||
"stdio": true,
|
||||
"version": "3.0.0"
|
||||
},
|
||||
"expect": {
|
||||
"code": "client_too_old",
|
||||
"text": "LLeMbas CLI 3.0.0 is newer than this LLeMbas TERM can use. Update LLeMbas TERM."
|
||||
}
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"kind": "state",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"about": "A command line → the id of the hardline rule it trips, or null. Checked raw and in its plain spelling (../permission/hardline.json).",
|
||||
"about": "A command line → the id of the hardline rule it trips, or null. Checked raw and in its plain spelling (../permission/hardline.json). `branch`: the branch checked out where the command runs, when the implementation knows it (force-push-main reads a push by its refspecs, spec 3.15.0).",
|
||||
"cases": [
|
||||
{
|
||||
"line": "rm -rf /",
|
||||
@@ -176,6 +176,111 @@
|
||||
{
|
||||
"line": "xargs rm -rf / < list",
|
||||
"expect": "rm-root"
|
||||
},
|
||||
{
|
||||
"line": "git push --force origin feature/main-menu",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push -f origin my-main-fix",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push --force-with-lease=main origin feature",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push origin feature:main",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push origin :main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push origin :refs/heads/master",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push --delete origin main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push -d origin master",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push origin --delete feature",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push -f origin feature:main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push origin +refs/heads/master",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push origin +feature",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push -uf origin main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push origin main --force",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push --force --all origin",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push --mirror backup",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push --all origin",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "sudo git -C repo push -f origin main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push -o ci.skip -f origin main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push -f",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push -f",
|
||||
"branch": "main",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push --force-with-lease origin HEAD",
|
||||
"branch": "master",
|
||||
"expect": "force-push-main"
|
||||
},
|
||||
{
|
||||
"line": "git push -f",
|
||||
"branch": "feature",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push",
|
||||
"branch": "main",
|
||||
"expect": null
|
||||
},
|
||||
{
|
||||
"line": "git push -f origin feature",
|
||||
"branch": "main",
|
||||
"expect": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
{
|
||||
"about": "The device's limits and a session that is already open (acp.md, *The device's limits*; spec 3.15.0). `limits` are the device's as they are when the request arrives (`require_trust` is off in these cases: trust is the device's own record), `session` the open session — its directory and its mode, `byName` when a terminal shared it by name — and `method` the request. The answer: `{refused, stop: true}` with the sentence a new session in that directory would get — the session's turn, what waits behind it and its background jobs are stopped — or `{mode}`: served, in that mode. LLeMbas: not run (the limits are the device's); CLI: acp/agent.ts openUnder.",
|
||||
"cases": [
|
||||
{
|
||||
"about": "Nothing changed: served in its mode.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"mode": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Remote work turned off under an open session: refused, and what it was doing is stopped.",
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/steer",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/configure",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/set_mode",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/session/compact",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/session/rewind",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/job/send",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/job/stop",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/jobs",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/team",
|
||||
"expect": {
|
||||
"refused": "remote work is off on this machine — lembas remote enable there (remote.enabled)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Its directory taken out of the roots.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/other"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"refused": "/srv/work/app is outside the directories this device accepts remote work in — to allow it, run lembas remote add <dir> there (remote.roots)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "A name that only begins like a root is not under it.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/wor"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"refused": "/srv/work/app is outside the directories this device accepts remote work in — to allow it, run lembas remote add <dir> there (remote.roots)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "No roots at all.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"refused": "this device allows no folders for remote work yet — lembas remote add <dir> there (remote.roots)",
|
||||
"stop": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "The mode lowered: the session runs no looser than the limit from the next request on.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "plan"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"mode": "plan"
|
||||
}
|
||||
},
|
||||
{
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "edit"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/steer",
|
||||
"expect": {
|
||||
"mode": "edit"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "A stricter mode of its own is kept.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "edit"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "manual"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"mode": "manual"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Stopping is never refused for a limit.",
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/cancel",
|
||||
"expect": {
|
||||
"mode": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Nor asking what it is doing.",
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/session/status",
|
||||
"expect": {
|
||||
"mode": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Nor deleting it (which has its own rule for sessions never shown).",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "_lembas/session/delete",
|
||||
"expect": {
|
||||
"mode": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "A terminal's session shared by name (/remote) is the person's own act: the limits do not decide.",
|
||||
"limits": {
|
||||
"enabled": false,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/app",
|
||||
"mode": "auto",
|
||||
"byName": true
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"mode": "auto"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "A directory named ..cache under a root is under it.",
|
||||
"limits": {
|
||||
"enabled": true,
|
||||
"roots": [
|
||||
"/srv/work"
|
||||
],
|
||||
"max_mode": "auto"
|
||||
},
|
||||
"session": {
|
||||
"cwd": "/srv/work/..cache",
|
||||
"mode": "auto"
|
||||
},
|
||||
"method": "session/prompt",
|
||||
"expect": {
|
||||
"mode": "auto"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"about": "Where an agent session works, as the model is told it and as its tools read a path (context.md §11, spec 3.2.0). `op: env` — `root` is the project root and `started` the directory the session was started in (both absolute); the answer is the environment block's lines about them, in order, from loop.json context.env — none naming an absolute path. `op: resolve` — `path` as a tool call gives it; the answer is the absolute path it means: relative paths against the project root, whatever `started` is, `.` and `..` by their text (filesystem.md, Paths); an absolute path as it is. LLeMbas: not run — a chat's paths are the server's tree's; CLI: prompt/assemble.ts, tool/tool.ts.",
|
||||
"about": "Where an agent session works, as the model is told it and as its tools read a path (context.md §11, spec 3.2.0). `op: env` — `root` is the project root and `started` the directory the session was started in (both absolute); the answer is the environment block's lines about them, in order, from loop.json context.env — none naming an absolute path. `op: resolve` — `path` as a tool call gives it; the answer is the absolute path it means: relative paths against the project root, whatever `started` is, `.` and `..` by their text (filesystem.md, Paths); an absolute path as it is. LLeMbas: not run — a chat's paths are the server's tree's; CLI: prompt/assemble.ts, tool/tool.ts. `op: within` (spec 3.15.0) — whether `path` is `dir` or under it, both absolute and as given: by whole names, never by a prefix of one, and never by a relative path's leading dots (a child named `..cache` is a child). Every rule that says \"inside\", \"under\" or \"outside\" a directory — the project, a root, a protected path — uses this one answer. LLeMbas: security/access.py; CLI: within.ts.",
|
||||
"cases": [
|
||||
{
|
||||
"about": "Started at the root: the project's name and nothing else.",
|
||||
@@ -84,6 +84,88 @@
|
||||
"started": "/home/ada/src/app",
|
||||
"path": "./docs//guide.md",
|
||||
"expect": "/home/ada/src/app/docs/guide.md"
|
||||
},
|
||||
{
|
||||
"about": "A directory is within itself.",
|
||||
"op": "within",
|
||||
"path": "/srv/app",
|
||||
"dir": "/srv/app",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"op": "within",
|
||||
"path": "/srv/app/src/a.ts",
|
||||
"dir": "/srv/app",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"about": "A name that begins like the directory's is not under it.",
|
||||
"op": "within",
|
||||
"path": "/srv/application",
|
||||
"dir": "/srv/app",
|
||||
"expect": false
|
||||
},
|
||||
{
|
||||
"about": "A child whose name begins with two dots is a child.",
|
||||
"op": "within",
|
||||
"path": "/srv/app/..cache",
|
||||
"dir": "/srv/app",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"op": "within",
|
||||
"path": "/srv/app/..cache/x",
|
||||
"dir": "/srv/app",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"op": "within",
|
||||
"path": "/srv/app/...",
|
||||
"dir": "/srv/app",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"about": "A parent is not within its child.",
|
||||
"op": "within",
|
||||
"path": "/srv",
|
||||
"dir": "/srv/app",
|
||||
"expect": false
|
||||
},
|
||||
{
|
||||
"about": "The root directory holds everything.",
|
||||
"op": "within",
|
||||
"path": "/etc/passwd",
|
||||
"dir": "/",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"op": "within",
|
||||
"path": "/",
|
||||
"dir": "/",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"about": "A trailing slash on the directory changes nothing.",
|
||||
"op": "within",
|
||||
"path": "/srv/app/x",
|
||||
"dir": "/srv/app/",
|
||||
"expect": true
|
||||
},
|
||||
{
|
||||
"op": "within",
|
||||
"path": "/srv/apple",
|
||||
"dir": "/srv/app/",
|
||||
"expect": false
|
||||
},
|
||||
{
|
||||
"about": "Spec 3.15.0: a directory named ..cache under the root is under it — said relative to the root, like any other (one answer to \"inside\", `within`).",
|
||||
"op": "env",
|
||||
"root": "/home/ada/src/app",
|
||||
"started": "/home/ada/src/app/..cache",
|
||||
"expect": [
|
||||
"Project: app (paths are relative to its root)",
|
||||
"Started in: ..cache (relative to the project root)"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"about": "A bash command line in a mode, with the default rules (and any extra rules given) → allow, ask or deny. The project root is /project and nothing named exists on disk.",
|
||||
"about": "A bash command line in a mode, with the default rules (and any extra rules given) → allow, ask or deny. The project root is /project and nothing named exists on disk. From spec 3.15.0 (permission/rules.md §5): cases with `about` say what they pin — a word the reader cannot resolve asks; a path riding on an option is a path; a command that may write a protected path is refused in every mode. `repeat: [text, n]` appends `text` n times to `line` (a line too long to analyse). `~` is the home directory of whoever runs the cases.",
|
||||
"cases": [
|
||||
{
|
||||
"mode": "manual",
|
||||
@@ -285,6 +285,357 @@
|
||||
}
|
||||
},
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Brace expansion is the shell's: this reads .env.",
|
||||
"mode": "manual",
|
||||
"line": "cat .en{v,}",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "…and a brace list of ordinary files is still read unasked.",
|
||||
"mode": "manual",
|
||||
"line": "cat src/{a,b}.ts",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "A sequence is not modelled: unresolved, so asked.",
|
||||
"mode": "manual",
|
||||
"line": "cat {1..3}.txt",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A brace without a comma is text.",
|
||||
"mode": "manual",
|
||||
"line": "git show HEAD@{1}",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "Quoted braces are text.",
|
||||
"mode": "manual",
|
||||
"line": "rg 'a{2,3}' src",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "~name is another home directory: not modelled, asked.",
|
||||
"mode": "manual",
|
||||
"line": "cat ~nobody/.ssh/id_ed25519",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "The same through a redirection.",
|
||||
"mode": "manual",
|
||||
"line": "cat < ~nobody/.ssh/id_ed25519",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A tilde that does not start the word is text.",
|
||||
"mode": "manual",
|
||||
"line": "git diff HEAD~3",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "A variable that is not one of the known ones: unresolved.",
|
||||
"mode": "manual",
|
||||
"line": "cat $XDG_CONFIG_HOME/app/secrets.yaml",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "head -c9999 $OLDPWD/x",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A variable expands inside double quotes too.",
|
||||
"mode": "manual",
|
||||
"line": "cat \"$f\"",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "…and not inside single quotes: a file named $f.",
|
||||
"mode": "manual",
|
||||
"line": "cat '$f'",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "$PWD is known: the working directory.",
|
||||
"mode": "manual",
|
||||
"line": "cat $PWD/README.md",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "$HOME is known, and outside the project.",
|
||||
"mode": "manual",
|
||||
"line": "cat $HOME/notes.txt",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A $ that begins no expansion is text.",
|
||||
"mode": "manual",
|
||||
"line": "grep -n \"foo$\" src/a.ts",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "An expansion in a search pattern is still not known.",
|
||||
"mode": "manual",
|
||||
"line": "grep \"$USER\" src/a.ts",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A path riding on a long option.",
|
||||
"mode": "manual",
|
||||
"line": "wc --files0-from=.env",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "wc --files0-from=list.txt",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "grep --file=.env -r x .",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A path glued to a short option.",
|
||||
"mode": "manual",
|
||||
"line": "rg -f.env x",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "rg -fpatterns.txt x",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "git blame --contents=.env x",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "Option values that are not paths resolve harmlessly.",
|
||||
"mode": "manual",
|
||||
"line": "git log --format=%H -n5",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "ls -la",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "tail -n +5 notes.txt",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "The pattern came by -e, glued: the first operand is a file.",
|
||||
"mode": "manual",
|
||||
"line": "grep -efoo .env",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A quoted > is not a redirection: .env is read.",
|
||||
"mode": "manual",
|
||||
"line": "grep '>' .env",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "An input redirection glued to its file.",
|
||||
"mode": "manual",
|
||||
"line": "cat <.env",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "ls 2>/dev/null",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "git status 2>&1",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "cat -- .env",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "name=PATH as an operand.",
|
||||
"mode": "manual",
|
||||
"line": "dd if=.env",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "edit",
|
||||
"line": "cat .en{v,}",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "Plan mode refuses a command it cannot allow.",
|
||||
"mode": "plan",
|
||||
"line": "cat .en{v,}",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Auto mode asks nothing.",
|
||||
"mode": "auto",
|
||||
"line": "cat .en{v,}",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "cd is not among the allowed commands; the files are judged where the line goes.",
|
||||
"mode": "manual",
|
||||
"line": "cd src && cat ../README.md",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "A protected path named by a command that is not known to only read: refused in every mode.",
|
||||
"mode": "auto",
|
||||
"line": "cp x ~/.ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "A redirection's target is written, whatever the command.",
|
||||
"mode": "auto",
|
||||
"line": "echo k >> ~/.ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "echo k >~/.gnupg/x",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "sed -i s/a/b/ ~/.ssh/config",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Through a wrapper.",
|
||||
"mode": "auto",
|
||||
"line": "sudo tee -a ~/.ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Through a shell's -c.",
|
||||
"mode": "auto",
|
||||
"line": "bash -c 'echo k >> ~/.ssh/authorized_keys'",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Inside a substitution.",
|
||||
"mode": "auto",
|
||||
"line": "echo $(cp x ~/.ssh/a)",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Relative to where cd went.",
|
||||
"mode": "auto",
|
||||
"line": "cd ~ && cp x .ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "(cd ~/.ssh; cp /tmp/x authorized_keys)",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Through a brace list.",
|
||||
"mode": "auto",
|
||||
"line": "cp x ~/.ss{h,x}/a",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "dd of=~/.ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "cp x $HOME/.ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"mode": "manual",
|
||||
"line": "cp x ~/.ssh/authorized_keys",
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Reading is not writing: a reader is not refused by the floor (auto mode asks nothing).",
|
||||
"mode": "auto",
|
||||
"line": "cat ~/.ssh/id_ed25519.pub",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "…and outside auto it is asked, as everything outside the project.",
|
||||
"mode": "manual",
|
||||
"line": "cat ~/.ssh/id_ed25519.pub",
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "ssh -i ~/.ssh/id_ed25519 example.org",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "ls ~/.ssh",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"mode": "auto",
|
||||
"line": "cp x notes/.sshrc",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "A line over hardline.json commands.max_bytes is not analysed: asked, in auto mode too.",
|
||||
"mode": "auto",
|
||||
"line": "rm",
|
||||
"repeat": [
|
||||
" -a",
|
||||
12000
|
||||
],
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"mode": "plan",
|
||||
"line": "ls",
|
||||
"repeat": [
|
||||
" -a",
|
||||
12000
|
||||
],
|
||||
"expect": "deny"
|
||||
},
|
||||
{
|
||||
"about": "Just under the limit it is analysed as any line.",
|
||||
"mode": "auto",
|
||||
"line": "rm",
|
||||
"repeat": [
|
||||
" -a",
|
||||
10000
|
||||
],
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "A short option's value is judged from where letters and digits end: nothing here is /a.ts.",
|
||||
"mode": "manual",
|
||||
"line": "git log -Lname:src/a.ts",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "A backslash makes the $ literal inside double quotes.",
|
||||
"mode": "manual",
|
||||
"line": "grep -n \"price: \\$5\" notes.txt",
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "A path glued after a cluster of short options.",
|
||||
"mode": "manual",
|
||||
"line": "rg -rf/etc/hostname x",
|
||||
"expect": "ask"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"about": "Which permission rule decides (permission/rules.md, spec 3.8.0; rule 2's set-aside 3.9.0). The rules by layer: `defaults` true — permission/defaults.json as the `default` layer; `user` and `project` — a configuration's permission map (a key's value an action, or a map of pattern → action, read in the order written); `made` — rules made during the session, in order, each `by` an `always` answer or a `menu`. With `request` (`permission`, `pattern`: what one call asks for): expect the action that decides, or null where no rule matches. With `set` (a rule a person makes now, by a menu): expect `result` — `unchanged` (the action is already in force), `refused` with the rule in its way as `by`, or `made` with `still`, the stricter narrower rules that still apply, in the order read. The same answers for a rule typed into a file as for one a menu wrote. LLeMbas: security/permission rules; CLI: src/permission/evaluate.ts.",
|
||||
"about": "Which permission rule decides (permission/rules.md, spec 3.8.0; rule 2's set-aside 3.9.0). The rules by layer: `defaults` true — permission/defaults.json as the `default` layer; `user` and `project` — a configuration's permission map (a key's value an action, or a map of pattern → action, read in the order written); `made` — rules made during the session, in order, each `by` an `always` answer or a `menu`. With `request` (`permission`, `pattern`: what one call asks for): expect the action that decides, or null where no rule matches. With `set` (a rule a person makes now, by a menu): expect `result` — `unchanged` (the action is already in force), `refused` with the rule in its way as `by`, or `made` with `still`, the stricter narrower rules that still apply, in the order read. The same answers for a rule typed into a file as for one a menu wrote. LLeMbas: security/permission rules; CLI: src/permission/evaluate.ts. Spec 3.15.0: a user-only permission (defaults.json `user_only`) is decided by the defaults and the user layer alone. With `call` (spec 3.15.0; a file tool's call in `mode`, the project root /project, `path` absolute) and `answer: always`: expect `first` (the action before), `made` (the rules the answer makes, each with `save`) and `then` (the same call after).",
|
||||
"cases": [
|
||||
{
|
||||
"about": "The defaults alone: a file is read, a .env asks.",
|
||||
@@ -662,6 +662,176 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "A project's rule keyed by a pattern that matches the settings tool is not read for it.",
|
||||
"defaults": true,
|
||||
"project": {
|
||||
"sett*": {
|
||||
"session *": "allow"
|
||||
}
|
||||
},
|
||||
"request": {
|
||||
"permission": "settings",
|
||||
"pattern": "session mode auto"
|
||||
},
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "Nor one keyed by the name, should a loader let it through.",
|
||||
"defaults": true,
|
||||
"project": {
|
||||
"settings": "allow"
|
||||
},
|
||||
"request": {
|
||||
"permission": "settings",
|
||||
"pattern": "set mode auto"
|
||||
},
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "Nor a project's rule for every tool.",
|
||||
"defaults": true,
|
||||
"project": {
|
||||
"*": "allow"
|
||||
},
|
||||
"request": {
|
||||
"permission": "settings",
|
||||
"pattern": "set mode auto"
|
||||
},
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "…which still decides the other tools.",
|
||||
"defaults": true,
|
||||
"project": {
|
||||
"*": "allow"
|
||||
},
|
||||
"request": {
|
||||
"permission": "edit",
|
||||
"pattern": "src/app.ts"
|
||||
},
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "Nor an \"always\" answer or a rule set in a menu.",
|
||||
"defaults": true,
|
||||
"made": [
|
||||
{
|
||||
"permission": "settings",
|
||||
"pattern": "*",
|
||||
"action": "allow",
|
||||
"by": "always"
|
||||
},
|
||||
{
|
||||
"permission": "settings",
|
||||
"pattern": "*",
|
||||
"action": "allow",
|
||||
"by": "menu"
|
||||
}
|
||||
],
|
||||
"request": {
|
||||
"permission": "settings",
|
||||
"pattern": "set mode auto"
|
||||
},
|
||||
"expect": "ask"
|
||||
},
|
||||
{
|
||||
"about": "The person's own configuration opens it.",
|
||||
"defaults": true,
|
||||
"user": {
|
||||
"settings": "allow"
|
||||
},
|
||||
"project": {
|
||||
"sett*": "deny"
|
||||
},
|
||||
"request": {
|
||||
"permission": "settings",
|
||||
"pattern": "set mode auto"
|
||||
},
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "The defaults' own allows for reading settings stand.",
|
||||
"defaults": true,
|
||||
"project": {
|
||||
"sett*": "deny"
|
||||
},
|
||||
"request": {
|
||||
"permission": "settings",
|
||||
"pattern": "get mode"
|
||||
},
|
||||
"expect": "allow"
|
||||
},
|
||||
{
|
||||
"about": "Always on a file outside the project makes the outside path's rule too, never saved to the project; the same call is then allowed.",
|
||||
"defaults": true,
|
||||
"call": {
|
||||
"permission": "read",
|
||||
"class": "read",
|
||||
"path": "/srv/notes/todo.txt",
|
||||
"mode": "manual"
|
||||
},
|
||||
"answer": "always",
|
||||
"expect": {
|
||||
"first": "ask",
|
||||
"made": [
|
||||
{
|
||||
"permission": "read",
|
||||
"pattern": "/srv/notes/todo.txt",
|
||||
"save": true
|
||||
},
|
||||
{
|
||||
"permission": "external_directory",
|
||||
"pattern": "/srv/notes/todo.txt",
|
||||
"save": false
|
||||
}
|
||||
],
|
||||
"then": "allow"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "Inside the project only the call's own rule.",
|
||||
"defaults": true,
|
||||
"call": {
|
||||
"permission": "read",
|
||||
"class": "read",
|
||||
"path": "/project/.env",
|
||||
"mode": "manual"
|
||||
},
|
||||
"answer": "always",
|
||||
"expect": {
|
||||
"first": "ask",
|
||||
"made": [
|
||||
{
|
||||
"permission": "read",
|
||||
"pattern": ".env",
|
||||
"save": true
|
||||
}
|
||||
],
|
||||
"then": "allow"
|
||||
}
|
||||
},
|
||||
{
|
||||
"about": "A written deny of the outside path still holds: nothing is asked, nothing made.",
|
||||
"defaults": true,
|
||||
"user": {
|
||||
"external_directory": {
|
||||
"/srv/*": "deny"
|
||||
}
|
||||
},
|
||||
"call": {
|
||||
"permission": "read",
|
||||
"class": "read",
|
||||
"path": "/srv/notes/todo.txt",
|
||||
"mode": "manual"
|
||||
},
|
||||
"answer": "always",
|
||||
"expect": {
|
||||
"first": "deny",
|
||||
"made": [],
|
||||
"then": "deny"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+615
-110
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@
|
||||
"android": "LLeMbas for Android",
|
||||
"nvim": "LLeMbas for Neovim",
|
||||
"vscode": "LLeMbas for VS Code",
|
||||
"term": "LLeMbas TERM",
|
||||
"tty": "LLeMbas TTY",
|
||||
"server": "LLeMbas"
|
||||
},
|
||||
@@ -69,6 +70,7 @@
|
||||
"cli": "Run lembas login <address>.",
|
||||
"nvim": "Run lembas login <address> in a terminal.",
|
||||
"vscode": "Run lembas login <address> in a terminal.",
|
||||
"term": "Run lembas login <address>.",
|
||||
"tty": "Run lembas login <address>."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +81,9 @@ goes only to the server whose address a person typed.
|
||||
## 3. Identify
|
||||
|
||||
Every product names itself the same way, `llembas-<product>/<version>`, with `<product>` one of
|
||||
`connection.json` `products`: `cli`, `desktop`, `android`, `nvim`, `vscode`, `tty`, `server`.
|
||||
`connection.json` `products`: `cli`, `desktop`, `android`, `nvim`, `vscode`, `term`, `server` —
|
||||
and `tty`, what the terminal named itself before it was renamed LLeMbas TERM (its releases
|
||||
1.0.0-beta.1 to 5), still known so that such a terminal is told what to update by its own name.
|
||||
|
||||
- **HTTP**: `User-Agent: llembas-<product>/<version>` on every request to a LLeMbas server, the
|
||||
link's upgrade request included.
|
||||
@@ -123,7 +125,7 @@ stdio wording, with both versions.
|
||||
|
||||
**`min_clients`.** Discovery may carry `"min_clients": { "<product>": "<version>" }`, the lowest
|
||||
version of each product the server still serves — products `cli`, `desktop`, `android`, `nvim`,
|
||||
`vscode`, `tty`. Absent, or without the product: no minimum. A client **below its minimum** says
|
||||
`vscode`, `term` (and `tty`, the terminal before its rename). Absent, or without the product: no minimum. A client **below its minimum** says
|
||||
`client_too_old` in the `minimum` wording — both versions, and how to update — **at discovery,
|
||||
and does not go on.** Versions are compared as numbers and know a pre-release
|
||||
(`2.0.0-beta.10` is newer than `2.0.0-beta.9`, and `2.0.0` newer than `2.0.0-beta.99`); a value
|
||||
|
||||
@@ -149,6 +149,28 @@ device.
|
||||
A device's own errors (a file too large, a binary file, a protected path) are the CLI's and stay as
|
||||
they are; the ones above it says the same way.
|
||||
|
||||
## A search does not read what `read` would ask about
|
||||
|
||||
Spec 3.15.0. `grep` over a directory reads every file under it, and its permission is judged for
|
||||
the directory. **No line of a file comes back from a search unless `read` of that file would run
|
||||
without asking, by the rules and the mode as they are at that moment** — a file whose `read` rule
|
||||
is `ask` or `deny` (`.env`, by the defaults), also when it is reached through a symbolic link, in
|
||||
manual, edit and plan mode alike; in auto mode only a `deny` leaves a file out. The files left out
|
||||
that had a match are counted and named after the matches, so that the model can `read` one — which
|
||||
asks the person:
|
||||
|
||||
```
|
||||
(2 files with matches were left out: reading them needs the person's approval — use read on one to ask: {path}, {path})
|
||||
```
|
||||
|
||||
At most five are named, then `…`. A search *of the file itself* (`path` names it) was judged as a
|
||||
read of it and is not filtered again. Outside the project the person answered for the directory.
|
||||
|
||||
**Names are not content.** `glob` and `list` return the name of such a file as of any other: that
|
||||
`.env` exists is not what the rule protects, and the model needs the name to ask for it. `show`
|
||||
puts a file in front of the person, not the model, and follows its own permission. What the person
|
||||
attaches themself (`@file`) is their own act.
|
||||
|
||||
## A listing
|
||||
|
||||
`list` and a directory given to `read`: one entry per line, directories (and mounts) with a trailing
|
||||
|
||||
+106
-26
@@ -1038,7 +1038,7 @@
|
||||
}
|
||||
},
|
||||
"files": {
|
||||
"about": "Spec 3.11.0 (acp.md, *Device files* and `_lembas/show`): the most one answer or one part carries, decoded; entries a listing names; uploads open on a link, the most one may carry in all, and how long one waits for its next part; the folders whose names a device keeps listed for a search; content matches a search answers. `show`: the most a text file and a file that is not text may be to be shown, and how long the client has to fetch one. conformance/device_files.json, show.json. `runs_code` (acp.md, *Files that run code*): what `_lembas/fs/*` reads, and writes, moves, copies onto, makes or deletes only on a device whose `remote.files_that_run_code` is on (off by default) — `segments`: a path with a directory of that name anywhere in it; `project`: those names under a project's `.agent` directory, and that directory itself; `home`: those paths under the home directory of the device's user. A path that is one of them, is under one, or (for `project` and `home`) holds one, is refused with the reason `runs_code` while the setting is off.",
|
||||
"about": "Spec 3.11.0 (acp.md, *Device files* and `_lembas/show`): the most one answer or one part carries, decoded; entries a listing names; uploads open on a link, the most one may carry in all, and how long one waits for its next part; the folders whose names a device keeps listed for a search; content matches a search answers. `show`: the most a text file and a file that is not text may be to be shown, and how long the client has to fetch one. conformance/device_files.json, show.json. `runs_code` (acp.md, *Files that run code*): what `_lembas/fs/*` reads, and writes, moves, copies onto, makes or deletes only on a device whose `remote.files_that_run_code` is on (off by default) — `segments`: a path with a directory of that name anywhere in it; `project`: those names under a project's agent directory — a directory named one of `project_dirs` (`.agent`, or `.lembas` where `.agent` is somebody else's; spec 3.15.0) — and that directory itself; `home`: those paths under the home directory of the device's user. A path that is one of them, is under one, or (for `project` and `home`) holds one, is refused with the reason `runs_code` while the setting is off.",
|
||||
"chunk_max_bytes": 1048576,
|
||||
"list_max": 2000,
|
||||
"uploads_max": 4,
|
||||
@@ -1055,7 +1055,10 @@
|
||||
"segments": [
|
||||
".git"
|
||||
],
|
||||
"project_dir": ".agent",
|
||||
"project_dirs": [
|
||||
".agent",
|
||||
".lembas"
|
||||
],
|
||||
"project": [
|
||||
"config.yaml",
|
||||
"agents",
|
||||
@@ -1090,19 +1093,25 @@
|
||||
}
|
||||
},
|
||||
"terminal": {
|
||||
"about": "Spec 3.12.0 (acp.md, *A terminal as the client*; context.md §12): a LLeMbas terminal as the client of the CLI. `env`: the variables the terminal sets in every pane, and the ones that say a multiplexer sits in between. `contract` and `features`: what `lembas --version --json` says. `state`: the user vars the TUI publishes, the most one value holds (UTF-8 bytes), how long changes are gathered, and the state each progress phase is published as. `context`: the context file — its version, the most it and each part may be — and the texts of the `<terminal>` block, of the transcript's chip and of each refusal. `tools`: terminal_run and terminal_read — the command's limits, how many lines a read gives, how long the terminal's program may take, and the texts. `complete`: `lembas complete --shell` — the shells, the timeout, the most of the line and of the history that is sent, the lines of a history left out, and the most a suggestion is. Spec 3.13.0, contract 2 (acp.md, *The terminal's display*): `env.status_dir`: the variable that names where a pane's status record is. `surface`: the display — its command, the window id, the input it takes, the keys and command lines, the two modes and the texts. `profile`: the tools the display's session is offered, and no other. `status`: a pane's status record — its file, its keys and limits, the user var a remote shell publishes it as. `run`: how terminal_run waits for the command it typed — how long, how often it looks, what tells that a program waits for the person — and its answers. `increment`: what of a context the model has not seen yet. `models`: the terminal's two model settings. conformance/terminal.json. Spec 3.14.0, contract 3 (acp.md, *A command placed at the prompt*, *The terminal's settings*): `place`: in the display's manual mode a command is typed at the person's prompt without Enter — how long the call waits for them, how the prompt is told to be free (the input mark, the characters a prompt ends in), and the texts of each outcome. `settings`: the terminal's settings store — its file, version, keys with their kinds and defaults, limits, the lock, and the texts of its commands. `status.keys` gains `ran`. `complete`: the gate (`texts.off`), `--debug`, and the timeouts a terminal is told to ask with.",
|
||||
"about": "Spec 3.12.0 (acp.md, *A terminal as the client*; context.md §12): a LLeMbas terminal as the client of the CLI. `env`: the variables the terminal sets in every pane, and the ones that say a multiplexer sits in between. `contract` and `features`: what `lembas --version --json` says. `state`: the user vars the TUI publishes, the most one value holds (UTF-8 bytes), how long changes are gathered, and the state each progress phase is published as. `context`: the context file — its version, the most it and each part may be — and the texts of the `<terminal>` block, of the transcript's chip and of each refusal. `tools`: terminal_run and terminal_read — the command's limits, how many lines a read gives, how long the terminal's program may take, and the texts. `complete`: `lembas complete --shell` — the shells, the timeout, the most of the line and of the history that is sent, the lines of a history left out, and the most a suggestion is. Spec 3.13.0, contract 2 (acp.md, *The terminal's display*): `env.status_dir`: the variable that names where a pane's status record is. `surface`: the display — its command, the window id, the input it takes, the keys and command lines, the two modes and the texts. `profile`: the tools the display's session is offered, and no other. `status`: a pane's status record — its file, its keys and limits, the user var a remote shell publishes it as. `run`: how terminal_run waits for the command it typed — how long, how often it looks, what tells that a program waits for the person — and its answers. `increment`: what of a context the model has not seen yet. `models`: the terminal's two model settings. conformance/terminal.json. Spec 3.14.0, contract 3 (acp.md, *A command placed at the prompt*, *The terminal's settings*): `place`: in the display's manual mode a command is typed at the person's prompt without Enter — how long the call waits for them, how the prompt is told to be free (the input mark, the characters a prompt ends in), and the texts of each outcome. `settings`: the terminal's settings store — its file, version, keys with their kinds and defaults, limits, the lock, and the texts of its commands. `status.keys` gains `ran`. `complete`: the gate (`texts.off`), `--debug`, and the timeouts a terminal is told to ask with. Spec 3.15.0, contract 4 (acp.md, *Recognising the terminal*, *The names before the rename*): the terminal is LLeMbas TERM. `env`, `status.magic`, `status.dir_name`, `status.uservar` and `place.input.magic` are THE names; `env.before`, `status.magic_before`, `status.dir_name_before`, `status.uservar_before` and `place.input.magic_before` are the ones a terminal released before the rename uses, also read — a whole family at a time, the new one first.",
|
||||
"env": {
|
||||
"version": "LLEMBAS_TTY",
|
||||
"pane": "LLEMBAS_TTY_PANE",
|
||||
"executable": "LLEMBAS_TTY_EXECUTABLE",
|
||||
"version": "LLEMBAS_TERM",
|
||||
"pane": "LLEMBAS_TERM_PANE",
|
||||
"executable": "LLEMBAS_TERM_EXECUTABLE",
|
||||
"multiplexers": [
|
||||
"TMUX",
|
||||
"STY",
|
||||
"ZELLIJ"
|
||||
],
|
||||
"status_dir": "LLEMBAS_TTY_STATUS_DIR"
|
||||
"status_dir": "LLEMBAS_TERM_STATUS_DIR",
|
||||
"before": {
|
||||
"version": "LLEMBAS_TTY",
|
||||
"pane": "LLEMBAS_TTY_PANE",
|
||||
"executable": "LLEMBAS_TTY_EXECUTABLE",
|
||||
"status_dir": "LLEMBAS_TTY_STATUS_DIR"
|
||||
}
|
||||
},
|
||||
"contract": 3,
|
||||
"contract": 4,
|
||||
"features": [
|
||||
"terminal_state",
|
||||
"terminal_context",
|
||||
@@ -1113,7 +1122,9 @@
|
||||
"terminal_context_2",
|
||||
"terminal_models",
|
||||
"terminal_settings",
|
||||
"terminal_placed"
|
||||
"terminal_placed",
|
||||
"terminal_names_2",
|
||||
"terminal_ask_id"
|
||||
],
|
||||
"state": {
|
||||
"vars": [
|
||||
@@ -1202,10 +1213,11 @@
|
||||
"seen_one": "(1 command you have already seen left out)",
|
||||
"yours": "[You ran this with terminal_run: its output is in that call's result.]",
|
||||
"chip_nothing": "terminal context: nothing new in the terminal since the last question",
|
||||
"chip_empty": "terminal context: nothing to add — the terminal sent no command and no screen",
|
||||
"chip_new": "terminal context: {{what}}{{pane}}, new since the last question"
|
||||
},
|
||||
"refusals": {
|
||||
"not_terminal": "terminal context is for a LLeMbas terminal: LLEMBAS_TTY is not set here",
|
||||
"not_terminal": "terminal context is for a LLeMbas terminal: LLEMBAS_TERM is not set here",
|
||||
"no_path": "terminal context: name the file the terminal wrote",
|
||||
"missing": "terminal context: there is no file {{path}}",
|
||||
"outside": "terminal context: {{path}} is not in a runtime, temporary, state or data directory of yours — not read, and left where it is",
|
||||
@@ -1213,12 +1225,12 @@
|
||||
"not_file": "terminal context: {{path}} is not a regular file — not read, and left where it is",
|
||||
"not_yours": "terminal context: {{path}} belongs to somebody else — not read, and left where it is",
|
||||
"writable": "terminal context: others may write to {{path}} — not read, and left where it is",
|
||||
"too_large": "terminal context: the file is larger than {{max}} KiB — not used",
|
||||
"not_json": "terminal context: the file is not JSON — not used",
|
||||
"not_object": "terminal context: the file does not hold a context — not used",
|
||||
"version": "terminal context: the file is version {{version}} of the format, and this LLeMbas CLI reads versions {{known}} — update the older of the terminal and the CLI",
|
||||
"no_version": "terminal context: the file names no version of the format (this LLeMbas CLI reads versions {{known}}) — not used",
|
||||
"empty": "terminal context: the file holds no command and no screen — nothing to attach"
|
||||
"too_large": "terminal context: the file is larger than {{max}} KiB — not used, and left where it is",
|
||||
"not_json": "terminal context: the file is not JSON — not used, and left where it is",
|
||||
"not_object": "terminal context: the file does not hold a context — not used, and left where it is",
|
||||
"version": "terminal context: the file is version {{version}} of the format, and this LLeMbas CLI reads versions {{known}} — not used, and left where it is; update the older of the terminal and the CLI",
|
||||
"no_version": "terminal context: the file names no version of the format (this LLeMbas CLI reads versions {{known}}) — not used, and left where it is",
|
||||
"own": "terminal context: {{path}} is one of LLeMbas CLI's own files — not read, and left where it is"
|
||||
},
|
||||
"versions": [
|
||||
1,
|
||||
@@ -1240,7 +1252,7 @@
|
||||
"control": "Not typed: the command must be one line of plain text — no line break, tab or other control character. Join commands with && or ;.",
|
||||
"empty": "Not typed: the command is empty.",
|
||||
"too_long": "Not typed: the command is longer than {{max}} characters.",
|
||||
"no_program": "The terminal's command-line program is not at {{path}} (LLEMBAS_TTY_EXECUTABLE): nothing was done.",
|
||||
"no_program": "The terminal's command-line program is not at {{path}} ({{variable}}): nothing was done.",
|
||||
"failed": "The terminal refused ({{what}}): {{error}}",
|
||||
"timeout": "The terminal did not answer in {{seconds}} seconds: it is not known whether anything was typed. Read the pane with terminal_read before trying again.",
|
||||
"read_head": "<terminal-output pane=\"{{pane}}\" lines=\"{{lines}}\">",
|
||||
@@ -1251,6 +1263,63 @@
|
||||
},
|
||||
"read_wait_max_seconds": 120
|
||||
},
|
||||
"secrets": {
|
||||
"about": "Spec 3.15.0 (acp.md, *A shell line completed* and *Terminal context*): what makes a shell line look as if it holds a secret. One table for every reader of shell lines — `lembas complete --shell` for the typed line (no request when it matches) and for `--history` (the line is left out), a terminal context's command blocks (the command becomes `placeholder`, its output is left out), and a terminal that wants to decide the same before it asks. A line holds a secret when any of `patterns` matches it (JavaScript regular expressions, `i` where `ignore_case`; an entry with `only: \"history\"` is read for history lines alone — it is too broad to stop a line being typed), or when one of its words is a `token`: at least `min_length` characters of `chars`, with a digit, a lower-case and an upper-case letter, and at least `min_bits_per_char` bits of Shannon entropy per character. Conservative by design: conformance/terminal.json `kind: secret` holds ordinary commands that must not match.",
|
||||
"patterns": [
|
||||
{
|
||||
"name": "assignment",
|
||||
"ignore_case": true,
|
||||
"pattern": "(?:^|[\\s;&|(])(?:export\\s+|declare\\s+-\\w+\\s+|local\\s+|readonly\\s+|typeset\\s+(?:-\\w+\\s+)?)?(?:[a-z0-9]*_)*(?:[a-z0-9]*(?:passw(?:or)?d|pwd)|(?:api)?keys?|tokens?|secrets?|credentials?|auth)(?:_[a-z0-9]+)*=[^\\s;&|]"
|
||||
},
|
||||
{
|
||||
"name": "fish_or_csh_set",
|
||||
"ignore_case": true,
|
||||
"pattern": "(?:^|[\\s;&|(])(?:set\\s+(?:-[a-z]+\\s+)*|setenv\\s+)(?:[a-z0-9]*_)*(?:[a-z0-9]*(?:passw(?:or)?d|pwd)|(?:api)?keys?|tokens?|secrets?|credentials?|auth)(?:_[a-z0-9]+)*\\s+[^\\s;&|]"
|
||||
},
|
||||
{
|
||||
"name": "mysql_password",
|
||||
"ignore_case": false,
|
||||
"pattern": "(?:^|[\\s;&|(/])(?:mysql|mariadb|mysqldump|mysqladmin|mysqlimport|mariadb-dump|mariadb-admin)\\b[^;&|]*\\s-p[^\\s]"
|
||||
},
|
||||
{
|
||||
"name": "secret_option",
|
||||
"ignore_case": true,
|
||||
"pattern": "(?:^|\\s)--(?:password|passwd|pass|token|api[-_]?key|secret|client[-_]secret|auth[-_]token|access[-_]token)(?:=|\\s+)[^\\s-]"
|
||||
},
|
||||
{
|
||||
"name": "user_password",
|
||||
"ignore_case": false,
|
||||
"pattern": "(?:^|\\s)(?:-u|--user)(?:\\s+|=)?['\"]?[^\\s:'\"]+:[^\\s'\"]"
|
||||
},
|
||||
{
|
||||
"name": "authorization",
|
||||
"ignore_case": true,
|
||||
"pattern": "\\b(?:authorization|proxy-authorization|x-api-key|private-token|x-auth-token)\\s*:|\\bbearer\\s+[a-z0-9._~+/=-]{8,}|\\bbasic\\s+[a-z0-9+/=]{8,}"
|
||||
},
|
||||
{
|
||||
"name": "url_credentials",
|
||||
"ignore_case": true,
|
||||
"pattern": "\\b[a-z][a-z0-9+.-]*://[^\\s/@:]+:[^\\s/@]+@"
|
||||
},
|
||||
{
|
||||
"name": "key_prefix",
|
||||
"ignore_case": false,
|
||||
"pattern": "\\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9]{8,}|github_pat_[A-Za-z0-9_]{8,}|glpat-[A-Za-z0-9_-]{8,}|xox[baprs]-[A-Za-z0-9-]{4,}|AKIA[0-9A-Z]{12,}|lmb_[A-Za-z0-9]{4,})|-----BEGIN [A-Z ]*PRIVATE KEY"
|
||||
},
|
||||
{
|
||||
"name": "secret_word",
|
||||
"ignore_case": true,
|
||||
"only": "history",
|
||||
"pattern": "(?:pass(?:word|wd|phrase)?|secret|token|api[_-]?key|authorization|bearer|credential)s?\\b"
|
||||
}
|
||||
],
|
||||
"token": {
|
||||
"min_length": 32,
|
||||
"chars": "A-Za-z0-9+_=-",
|
||||
"min_bits_per_char": 4.0
|
||||
},
|
||||
"placeholder": "[a command that looks as if it holds a secret — left out]"
|
||||
},
|
||||
"complete": {
|
||||
"shells": [
|
||||
"bash",
|
||||
@@ -1265,7 +1334,6 @@
|
||||
"history_lines": 20,
|
||||
"history_line_max_chars": 500,
|
||||
"history_read_bytes": 65536,
|
||||
"history_secret": "(?:pass(?:word|wd|phrase)?|secret|token|api[_-]?key|authorization|bearer|credential)s?\\b|\\b(?:AKIA[0-9A-Z]{8}|gh[pousr]_[A-Za-z0-9]{8}|sk-[A-Za-z0-9_-]{8}|lmb_[A-Za-z0-9]{4}|xox[abprs]-)",
|
||||
"max_tokens": 64,
|
||||
"suggestion_max_chars": 500,
|
||||
"texts": {
|
||||
@@ -1278,7 +1346,8 @@
|
||||
"usage": "usage: … | lembas complete --shell <bash|zsh|fish> [--cwd <dir>] [--history <file>] [--timeout-ms <n>] [--model <id>] [--debug] (the line so far on stdin; the rest of it on stdout)",
|
||||
"off": "lembas complete: autocomplete is turned off in the terminal's settings ({{key}}: false, from {{from}})",
|
||||
"debug": "lembas complete: debug: {{what}}",
|
||||
"no_cwd": "# Working directory: not known"
|
||||
"no_cwd": "# Working directory: not known",
|
||||
"secret": "lembas complete: the line looks as if it holds a secret — nothing was sent"
|
||||
},
|
||||
"timeout_ms_recommended": 8000,
|
||||
"timeout_ms_warm": 20000,
|
||||
@@ -1313,6 +1382,11 @@
|
||||
"stop": "\u0003"
|
||||
},
|
||||
"option_keys": "123456789",
|
||||
"ask_id": {
|
||||
"about": "Spec 3.15.0 (acp.md, *The display*, `lembas_ask`): each open approval and each question of a question card has an id — a whole number of 1 to `digits_max` digits, new for each — written after the kind with `#`: `approval#12 yn terminal_run: make test`, `question#13 1-3n Which one?`. `/approve`, `/always` and `/deny` take it as their first word (`/approve 12`); `/answer` takes the option alone, as before (`/answer 2`), or the id first (`/answer 13 2`). An answer naming another id than the one asked now decides nothing and is refused in words (`texts.wrong_id`); without an id they answer what is asked now, as before. A value cut to fit `state.max_bytes` ends in `ellipsis`, so the terminal can say the rest is in the display.",
|
||||
"digits_max": 9,
|
||||
"ellipsis": "…"
|
||||
},
|
||||
"exit": {
|
||||
"closed": 0,
|
||||
"error": 1,
|
||||
@@ -1321,7 +1395,7 @@
|
||||
},
|
||||
"seen_max": 500,
|
||||
"texts": {
|
||||
"not_terminal": "lembas terminal is the display of a LLeMbas terminal: LLEMBAS_TTY is not set here",
|
||||
"not_terminal": "lembas terminal is the display of a LLeMbas terminal: LLEMBAS_TERM is not set here",
|
||||
"no_tty": "lembas terminal draws in a terminal pane: standard input and output must be one",
|
||||
"no_window": "lembas terminal: name the terminal window this display belongs to (--window <id>: 1 to 64 letters, digits, dots, dashes or underscores)",
|
||||
"taken": "lembas terminal: a display for window {{window}} is already running (process {{pid}}) — this one is not started",
|
||||
@@ -1348,7 +1422,8 @@
|
||||
"hint_question_free": "send your answer · {{deny}} skip",
|
||||
"empty": "Ask from your terminal's ask line. What the agent runs appears in your own pane.",
|
||||
"model_session": "model: {{model}} — for this conversation only. The terminal's settings keep what a display starts with.",
|
||||
"mode_session": "mode: {{mode}} — for this display only. The terminal's settings keep what a display starts with."
|
||||
"mode_session": "mode: {{mode}} — for this display only. The terminal's settings keep what a display starts with.",
|
||||
"wrong_id": "{{said}} is not what is asked now{{now}} — nothing decided. Answer what the display shows."
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
@@ -1379,8 +1454,10 @@
|
||||
},
|
||||
"status": {
|
||||
"version": 1,
|
||||
"magic": "llembas-tty-status",
|
||||
"dir_name": "llembas-tty",
|
||||
"magic": "llembas-term-status",
|
||||
"magic_before": "llembas-tty-status",
|
||||
"dir_name": "llembas-term",
|
||||
"dir_name_before": "llembas-tty",
|
||||
"file": "pane-{{pane}}.status",
|
||||
"max_bytes": 4096,
|
||||
"keys": [
|
||||
@@ -1403,7 +1480,8 @@
|
||||
"id_pattern": "^[A-Za-z0-9._:-]{1,64}$",
|
||||
"value_max_chars": 4096,
|
||||
"host_max_chars": 255,
|
||||
"uservar": "llembas_tty_status",
|
||||
"uservar": "llembas_term_status",
|
||||
"uservar_before": "llembas_tty_status",
|
||||
"via_uservar": "uservar"
|
||||
},
|
||||
"run": {
|
||||
@@ -1446,7 +1524,8 @@
|
||||
"fact_ended": "ended",
|
||||
"fact_ok": "exit 0",
|
||||
"fact_denied": "denied",
|
||||
"fact_failed": "failed"
|
||||
"fact_failed": "failed",
|
||||
"unverified": "(Reported by the remote shell; not verified.)"
|
||||
}
|
||||
},
|
||||
"models": {
|
||||
@@ -1474,7 +1553,8 @@
|
||||
"actual_max_chars": 2000,
|
||||
"prompt_end": "[$#%>❯➜»λ→▶]$",
|
||||
"input": {
|
||||
"magic": "llembas-tty-input",
|
||||
"magic": "llembas-term-input",
|
||||
"magic_before": "llembas-tty-input",
|
||||
"version": 1,
|
||||
"file": "pane-{{pane}}.input",
|
||||
"max_bytes": 512
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
{
|
||||
"about": "The rules every session starts from, before the user's own. Keys are permission keys (a tool's access), values an action or a map of pattern → action; for a pattern the last matching rule wins, across patterns the strictest. Permission keys are tool names, except `plan`, which covers plan_write and plan_update together (the former `todo` key is read as `plan`).",
|
||||
"user_only": [
|
||||
"settings"
|
||||
],
|
||||
"user_only_about": "Spec 3.15.0 (rules.md §2): permissions whose rules are read from the `default` and `user` layers only. A rule of the `project` or `made` layer is not read for a call of one of them, whatever its key — `settings`, `sett*` or `*` — so a project cannot open the tool that changes the person's settings by a key that merely matches it.",
|
||||
"rules": {
|
||||
"*": "ask",
|
||||
"read": {
|
||||
|
||||
@@ -60,8 +60,36 @@
|
||||
},
|
||||
{
|
||||
"id": "force-push-main",
|
||||
"description": "force-push to main/master",
|
||||
"pattern": "(?:^|[\\n\\`;&|(]|\\$\\()\\s*(?:sudo\\s+(?:-\\S+\\s+)*)?(?:env\\s+(?:\\w+=\\S*\\s+)*)?(?:(?:exec|nohup|setsid|time|command)\\s+)*\\s*git\\s+push\\b(?=[^\\n;&|]*(?:\\s--force\\b|\\s-[a-zA-Z]*f[a-zA-Z]*\\b|\\s--force-with-lease\\b|\\s\\+))[^\\n;&|]*\\b(?:main|master)\\b"
|
||||
"description": "force-push to, or deletion of, main/master",
|
||||
"check": "git_push",
|
||||
"branches": [
|
||||
"main",
|
||||
"master"
|
||||
],
|
||||
"about": "Not a pattern (spec 3.15.0; a pattern refused `feature/main-menu` and missed `:main`): each simple command in its plain spelling that is `git push` is read as git reads it. Options first: `value_options` take the next word; the first other word is the remote, the rest are refspecs. A refspec's destination is what follows its `:`, or the whole of it, without a leading `+` and without `refs/heads/`. The push is forced when an option is one of `force_options` (a long one also with `=value`; a short one anywhere in a cluster: `-uf`) or a refspec begins with `+`, and for those refspecs only when the `+` is all that forces. It deletes when an option is one of `delete_options` (every refspec is then a deletion) or a refspec's source is empty (`:main`). Refused: a deletion whose destination is one of `branches`; a forced push with a refspec whose destination is one of `branches`; a forced push with one of `all_options` (it takes every branch); and a forced push that names no branch (no refspec, or only `HEAD`) when the implementation knows the current branch and it is one of `branches` — where it cannot know, the floor does not speak and the rules and the mode decide.",
|
||||
"value_options": [
|
||||
"-o",
|
||||
"--push-option",
|
||||
"--receive-pack",
|
||||
"--exec",
|
||||
"--repo"
|
||||
],
|
||||
"force_options": [
|
||||
"-f",
|
||||
"--force",
|
||||
"--force-with-lease",
|
||||
"--force-if-includes",
|
||||
"--mirror"
|
||||
],
|
||||
"delete_options": [
|
||||
"-d",
|
||||
"--delete"
|
||||
],
|
||||
"all_options": [
|
||||
"--all",
|
||||
"--branches",
|
||||
"--mirror"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "find-delete-system",
|
||||
@@ -84,6 +112,75 @@
|
||||
"scope": "cli"
|
||||
}
|
||||
],
|
||||
"commands": {
|
||||
"about": "How a command line is read for the files it touches (rules.md §5, spec 3.15.0). `max_bytes`: a line longer than this (UTF-8) is not analysed at all — it is asked about in every mode, auto included, and refused where nobody can answer. `known_variables`: the only variables a reader expands ($NAME and ${NAME}); any other expansion leaves the word unresolved. `pattern_first`: programs whose first operand is a pattern, not a file, unless an option gives the pattern (`pattern_options`). `readers`: programs that only read the files they name — a command of any other program that names a protected path is taken to write it, and is refused. `brace_max`: the most words one brace expansion may give before the word counts as unresolved; `glob_max` the same for a glob; `cd`: the programs that change the directory later commands of the line work in.",
|
||||
"max_bytes": 32768,
|
||||
"known_variables": [
|
||||
"HOME",
|
||||
"PWD"
|
||||
],
|
||||
"brace_max": 64,
|
||||
"glob_max": 500,
|
||||
"cd": [
|
||||
"cd",
|
||||
"pushd"
|
||||
],
|
||||
"pattern_first": [
|
||||
"grep",
|
||||
"egrep",
|
||||
"fgrep",
|
||||
"rg",
|
||||
"ag",
|
||||
"ack"
|
||||
],
|
||||
"pattern_options": [
|
||||
"-e",
|
||||
"--regexp",
|
||||
"-f",
|
||||
"--file",
|
||||
"--files"
|
||||
],
|
||||
"readers": [
|
||||
"cat",
|
||||
"head",
|
||||
"tail",
|
||||
"wc",
|
||||
"grep",
|
||||
"egrep",
|
||||
"fgrep",
|
||||
"rg",
|
||||
"ag",
|
||||
"ack",
|
||||
"ls",
|
||||
"file",
|
||||
"tree",
|
||||
"which",
|
||||
"stat",
|
||||
"du",
|
||||
"less",
|
||||
"more",
|
||||
"diff",
|
||||
"cmp",
|
||||
"sha256sum",
|
||||
"sha1sum",
|
||||
"md5sum",
|
||||
"od",
|
||||
"xxd",
|
||||
"strings",
|
||||
"basename",
|
||||
"dirname",
|
||||
"realpath",
|
||||
"readlink",
|
||||
"test",
|
||||
"[",
|
||||
"echo",
|
||||
"printf",
|
||||
"cd",
|
||||
"pushd",
|
||||
"ssh",
|
||||
"ssh-add"
|
||||
]
|
||||
},
|
||||
"plain": {
|
||||
"about": "How a simple command is spelled plainly before the rules are checked again: leading keywords and VAR= assignments dropped; wrapper programs and their options taken off (an option listed for a wrapper takes a value); `timeout` also drops its duration; a shell's -c argument read as its own line; git's global options dropped; quotes, escapes and program paths removed; paths normalised (~ for the home directory).",
|
||||
"wrappers": {
|
||||
|
||||
+126
-1
@@ -21,6 +21,11 @@ anything), and `allow`, `ask` or `deny`. Every rule has a **layer**, by where it
|
||||
|
||||
Within a layer, rules are read in the order they are written.
|
||||
|
||||
**User-only permissions** (spec 3.15.0; `defaults.json` `user_only`: `settings`). For a call of
|
||||
one of these, only the `default` and `user` layers are read. A `project` or `made` rule is not
|
||||
read for it by any key — its name, a pattern that matches its name (`sett*`), or `*`. A loader
|
||||
that drops such a key from a project's file says so; the rule holds without the loader.
|
||||
|
||||
## 2. The rule that decides
|
||||
|
||||
For a call's permission and what it asks for, among the rules that match both:
|
||||
@@ -79,6 +84,12 @@ When a person makes a rule — an "always" answer, or one set in a menu:
|
||||
trusted project's configuration) — saved as a `project` rule. Because §2 treats `made` and
|
||||
`project` alike, the session it was made in and the next start from the saved file decide
|
||||
every call the same way.
|
||||
- **An "always" answer makes what the card asked about** (spec 3.15.0). A call asked about
|
||||
because it reaches outside the project (`external_directory`) is remembered with an
|
||||
`external_directory` rule for each such path besides the rule for the call's own permission —
|
||||
the latter alone left the next identical call asked. That path rule is made for the session
|
||||
and never saved to a project's file: a machine's paths are not the project's. Where the card
|
||||
offers no "always", none is made.
|
||||
- The person is told what it did: where it holds, whether it was saved, and **which stricter
|
||||
rules still apply** — every rule of the `default`, `user` or `project` layer that is narrower
|
||||
than the new rule and stricter than it. (A rule set aside for every call it could decide is
|
||||
@@ -121,4 +132,118 @@ in place of it: **a command is never typed at a password prompt**, and not into
|
||||
command runs unless the call says the pane is at a prompt (`kind: ready`) — both after the
|
||||
person allowed the call, so an allowed command can still be not typed, in words. A command to
|
||||
be placed has one check more: **only at an empty prompt** (`kind: prompt`) — nothing is ever
|
||||
added to what the person typed.
|
||||
added to what the person typed.
|
||||
|
||||
## 5. What a command touches (spec 3.15.0)
|
||||
|
||||
A command line is text; what runs is what the shell makes of it. A reader that judged a line by
|
||||
its spelling let `cat .en{v,}`, `cat ~name/.ssh/key`, `cat $DIR/token`, `wc --files0-from=.env`
|
||||
and `rg -f.env x` read what `cat .env` is asked about. So the reading is a rule, not a list
|
||||
(`hardline.json` `commands` holds its data; `conformance/permission.json`):
|
||||
|
||||
**The rule: a command is known to be safe only when every word of it is known.** Each word
|
||||
after the program's name resolves to *a definite path*, *a definite non-path*, or it is
|
||||
**unresolved** — and a line with an unresolved word is never "allowed by rules": where the
|
||||
rules would allow it, it is asked about (plan mode, which refuses what it cannot allow, refuses
|
||||
it; auto mode asks nothing and runs it). The reader fails closed: what it does not model is
|
||||
unresolved, never ignored.
|
||||
|
||||
**1. Words.** The line is split into simple commands (`conformance/split.json`), each into
|
||||
shell words with their quoting kept: a character is *unquoted*, *double-quoted* (a `$` or a
|
||||
backquote still expands) or *literal* (single-quoted, or after a backslash — inside double
|
||||
quotes a backslash makes literal only `$`, a backquote, `"` and `\`). A subshell's own
|
||||
parentheses are not part of a word. What a `$( … )` or backquote substitution runs, what a
|
||||
shell's `-c` carries and what `env -S` carries are lines too, read the same way (four deep at
|
||||
most; deeper is unresolved).
|
||||
|
||||
**2. Expansion, as far as it is modelled** — in the shell's order:
|
||||
|
||||
| In a word | Read as |
|
||||
|---|---|
|
||||
| an unquoted `{a,b}` (a comma at its own depth; nesting allowed) | each alternative, up to `brace_max` words — more is unresolved |
|
||||
| an unquoted `{x..y}` | unresolved |
|
||||
| any other brace (`HEAD@{1}`, quoted braces) | text |
|
||||
| a leading unquoted `~` alone or before `/` | the home directory |
|
||||
| a leading unquoted `~` before anything else (`~name`, `~+`) | unresolved |
|
||||
| `$NAME` / `${NAME}`, not literal, `NAME` one of `known_variables` | its value: `HOME` the home directory, `PWD` the directory the command runs in |
|
||||
| `$NAME` / `${NAME}` of any other name; `$(`, `${…}` of another shape, a backquote, `$?` `$$` `$!` `$@` `$*` `$#` `$-` `$0`–`$9`, not literal | unresolved |
|
||||
| a `$` followed by anything else (`"foo$"`) | text |
|
||||
| `*`, `?`, `[` — quoted or not | a glob over what exists, dotfiles included; over `glob_max` names is unresolved; no match is the word itself |
|
||||
|
||||
An implementation may expand a variable beyond `known_variables` only when it knows the value
|
||||
the shell will have for certain; the cases use none.
|
||||
|
||||
**3. Which words name a path.** Every word after the program's name is a candidate — a word
|
||||
that is not really a path resolves inside the working directory, harmlessly — with these
|
||||
readings:
|
||||
|
||||
- **A redirection** whose operator is unquoted: `<file` and `N<file` are read; `>file`,
|
||||
`>>file`, `N>file`, `&>file`, `>|file`, `<>file` are **written**, the file glued to the
|
||||
operator or the next word. `>&N`, `N>&M`, `>&-` name no file; the word after `<<`/`<<<` is
|
||||
data.
|
||||
- **An option** (a word beginning `-`; `-` and `--` alone name nothing): the text after its
|
||||
first `=` is a candidate (`--files0-from=PATH`), and for a short option every tail of it
|
||||
that begins after a run of letters and digits from its second character (`-fPATH`, `-rfPATH`:
|
||||
the tails `PATH`, `fPATH`…; in `-Lname:src/a.ts` nothing after the `:` begins a tail); a
|
||||
short option longer than 256 characters is unresolved. The option's own name is not a path.
|
||||
- **An operand with `=`** (`if=PATH`): the whole word and the text after the first `=`.
|
||||
- **A pattern-first program** (`pattern_first`): its first operand is the pattern, not a file —
|
||||
unless a `pattern_options` option, or any short option with `e` or `f` in it, gave the
|
||||
pattern. The pattern is still a word: an unresolved expansion in it is unresolved.
|
||||
- The devices `/dev/null`, `zero`, `stdin`, `stdout`, `stderr`, `tty`, `random`, `urandom` are
|
||||
no file.
|
||||
|
||||
**4. Where.** A relative path is taken in the directory the command runs in. After a `cd` (the
|
||||
programs in `cd`) to a resolved directory, later commands of the line are read there — when the
|
||||
line is a plain sequence (`;`, `&&`, new lines). When it has a subshell, a group, a pipe, `||`
|
||||
or a background job, the `cd` may not hold for what follows, and later paths are read in
|
||||
**both** directories. `cd` with no operand goes home; a `cd` whose target is unresolved (`cd -`)
|
||||
makes the line unresolved.
|
||||
|
||||
**5. What each path means.** Every path named, resolved through symbolic links:
|
||||
|
||||
- inside the project, is a **read** of it: the `read` rules apply (`*.env` asks);
|
||||
- outside the project, falls under `external_directory`;
|
||||
- **and a path the line may write that is a protected path is refused in every mode**, auto
|
||||
included (`modes.json` `floor`) — as the write tools are. A line *may write* a path when it
|
||||
is a redirection's target, or when it is named by a command whose program — after its
|
||||
wrappers (`hardline.json` `plain.wrappers`) — is not one of `readers`: programs that only
|
||||
read what they name. Reading a protected path is not refused by the floor; it is asked as
|
||||
everything outside the project is.
|
||||
|
||||
**6. Too long to read.** A line longer than `max_bytes` is not analysed: not by the floor, not
|
||||
by the rules. It is asked about **in every mode, auto included** (plan mode refuses it; with
|
||||
nobody to answer it is refused), with no "always". The floor's patterns and this reader are
|
||||
then never run on unbounded input.
|
||||
|
||||
**What this does not see**, so that nobody takes it for more: a program that reads files it was
|
||||
not given (`grep -r x .` reads every file under `.`; the search *tools* leave protected files
|
||||
out — `filesystem.md`), what a script does once it runs, and in auto mode an unresolved word (a
|
||||
variable holding a protected path is not known to be one).
|
||||
|
||||
## 6. A custom command's shell substitution (spec 3.15.0; the CLI's alone)
|
||||
|
||||
A custom command (a markdown file of the person's, or of a trusted project — an untrusted
|
||||
project's commands do not exist) may hold `` !`line` ``, replaced by the line's output before
|
||||
the prompt is sent. That line is the command file's code run with the person's rights, and the
|
||||
prompt that triggers it may come from anywhere a prompt comes from — the keyboard, `lembas run`,
|
||||
the link. So:
|
||||
|
||||
1. **It is judged as a `bash` call of that line, in the session's mode, by the session's rules**
|
||||
— the floor, the rules (§2), what the line touches (§5), the mode, and with them the device's
|
||||
remote limits, which clamp a remote session's mode (`acp.md`). **Only `allow` runs it.** A
|
||||
`deny` puts `[not run — {reason}]` in its place; an `ask` puts
|
||||
``[not run — `{line}` needs the person's approval here; run it with bash if its output is needed]``
|
||||
— nothing is asked while a prompt is being put together; the model may make the call itself,
|
||||
which is then asked about as any call is.
|
||||
2. **The arguments are never part of the line.** `$ARGUMENTS` and `$1`…`$9` are filled in the
|
||||
command's *text* (in one pass: a `$` inside the arguments is text). Inside a `` !`…` `` nothing
|
||||
is filled in: the line runs as written, with the arguments as the shell's positional
|
||||
parameters (`$1`…, `"$@"`) and `ARGUMENTS` in its environment — data the shell expands, not
|
||||
text it parses. By §5 a line with `$1` in it is unresolved, so outside auto mode it is not
|
||||
run.
|
||||
3. **The floor is checked twice**: on the line as written and on the line with the arguments
|
||||
filled in as text.
|
||||
4. It runs in the project root with the environment `bash` calls get, and is stopped after ten
|
||||
seconds.
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
# Files
|
||||
- You work in the user's file system, through the file tools. Relative paths start at {{start}}; absolute paths start at `/`.
|
||||
- What this session can reach, and how: {{view}}. Nothing else exists here. A path below one of these is reached by its full path; a directory above one that is not itself listed cannot be listed, read or written.
|
||||
- A listing ends a directory with `/`, marks a repository mounted from a forge `[mount]`, and an entry you can read but not change `[read-only]`.
|
||||
- Read-only means read but not changed. Stage means changes are kept in this session and, in a repository, not committed. Commit means that, in a repository, the changes may also be committed and pushed to the forge.
|
||||
- A listing ends a directory with `/`, marks a repository mounted from a Git server `[mount]`, and an entry you can read but not change `[read-only]`.
|
||||
- Read-only means read but not changed. Stage means changes are kept in this session and, in a repository, not committed. Commit means that, in a repository, the changes may also be committed and pushed to its Git server.
|
||||
- {{repositories}}
|
||||
- Deleting moves a file to the trash, from which the user can restore it. Still, delete only what you were asked to, or what you made yourself.
|
||||
- {{show}}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!-- Source: OpenCode session/prompt/anthropic.txt (MIT, © 2025 opencode) — professional
|
||||
objectivity and todo discipline; product references removed, tool names the CLI's. -->
|
||||
objectivity and plan discipline; product references removed, tool names the CLI's. -->
|
||||
# Professional objectivity
|
||||
Prioritise technical accuracy over agreeing with the user. Give direct, objective information without superlatives, praise or emotional validation, and disagree when the facts call for it — respectful correction is worth more than false agreement. When unsure, investigate before confirming what the user believes.
|
||||
|
||||
# Tracking the work
|
||||
For anything with three or more steps, use the todo tool from the start and keep it current: one item in_progress at a time, marked completed the moment it is done — never in a batch at the end. It is how the user sees where you are.
|
||||
For anything with three or more steps, write a plan with plan_write from the start and keep it current with plan_update: one task doing at a time, marked done the moment it is checked — never in a batch at the end. It is how the user sees where you are.
|
||||
@@ -27,7 +27,7 @@
|
||||
"type": "string"
|
||||
},
|
||||
"value": {
|
||||
"description": "set: the new value, as text — high, connection/model, 0.7, true, a list as ddg,searxng.",
|
||||
"description": "set: the new value, as text — high, a model's id, 0.7, true, a list as ddg,searxng.",
|
||||
"type": "string"
|
||||
},
|
||||
"scope": {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"cli": [],
|
||||
"llembas": []
|
||||
},
|
||||
"description": "The project's task board (.agent/tasks.md): work that outlives this session — as opposed to todo, which is your checklist for the task at hand.\n\n- list: show the board. add: a new item (to todo unless you say). move: an item to todo, doing or done. remove: drop an item.\n- Add what the user asks you to remember or what you find that should be done later; move items as you work on them. Refer to items by their number.",
|
||||
"description": "The project's task board (.agent/tasks.md): work that outlives this session — as opposed to your plan (plan_write), which is for the task at hand.\n\n- list: show the board. add: a new item (to todo unless you say). move: an item to todo, doing or done. remove: drop an item.\n- Add what the user asks you to remember or what you find that should be done later; move items as you work on them. Refer to items by their number.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "lembas-cli",
|
||||
"version": "2.0.0-beta.20",
|
||||
"version": "2.0.0-beta.21",
|
||||
"description": "LLeMbas CLI: a terminal coding agent and project manager for a LLeMbas server — OpenTUI, memory, skills, MCP, git-native.",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
|
||||
+16
-16
@@ -306,7 +306,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"order": {
|
||||
"description": "Providers to try, in order; the first that answers wins. Default: those configured (webui first), then ddg. webui: the LLeMbas instance's own search.",
|
||||
"description": "Providers to try, in order; the first that answers wins. Default: those configured (webui first), then ddg. webui: the LLeMbas server's own search.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
@@ -400,18 +400,18 @@
|
||||
"additionalProperties": false
|
||||
},
|
||||
"webui": {
|
||||
"description": "Search through a LLeMbas instance: its provider, its settings, its keys.",
|
||||
"description": "Search through the LLeMbas server: its provider, its settings, its keys.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"connection": {
|
||||
"description": "Which webui connection (default: the only one there is).",
|
||||
"description": "Which sign-in (default: the only one there is).",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"fetch": {
|
||||
"description": "How web_fetch reads a page: here, through Firecrawl's scrape, or through the LLeMbas instance.",
|
||||
"description": "How web_fetch reads a page: here, through Firecrawl's scrape, or through the LLeMbas server.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"local",
|
||||
@@ -430,7 +430,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"description": "openai: POST {base_url}/audio/transcriptions (OpenAI, whisper.cpp's server with its OpenAI path, faster-whisper servers). whispercpp: POST {base_url}/inference (whisper.cpp's own). webui: the LLeMbas instance's.",
|
||||
"description": "openai: POST {base_url}/audio/transcriptions (OpenAI, whisper.cpp's server with its OpenAI path, faster-whisper servers). whispercpp: POST {base_url}/inference (whisper.cpp's own). webui: the LLeMbas server's.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"openai",
|
||||
@@ -464,7 +464,7 @@
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"connection": {
|
||||
"description": "webui: which webui connection (default: the only one there is).",
|
||||
"description": "webui: which sign-in (default: the only one there is).",
|
||||
"type": "string"
|
||||
},
|
||||
"model": {
|
||||
@@ -482,7 +482,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"description": "openai: POST {base_url}/audio/transcriptions (OpenAI, whisper.cpp's server with its OpenAI path, faster-whisper servers). whispercpp: POST {base_url}/inference (whisper.cpp's own). webui: the LLeMbas instance's.",
|
||||
"description": "openai: POST {base_url}/audio/transcriptions (OpenAI, whisper.cpp's server with its OpenAI path, faster-whisper servers). whispercpp: POST {base_url}/inference (whisper.cpp's own). webui: the LLeMbas server's.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"openai",
|
||||
@@ -516,7 +516,7 @@
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"connection": {
|
||||
"description": "webui: which webui connection (default: the only one there is).",
|
||||
"description": "webui: which sign-in (default: the only one there is).",
|
||||
"type": "string"
|
||||
},
|
||||
"model": {
|
||||
@@ -539,7 +539,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"description": "openai: POST {base_url}/audio/speech (OpenAI, Kokoro-FastAPI). piper-http: POST {base_url} with {text} (piper's http_server). piper-cli: the piper program. webui: the LLeMbas instance's, in the account's voice.",
|
||||
"description": "openai: POST {base_url}/audio/speech (OpenAI, Kokoro-FastAPI). piper-http: POST {base_url} with {text} (piper's http_server). piper-cli: the piper program. webui: the LLeMbas server's, in the account's voice.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"openai",
|
||||
@@ -574,7 +574,7 @@
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"connection": {
|
||||
"description": "webui: which webui connection (default: the only one there is).",
|
||||
"description": "webui: which sign-in (default: the only one there is).",
|
||||
"type": "string"
|
||||
},
|
||||
"model": {
|
||||
@@ -600,7 +600,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"description": "openai: POST {base_url}/audio/speech (OpenAI, Kokoro-FastAPI). piper-http: POST {base_url} with {text} (piper's http_server). piper-cli: the piper program. webui: the LLeMbas instance's, in the account's voice.",
|
||||
"description": "openai: POST {base_url}/audio/speech (OpenAI, Kokoro-FastAPI). piper-http: POST {base_url} with {text} (piper's http_server). piper-cli: the piper program. webui: the LLeMbas server's, in the account's voice.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"openai",
|
||||
@@ -635,7 +635,7 @@
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"connection": {
|
||||
"description": "webui: which webui connection (default: the only one there is).",
|
||||
"description": "webui: which sign-in (default: the only one there is).",
|
||||
"type": "string"
|
||||
},
|
||||
"model": {
|
||||
@@ -1004,7 +1004,7 @@
|
||||
"description": "github or gitea (Forgejo too): their releases API. static: any web directory with files `stable` and `beta` naming a tag, and the assets under <tag>/."
|
||||
},
|
||||
"url": {
|
||||
"description": "gitea: the forge (https://git.example.org). github: the API (default https://api.github.com). static: the directory.",
|
||||
"description": "gitea: the address of the Gitea server (https://git.example.org). github: the API (default https://api.github.com). static: the directory.",
|
||||
"type": "string"
|
||||
},
|
||||
"repo": {
|
||||
@@ -1071,11 +1071,11 @@
|
||||
]
|
||||
},
|
||||
"remote": {
|
||||
"description": "Global config only. What a LLeMbas instance may ask of this machine over the link: the device decides, never the server.",
|
||||
"description": "Global config only. What the LLeMbas server may ask of this machine over the link: the device decides, never the server.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"description": "Accept work from a LLeMbas instance this machine is logged in to (lembas service). Default false.",
|
||||
"description": "Accept work from the LLeMbas server this machine is signed in to (lembas service). Default false.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"roots": {
|
||||
@@ -1110,7 +1110,7 @@
|
||||
"type": "boolean"
|
||||
},
|
||||
"scheduled": {
|
||||
"description": "Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas instance run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off.",
|
||||
"description": "Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas server run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"files_that_run_code": {
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "webui",
|
||||
"description": "A LLeMbas instance: its models, their settings, its voice and its web search."
|
||||
"description": "A LLeMbas server: its models, their settings, its voice and its web search."
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
|
||||
@@ -45,6 +45,9 @@ bun x tsc --noEmit # `bun x`: the release zip CI fetches has no bunx link
|
||||
step "tests"
|
||||
bun test --timeout 20000
|
||||
|
||||
step "the terminal's tests in the names from before its rename"
|
||||
scripts/test-terminal-names.sh
|
||||
|
||||
step "the compiled binary (smoke)"
|
||||
bun run smoke
|
||||
|
||||
|
||||
+5
-4
@@ -295,7 +295,7 @@ for (const [cols, rows] of [
|
||||
await Bun.write(join(cfgDir, "connections.yaml"), connections)
|
||||
await Bun.write(join(cfgDir, "config.yaml"), "model: fake/coder\nupdate: { auto: off }\n")
|
||||
// The screen opens on the sign-in, its address focused: ctrl+r tries again from there.
|
||||
const focused = await d.waitFor("Log in to a LLeMbas instance")
|
||||
const focused = await d.waitFor("Sign in to a LLeMbas server")
|
||||
await d.key("\x12")
|
||||
const opened = await d.waitFor("fake/coder")
|
||||
await d.type("hi")
|
||||
@@ -408,7 +408,7 @@ for (const [cols, rows] of [
|
||||
])
|
||||
const tty = mkdtempSync(join(tmpdir(), "lembas-smoke-tty-"))
|
||||
const pane = fakePane(tty, { output: "SMOKE-PANE-OUTPUT 1 failed" })
|
||||
const ttyEnv = { LLEMBAS_TTY: "2.0.0", LLEMBAS_TTY_PANE: "3", LLEMBAS_TTY_EXECUTABLE: pane.exe, LLEMBAS_TTY_STATUS_DIR: pane.statusDir }
|
||||
const ttyEnv = { LLEMBAS_TERM: "2.0.0", LLEMBAS_TERM_PANE: "3", LLEMBAS_TERM_EXECUTABLE: pane.exe, LLEMBAS_TERM_STATUS_DIR: pane.statusDir }
|
||||
const context = join(tty, "context-1.json")
|
||||
writeFileSync(context, JSON.stringify({ version: 2, pane: 7, cwd, shell: "zsh", blocks: [{ seq: 1, command: "make test", exit: 2, output: "FAIL src/oven.test.ts\n1 failed" }] }), { mode: 0o600 })
|
||||
const args = ["terminal", "--window", "smoke-1", "--pane", "7"]
|
||||
@@ -508,10 +508,11 @@ for (const [cols, rows] of [
|
||||
check("display: opened again, the model is told the command it placed is still at the prompt", last.includes("make clean") && last.includes("is still there, not run"), last)
|
||||
// Outside a LLeMbas terminal there is no display; the version says the contract.
|
||||
const outside = run(["terminal", "--window", "x"])
|
||||
check("lembas terminal outside a LLeMbas terminal: status 2, in words", outside.code === 2 && outside.err.includes("LLEMBAS_TTY is not set"), JSON.stringify(outside))
|
||||
check("lembas terminal outside a LLeMbas terminal: status 2, in words", outside.code === 2 && outside.err.includes("LLEMBAS_TERM is not set"), JSON.stringify(outside))
|
||||
const v = JSON.parse(run(["--version", "--json"]).out || "{}")
|
||||
check("--version --json: terminal contract 3 with the display's, the settings' and the placing's capabilities", v.terminal_contract === 3 && ["terminal_surface", "terminal_await", "terminal_context_2", "terminal_models", "terminal_settings", "terminal_placed"].every((c) => (v.capabilities ?? []).includes(c)), JSON.stringify(v))
|
||||
check("--version --json: terminal contract 4 with the display's, the settings', the placing's and the renamed names' capabilities", v.terminal_contract === 4 && ["terminal_surface", "terminal_await", "terminal_context_2", "terminal_models", "terminal_settings", "terminal_placed", "terminal_names_2"].every((c) => (v.capabilities ?? []).includes(c)), JSON.stringify(v))
|
||||
// The terminal's settings and its two models, from the compiled binary, with a GUI's bare environment.
|
||||
// In the names of a terminal released before the rename (LLEMBAS_TTY): read as before.
|
||||
const bare = (a: string[], stdin = "") => {
|
||||
const p = Bun.spawnSync([bin, ...a], { cwd: "/", env: { LEMBAS_HOME: h, PATH: "/usr/bin:/bin", HOME: h, LLEMBAS_TTY: "2.0.0" }, stdin: Buffer.from(stdin), stdout: "pipe", stderr: "pipe" })
|
||||
return { code: p.exitCode, out: p.stdout.toString(), err: p.stderr.toString() }
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# The terminal's tests once more, spelled as a terminal released before the rename spells them
|
||||
# (LLEMBAS_TTY…, llembas-tty-status=1, llembas-tty-input=1): the CLI reads both families of names
|
||||
# (harness/acp.md, *The names before the rename*), so every one of them passes unchanged.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
LEMBAS_TEST_TERMINAL_NAMES=before exec bun test --timeout 20000 \
|
||||
tests/terminal.test.ts tests/terminal-display.test.ts tests/terminal-contract3.test.ts \
|
||||
tests/tui/terminal.test.tsx tests/tui/terminal-display.test.tsx
|
||||
+116
-16
@@ -13,6 +13,8 @@
|
||||
// block: a directory outside `roots` is refused, a mode beyond `max_mode` is lowered to it, an
|
||||
// untrusted project is refused, and an approval nobody answers in time is a denial. The hardline
|
||||
// applies in every mode, as everywhere.
|
||||
import { clampMode, MODE_RANK } from "../permission/modes.ts"
|
||||
import { within } from "../within.ts"
|
||||
import { closeSync, existsSync, fstatSync, openSync, readdirSync, readSync, statSync } from "node:fs"
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
|
||||
import { createApp, InteractiveOnlyError, type App, type SessionContext } from "../app.ts"
|
||||
@@ -98,6 +100,20 @@ export interface Limits {
|
||||
sharedOnly?: boolean
|
||||
}
|
||||
|
||||
/** The requests that are answered for a session whatever the limits have become (acp.md, *The
|
||||
* device's limits*): stopping, asking and deleting are never refused for a limit. */
|
||||
export const ALWAYS_ANSWERED = ["session/cancel", "_lembas/session/status", "_lembas/session/delete"]
|
||||
|
||||
/** A request for a session that is already open, under the limits as they are now: refused in
|
||||
* the words a new session in its directory would be (`stop`: what it was doing is stopped), or
|
||||
* served in a mode no looser than `max_mode`. */
|
||||
export function openUnder(L: Limits | undefined, o: { cwd: string; mode: Mode; method: string; byName?: boolean }): { refused: string; stop: true } | { mode: Mode } {
|
||||
if (!L || o.byName || ALWAYS_ANSWERED.includes(o.method)) return { mode: o.mode }
|
||||
const why = refusalFor(L, o.cwd)
|
||||
if (why) return { refused: why, stop: true }
|
||||
return { mode: clampMode(o.mode, L.maxMode) }
|
||||
}
|
||||
|
||||
/** Why a remote session may not be opened in `dir` under these limits, or undefined when it may. */
|
||||
export function refusalFor(L: Limits | undefined, dir: string): string | undefined {
|
||||
if (!L) return undefined
|
||||
@@ -152,8 +168,13 @@ interface Terminal {
|
||||
pty: { write(d: string | Uint8Array): void; resize(cols: number, rows: number): void; close?(): void }
|
||||
/** The rc files its shell integration was given, removed with it. */
|
||||
cleanup(): void
|
||||
/** Where it was opened: judged again whenever something is typed into it. */
|
||||
cwd: string
|
||||
}
|
||||
|
||||
/** Said with `_lembas/terminal/exit` when the device's limits closed a terminal. */
|
||||
export const TERMINAL_OFF = "Terminals are switched off on this computer, or its folder is no longer accepted for remote work — closed there."
|
||||
|
||||
/** Most terminals one link may hold at once. */
|
||||
const MAX_TERMINALS = 4
|
||||
|
||||
@@ -163,18 +184,13 @@ export function effortOf(v: unknown): Level | undefined {
|
||||
return isLevel(v) ? v : undefined
|
||||
}
|
||||
|
||||
const MODE_RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
|
||||
export function clampMode(wanted: Mode, max: Mode): Mode {
|
||||
return MODE_RANK[wanted] < MODE_RANK[max] ? max : wanted
|
||||
}
|
||||
export { clampMode }
|
||||
|
||||
export function underRoots(dir: string, roots: string[]): boolean {
|
||||
// Symlinks followed (realPath), so a link inside a root that points out of it is outside.
|
||||
const target = realPath(dir)
|
||||
return roots.some((r) => {
|
||||
const root = realPath(expandHome(r))
|
||||
const rel = relative(root, target)
|
||||
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))
|
||||
return within(target, realPath(expandHome(r)))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -968,11 +984,60 @@ export class AcpAgent {
|
||||
|
||||
private get(p: any): Session {
|
||||
const id = String(p?.sessionId ?? "")
|
||||
const s = this.sessions.get(id) ?? this.load(id)
|
||||
const held = this.sessions.get(id)
|
||||
// The limits as they are at this moment, for a session already open as for a new one
|
||||
// (acp.md, *The device's limits*): `load` judges one it opens, this one that is open.
|
||||
if (held) this.fit(held)
|
||||
const s = held ?? this.load(id)
|
||||
if (!s) throw new RpcError(INVALID_PARAMS, "no such session")
|
||||
return s
|
||||
}
|
||||
|
||||
/** Judge an open session by the limits as they are now. One that no longer fits — remote work
|
||||
* turned off, its directory taken out of the roots, its project's trust withdrawn — is refused
|
||||
* in the words a new session there would be, and what it was doing is stopped: its turn, what
|
||||
* waits behind it, its background jobs. One that fits runs no looser than `max_mode`. */
|
||||
private fit(s: Session): void {
|
||||
const now = openUnder(this.limits, { cwd: s.cwd, mode: s.app.engine.mode, method: "" })
|
||||
if ("refused" in now) {
|
||||
this.halt(s)
|
||||
throw new RpcError(INVALID_PARAMS, now.refused)
|
||||
}
|
||||
s.app.engine.mode = now.mode
|
||||
}
|
||||
|
||||
/** Stop everything a session is doing, quietly: the person turned it off at the device. */
|
||||
private halt(s: Session): void {
|
||||
try {
|
||||
for (const take of [...(s.waiting?.values() ?? [])]) take()
|
||||
s.app.cancel()
|
||||
s.app.stopSubagents?.()
|
||||
s.app.registry.stopAll(s.id, true)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** The limits changed (the link looks every few seconds, link.ts): applied now to what is open,
|
||||
* without waiting for a request — turns stopped, modes lowered, terminals closed. Returns how
|
||||
* many sessions and terminals were stopped. */
|
||||
enforce(): number {
|
||||
const L = this.limits
|
||||
if (!L) return 0
|
||||
let n = 0
|
||||
for (const s of this.sessions.values()) {
|
||||
if (refusalFor(L, s.cwd)) {
|
||||
if (occupied(s)) n++
|
||||
this.halt(s)
|
||||
} else s.app.engine.mode = clampMode(s.app.engine.mode, L.maxMode)
|
||||
}
|
||||
for (const [id, t] of [...this.terminals]) {
|
||||
if (L.terminal && !refusalFor(L, t.cwd)) continue
|
||||
n++
|
||||
this.terminalClose(id)
|
||||
this.peer.notify("_lembas/terminal/exit", { terminalId: id, code: null, reason: TERMINAL_OFF })
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
/** A session this machine has in its store but not in memory: after a restart of either
|
||||
* side, or one a terminal had open and let go of. Opened under the same rules as a new one. */
|
||||
private load(id: string): Session | undefined {
|
||||
@@ -1227,6 +1292,8 @@ export class AcpAgent {
|
||||
if (refused) throw new RpcError(INVALID_PARAMS, refused)
|
||||
root = findProject(dir).root
|
||||
}
|
||||
// On the link the list is of one directory the device accepts, never of the whole machine.
|
||||
if (this.limits && root === undefined) throw new RpcError(INVALID_PARAMS, "a directory is required: _lembas/sessions/list lists the sessions of one project (cwd)")
|
||||
const limit = Math.max(1, Math.min(50, Number(p?.limit) || 25))
|
||||
const rows = (this.store ??= new Store()).sessions(limit, root, true)
|
||||
return {
|
||||
@@ -1542,9 +1609,15 @@ export class AcpAgent {
|
||||
|
||||
/** The terminal running a session, when one does. Its mode beyond the device's limit stops a
|
||||
* prompt from the web UI unless the session was shared by name (/remote). */
|
||||
private terminalFor(p: any) {
|
||||
private terminalFor(p: any, anyway = false) {
|
||||
const s = this.hub?.shared.get(String(p?.sessionId ?? ""))
|
||||
if (!s || s.client.isClosed) return undefined
|
||||
// Shared by the device's limits, not by name: judged when it was shared (hub/share), and
|
||||
// again on every request, as they are now. Stopping, asking and deleting are never refused.
|
||||
if (!anyway && !s.explicit && this.limits) {
|
||||
const why = refusalFor(this.limits, s.cwd)
|
||||
if (why) throw new RpcError(INVALID_PARAMS, why)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -1780,7 +1853,7 @@ export class AcpAgent {
|
||||
* sending its prompt a second time. */
|
||||
private async status(p: any) {
|
||||
const id = String(p?.sessionId ?? "")
|
||||
const t = this.terminalFor(p)
|
||||
const t = this.terminalFor(p, true)
|
||||
if (t) {
|
||||
// The terminal knows its turns; what the hub saw of them, when it cannot be asked.
|
||||
const turns = await t.client
|
||||
@@ -1805,12 +1878,26 @@ export class AcpAgent {
|
||||
progress: s.app.engine.progress.current,
|
||||
tree: treeOf(s.app),
|
||||
}
|
||||
const row = (this.store ??= new Store()).session(id)
|
||||
const found = (this.store ??= new Store()).session(id)
|
||||
// One the client was never shown and that lies outside where this device accepts remote work
|
||||
// is answered as one that does not exist (acp.md, *Which sessions a client may reach*).
|
||||
const row = found && !this.unreachable(id, found.root) ? found : undefined
|
||||
// Not open: the last turn it finished, as kept across a restart, its plan and its jobs as stored.
|
||||
const last = row ? turnStore(id).load().at(-1)?.[0] : undefined
|
||||
return { sessionId: id, exists: Boolean(row), held: "none", busy: false, title: row?.title ?? "", queued: [], ...(last ? { lastTurnId: last } : {}), plan: row ? this.storedPlan(id) : null, jobs: row ? this.storedJobsOf(id) : [] }
|
||||
}
|
||||
|
||||
/** Whether a stored session is out of this client's reach (acp.md, *Which sessions a client may
|
||||
* reach*): on the link, one it does not hold, no terminal shares and it was never shown
|
||||
* (REMOTE_META) is reached only inside the roots, with remote work on — the rule a delete
|
||||
* follows. An editor on stdio is the person's own and reaches every session. */
|
||||
private unreachable(id: string, root: string): boolean {
|
||||
if (!this.limits) return false
|
||||
const store = (this.store ??= new Store())
|
||||
const shown = this.sessions.has(id) || Boolean(this.hub?.shared.has(id)) || store.meta<boolean>(id, REMOTE_META) === true
|
||||
return deletableFor(this.limits, root, shown) !== undefined
|
||||
}
|
||||
|
||||
/** A stored session's jobs (capability `jobs`), or none. */
|
||||
private storedJobsOf(id: string): JobInfo[] {
|
||||
try {
|
||||
@@ -1894,7 +1981,7 @@ export class AcpAgent {
|
||||
private async deleteSession(p: any) {
|
||||
const id = String(p?.sessionId ?? "")
|
||||
const store = (this.store ??= new Store())
|
||||
const t = this.terminalFor(p)
|
||||
const t = this.terminalFor(p, true)
|
||||
if (t) return t.client.request("hub/delete", { sessionId: t.sessionId }, 30_000)
|
||||
const row = store.session(id)
|
||||
if (!row) return { deleted: false }
|
||||
@@ -1936,7 +2023,8 @@ export class AcpAgent {
|
||||
if (t) return t.client.request("hub/title", { sessionId: t.sessionId, title }, 15_000)
|
||||
const id = String(p?.sessionId ?? "")
|
||||
const store = (this.store ??= new Store())
|
||||
if (!store.session(id)) throw new RpcError(INVALID_PARAMS, "no such session")
|
||||
const row = store.session(id)
|
||||
if (!row || this.unreachable(id, row.root)) throw new RpcError(INVALID_PARAMS, "no such session")
|
||||
store.setTitle(id, title)
|
||||
return { title }
|
||||
}
|
||||
@@ -1994,7 +2082,7 @@ export class AcpAgent {
|
||||
throw new RpcError(INVALID_PARAMS, `A terminal could not be opened on this computer (${basename(picked.shell)}): ${(e as Error).message.split("\n")[0]}`)
|
||||
}
|
||||
const pty = (proc as unknown as { terminal: Terminal["pty"] }).terminal
|
||||
this.terminals.set(id, { proc, pty, cleanup: launch.cleanup })
|
||||
this.terminals.set(id, { proc, pty, cleanup: launch.cleanup, cwd })
|
||||
void proc.exited.then((code) => {
|
||||
launch.cleanup()
|
||||
if (!this.terminals.delete(id)) return
|
||||
@@ -2003,8 +2091,20 @@ export class AcpAgent {
|
||||
return { terminalId: id, cwd, cols, rows, shell: launch.kind, integration: launch.integration }
|
||||
}
|
||||
|
||||
/** An open terminal under the limits as they are now: closed, and said, when terminals were
|
||||
* switched off or its folder is no longer accepted. */
|
||||
private terminalNow(id: string): Terminal | undefined {
|
||||
const t = this.terminals.get(id)
|
||||
if (!t) return undefined
|
||||
const L = this.limits
|
||||
if (L?.terminal && !refusalFor(L, t.cwd)) return t
|
||||
this.terminalClose(id)
|
||||
this.peer.notify("_lembas/terminal/exit", { terminalId: id, code: null, reason: TERMINAL_OFF })
|
||||
return undefined
|
||||
}
|
||||
|
||||
private terminalInput(p: any) {
|
||||
const t = this.terminals.get(String(p?.terminalId ?? ""))
|
||||
const t = this.terminalNow(String(p?.terminalId ?? ""))
|
||||
if (!t || typeof p?.data !== "string") return
|
||||
t.pty.write(Buffer.from(p.data, "base64"))
|
||||
}
|
||||
@@ -2049,7 +2149,7 @@ export class AcpAgent {
|
||||
private async cancel(p: any): Promise<{ cancelled: "running" | "queued" | "none" }> {
|
||||
const named = p?._meta?.lembas?.turnId
|
||||
const turn = typeof named === "string" && named.trim() ? named.trim().slice(0, 100) : undefined
|
||||
const t = this.terminalFor(p)
|
||||
const t = this.terminalFor(p, true)
|
||||
if (t) {
|
||||
// The terminal knows its turns. One named is asked of it; a terminal of a build that has no
|
||||
// such request is not told to stop whatever runs there.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// from cached file summaries (preferring unsaved open buffers sent by the editor), returning
|
||||
// compact declarations/excerpts in a deterministic session order so KV-cache prefill hits
|
||||
// stay warm across keystrokes.
|
||||
import { relativeWithin } from "../within.ts"
|
||||
import { readFileSync, statSync } from "node:fs"
|
||||
import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path"
|
||||
import type { FileIndex } from "../project/files.ts"
|
||||
@@ -273,8 +274,7 @@ export class CompletionContext {
|
||||
private relOf(root: string, filePath?: string): string {
|
||||
if (!filePath) return ""
|
||||
if (!isAbsolute(filePath)) return filePath.replace(/\\/g, "/")
|
||||
const rel = relative(root, resolve(filePath)).replace(/\\/g, "/")
|
||||
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : ""
|
||||
return relativeWithin(resolve(filePath), resolve(root)) ?? ""
|
||||
}
|
||||
|
||||
private readCached(root: string, rel: string): CachedFile | undefined {
|
||||
|
||||
+2
-2
@@ -5,6 +5,7 @@
|
||||
//
|
||||
// Neither autocomplete nor a rewrite runs a tool or reads the disk: they see what the client sent.
|
||||
// What a model answers is text for the client to insert or to show as a diff — never run here.
|
||||
import { relativeWithin } from "../within.ts"
|
||||
import { isAbsolute, relative, resolve } from "node:path"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { apiCall, LembasError, type ServedModel } from "../lembas/client.ts"
|
||||
@@ -413,8 +414,7 @@ function saidPath(p: unknown, root: string): string | undefined {
|
||||
const clean = oneLine(p).replace(/[<>]/g, "").trim().slice(0, 1000)
|
||||
if (!clean) return undefined
|
||||
if (!isAbsolute(clean)) return clean
|
||||
const rel = relative(root, resolve(clean))
|
||||
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : clean
|
||||
return relativeWithin(resolve(clean), resolve(root)) || clean
|
||||
}
|
||||
|
||||
/** Text of a file's or a tool's own inside the block: it cannot close the block or the selection
|
||||
|
||||
+43
-32
@@ -3,12 +3,14 @@
|
||||
// What bounds them is this device: only inside `remote.roots` with remote work on; a path judged
|
||||
// where it really is, symlinks followed first; never the CLI's own files, never a protected path;
|
||||
// read-only where the device allows plan mode only. conformance/device_files.json.
|
||||
import { closeSync, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync, chmodSync } from "node:fs"
|
||||
import { projectRunsCode } from "../runs-code.ts"
|
||||
import { within } from "../within.ts"
|
||||
import { closeSync, constants, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync, chmodSync } from "node:fs"
|
||||
import { cp, rm } from "node:fs/promises"
|
||||
import { createHash } from "node:crypto"
|
||||
import { homedir } from "node:os"
|
||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path"
|
||||
import { expandHome, globalPaths, paths } from "../config/paths.ts"
|
||||
import { expandHome, globalPaths, ownDir, ownDirs, paths } from "../config/paths.ts"
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { realPath } from "../permission/evaluate.ts"
|
||||
@@ -24,7 +26,7 @@ export type FsReason = "off" | "invalid" | "outside" | "own" | "protected" | "ru
|
||||
* target. `remove`: delete and a move's source — the name itself, a link not followed. */
|
||||
export type FsOp = "read" | "write" | "remove"
|
||||
|
||||
const inside = (p: string, dir: string) => p === dir || p.startsWith(dir.endsWith("/") ? dir : dir + "/")
|
||||
const inside = within
|
||||
|
||||
export interface Judging {
|
||||
op: FsOp
|
||||
@@ -76,14 +78,7 @@ export function judgePath(o: Judging): { ok: true; real: string } | { refused: F
|
||||
* device's user. `_lembas/fs/*` reads them and never changes them: a path that is one, is under
|
||||
* one, or — for the project's and the home's — holds one. */
|
||||
export function runsCode(p: string, home: string, R: typeof F.runs_code = F.runs_code): boolean {
|
||||
const parts = p.split("/")
|
||||
if (parts.some((x) => R.segments.includes(x))) return true
|
||||
const at = parts.lastIndexOf(R.project_dir)
|
||||
if (at >= 0) {
|
||||
const rest = parts.slice(at + 1)
|
||||
// The directory itself (moved or copied into place it brings all of them), or one of its names.
|
||||
if (!rest.length || R.project.includes(rest[0]!)) return true
|
||||
}
|
||||
if (projectRunsCode(p, undefined, R)) return true
|
||||
return R.home.some((h) => {
|
||||
const g = join(home, h)
|
||||
return inside(p, g) || (p !== home && inside(g, p) && inside(p, home))
|
||||
@@ -138,10 +133,7 @@ const refuse = (reason: FsReason, path: string, message?: string, extra: Record<
|
||||
throw new RpcError(INVALID_PARAMS, message ?? SENTENCES[reason]?.(path) ?? `${path}: ${reason}`, { reason, ...extra })
|
||||
}
|
||||
|
||||
/** The CLI's own directories: its configuration, data and state — the user's, and local mode's. */
|
||||
export function ownDirs(): string[] {
|
||||
return [...new Set([paths.config, paths.data, paths.state, globalPaths.config, globalPaths.data, globalPaths.state])]
|
||||
}
|
||||
export { ownDirs }
|
||||
|
||||
const guarded = (p: string) => protectedPath(p) !== undefined
|
||||
|
||||
@@ -163,9 +155,34 @@ export async function hashFd(fd: number): Promise<string> {
|
||||
return `sha256:${h.digest("hex")}`
|
||||
}
|
||||
|
||||
/** Open a regular file to read, and nothing else. A named pipe opened for reading blocks until a
|
||||
* writer comes — on the service's only thread, every session with it — and a device may do
|
||||
* anything on open: what is not a regular file is never opened, and the open does not wait
|
||||
* (O_NONBLOCK), so one swapped in between the look and the open is found by fstat and closed.
|
||||
* Undefined when there is nothing there; `not_a_file` for anything else. */
|
||||
export function openRegular(abs: string): number | undefined | "not_a_file" {
|
||||
let st
|
||||
try {
|
||||
st = statSync(abs)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (!st.isFile()) return "not_a_file"
|
||||
let fd: number
|
||||
try {
|
||||
fd = openSync(abs, constants.O_RDONLY | constants.O_NONBLOCK)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (fstatSync(fd).isFile()) return fd
|
||||
closeSync(fd)
|
||||
return "not_a_file"
|
||||
}
|
||||
|
||||
/** The same for a path this process chose itself (the show tool's file). */
|
||||
export async function hashFile(abs: string): Promise<string> {
|
||||
const fd = openSync(abs, "r")
|
||||
const fd = openRegular(abs)
|
||||
if (typeof fd !== "number") throw new Error(`${abs}: ${fd === undefined ? "no such file" : "not a regular file"}`)
|
||||
try {
|
||||
return await hashFd(fd)
|
||||
} finally {
|
||||
@@ -187,7 +204,7 @@ function journal(change?: (list: string[]) => string[]): string[] {
|
||||
if (!change) return list
|
||||
const next = change(list)
|
||||
try {
|
||||
mkdirSync(paths.state, { recursive: true, mode: 0o700 })
|
||||
ownDir(paths.state)
|
||||
writeFileSync(journalFile(), JSON.stringify(next), { mode: 0o600 })
|
||||
} catch {}
|
||||
return next
|
||||
@@ -427,7 +444,9 @@ export class DeviceFiles {
|
||||
const e = this.entry(abs)
|
||||
if (p?.hash !== true || e.kind !== "file") return e
|
||||
// Opened in the same breath as it was judged: the hash is of that file.
|
||||
const fd = openSync(abs, "r")
|
||||
const fd = openRegular(abs)
|
||||
if (fd === undefined) return refuse("missing", said)
|
||||
if (fd === "not_a_file") return refuse("not_a_file", said)
|
||||
try {
|
||||
return { ...e, hash: await hashFd(fd) }
|
||||
} finally {
|
||||
@@ -438,15 +457,11 @@ export class DeviceFiles {
|
||||
read(p: any) {
|
||||
const said = String(p?.path ?? "")
|
||||
const abs = this.judge("read", p?.path)
|
||||
let fd: number
|
||||
try {
|
||||
fd = openSync(abs, "r")
|
||||
} catch {
|
||||
return refuse("missing", said)
|
||||
}
|
||||
const fd = openRegular(abs)
|
||||
if (fd === undefined) return refuse("missing", said)
|
||||
if (fd === "not_a_file") return refuse("not_a_file", said)
|
||||
try {
|
||||
const st = fstatSync(fd)
|
||||
if (!st.isFile()) return refuse("not_a_file", said)
|
||||
const offset = Number.isInteger(p?.offset) && p.offset > 0 ? (p.offset as number) : 0
|
||||
const length = Math.max(0, Math.min(F.chunk_max_bytes, Number.isInteger(p?.length) && p.length >= 0 ? (p.length as number) : F.chunk_max_bytes))
|
||||
const buf = Buffer.alloc(Math.max(0, Math.min(length, st.size - offset)))
|
||||
@@ -468,14 +483,10 @@ export class DeviceFiles {
|
||||
|
||||
/** The hash of the file at `abs` now, or null when there is none. */
|
||||
private async current(abs: string): Promise<string | null> {
|
||||
let fd: number
|
||||
const fd = openRegular(abs)
|
||||
if (typeof fd !== "number") return null
|
||||
try {
|
||||
fd = openSync(abs, "r")
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return fstatSync(fd).isFile() ? await hashFd(fd) : null
|
||||
return await hashFd(fd)
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
|
||||
+3
-3
@@ -17,10 +17,10 @@
|
||||
//
|
||||
// The socket is the user's own (0600, in ~/.local/state/lembas). It answers JSON-RPC, one
|
||||
// message a line, the same framing as `serve --stdio`.
|
||||
import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs"
|
||||
import { chmodSync, existsSync, rmSync } from "node:fs"
|
||||
import { connect, createServer, type Server, type Socket } from "node:net"
|
||||
import { join } from "node:path"
|
||||
import { isLocal, paths } from "../config/paths.ts"
|
||||
import { isLocal, ownDir, paths } from "../config/paths.ts"
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import type { CommandInfo } from "../session/commands.ts"
|
||||
import { clampMode, keeps, occupied, refusalFor, type AcpAgent, type Limits } from "./agent.ts"
|
||||
@@ -140,7 +140,7 @@ export class Hub {
|
||||
/** Take the socket. False: another hub is alive on it. */
|
||||
async listen(path = hubSocket()): Promise<boolean> {
|
||||
if (isLocal()) return false
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
if (existsSync(path)) {
|
||||
if (await answers(path)) return false
|
||||
rmSync(path, { force: true })
|
||||
|
||||
+13
-3
@@ -95,7 +95,7 @@ export function pickInstance(name?: string): Instance {
|
||||
return one
|
||||
}
|
||||
const list = Object.values(all)
|
||||
if (!list.length) throw new LinkError("not logged in to any LLeMbas instance — lembas login <address>", "not_logged_in")
|
||||
if (!list.length) throw new LinkError("not signed in to a LLeMbas server — lembas login <address>", "not_logged_in")
|
||||
if (list.length > 1) throw new LinkError(`logged in to several instances; name one: ${Object.keys(all).join(", ")}`, "not_logged_in")
|
||||
return list[0]!
|
||||
}
|
||||
@@ -187,7 +187,7 @@ type Outcome =
|
||||
* `roots: []` and can tell a device that allows no folder yet from one that is not running, and a
|
||||
* `lembas remote add` or `enable` makes it serve, without a restart. */
|
||||
export async function runLink(o: LinkOptions = {}): Promise<LinkStatus> {
|
||||
const local = refusedLocally("the link to a LLeMbas instance (lembas service, /remote)")
|
||||
const local = refusedLocally("the link to the LLeMbas server (lembas service, /remote)")
|
||||
if (local) throw new LinkError(local, "disabled")
|
||||
const limits = limitsFromConfig({ sharedOnly: o.sharedOnly })
|
||||
const poll = o.pollMs ?? 2000
|
||||
@@ -344,8 +344,18 @@ export async function runLink(o: LinkOptions = {}): Promise<LinkStatus> {
|
||||
// the start is told again by dialling again, once nothing is working here: the sessions
|
||||
// are the hub's, so they outlive the link either way.
|
||||
const said = announced(limits)
|
||||
let applied = said
|
||||
watch = setInterval(() => {
|
||||
if (changed || announced(limits) === said || o.hub?.busy()) return
|
||||
const now = announced(limits)
|
||||
// A change is applied to what is open at once (acp.md): a session that no longer fits
|
||||
// is stopped, a terminal closed — `lembas remote disable` is a stop. Then the redial.
|
||||
if (now !== applied) {
|
||||
applied = now
|
||||
try {
|
||||
agent.enforce()
|
||||
} catch {}
|
||||
}
|
||||
if (changed || now === said || o.hub?.busy()) return
|
||||
changed = true
|
||||
ws.close()
|
||||
}, poll)
|
||||
|
||||
+3
-3
@@ -12,9 +12,9 @@
|
||||
// through a rename, so a reader never sees half of it; deduplicated; the newest DELETED_MAX kept —
|
||||
// a machine whose link never comes back must not grow it for ever, and a chat that old is long
|
||||
// out of anybody's mind.
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { isLocal, paths } from "../config/paths.ts"
|
||||
import { isLocal, ownDir, paths } from "../config/paths.ts"
|
||||
|
||||
export const DELETED_MAX = 500
|
||||
|
||||
@@ -33,7 +33,7 @@ export function pendingDeleted(): string[] {
|
||||
function write(ids: string[]) {
|
||||
const file = deletedFile()
|
||||
if (!ids.length) return void rmSync(file, { force: true })
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
const tmp = `${file}.${process.pid}.tmp`
|
||||
writeFileSync(tmp, JSON.stringify(ids), { mode: 0o600 })
|
||||
renameSync(tmp, file)
|
||||
|
||||
+2
-1
@@ -4,6 +4,7 @@
|
||||
// composer adds — images and files — stored the way the TUI stores a pasted image or a dropped
|
||||
// file: written under the session's attachment directory and attached by path, so a vision model
|
||||
// sees the image, any other model is told it is there, and the model can read a file again later.
|
||||
import { within as inDir } from "../within.ts"
|
||||
import { mkdirSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { basename, extname, join, resolve } from "node:path"
|
||||
import type { App } from "../app.ts"
|
||||
@@ -103,7 +104,7 @@ export function mayAttach(abs: string, root: string, roots?: string[]): boolean
|
||||
const real = realPath(abs)
|
||||
const within = (p: string, dir: string) => {
|
||||
const d = realPath(dir)
|
||||
return p === d || p.startsWith(d.endsWith("/") ? d : d + "/")
|
||||
return inDir(p, d)
|
||||
}
|
||||
if (!within(real, root)) return false
|
||||
if (roots && !roots.some((r) => within(real, expandHome(r)))) return false
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// device decides whether (Accept scheduled work, `remote.scheduled`) and how far (the schedule's
|
||||
// mode, never wider than Edit unless it says Auto, lowered to remote.max_mode). The pure rules are
|
||||
// here, run by the conformance areas `scheduled`, `silent` and `monitor`; agent.ts wires them in.
|
||||
import { clampMode } from "../permission/modes.ts"
|
||||
import { trackGroup } from "../shutdown.ts"
|
||||
import { spawn } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import { join } from "node:path"
|
||||
@@ -17,9 +19,6 @@ import type { Message } from "../provider/types.ts"
|
||||
|
||||
export const SCHEDULED = LOOP.scheduled
|
||||
|
||||
const RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
|
||||
/** A mode lowered to `max` (agent.ts clampMode, kept here so neither imports the other). */
|
||||
const clampMode = (wanted: Mode, max: Mode): Mode => (RANK[wanted] < RANK[max] ? max : wanted)
|
||||
|
||||
/** Why a scheduled request is refused: `data.reason` of the -32602. */
|
||||
export type Refusal = "scheduled_off" | "plan" | "folder" | "permission"
|
||||
@@ -195,6 +194,7 @@ export function runMonitor(command: string, cwd: string, timeoutS: number, env:
|
||||
const started = Date.now()
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn("bash", ["-c", `exec 2>&1\n${command}`], { cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], env })
|
||||
trackGroup(child.pid)
|
||||
const hash = createHash("sha256")
|
||||
const kept: Buffer[] = []
|
||||
let keptBytes = 0
|
||||
|
||||
+1
-1
@@ -353,7 +353,7 @@ export class Share {
|
||||
const local = refusedLocally("/remote")
|
||||
if (local) return local
|
||||
const { instances } = await import("../lembas/login.ts")
|
||||
if (!Object.keys(instances()).length) return "not logged in to a LLeMbas instance — /login first"
|
||||
if (!Object.keys(instances()).length) return "not signed in to a LLeMbas server — /login first"
|
||||
const hub = new Hub({ service: false, limits: limitsFromConfig() })
|
||||
if (!(await hub.listen())) return (await this.connect()) ? undefined : "something holds the hub's socket but does not answer"
|
||||
const stop = new AbortController()
|
||||
|
||||
+3
-5
@@ -1,5 +1,6 @@
|
||||
// Wiring shared by every front end: load config, find the project, resolve the model, and build
|
||||
// an Engine. The TUI and `run` both start here.
|
||||
import { stricterMode } from "./permission/modes.ts"
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs"
|
||||
import { join, relative } from "node:path"
|
||||
import { capacityRefusal, capacityBeside } from "./session/capacity.ts"
|
||||
@@ -97,7 +98,7 @@ export interface AppOptions {
|
||||
automated?: true
|
||||
/** The LLeMbas terminal this session runs in (harness acp.md, *A terminal as the client*):
|
||||
* given by the TUI and `lembas run` only — never for a session on the link or an editor's —
|
||||
* and only when LLEMBAS_TTY is set. Absent: nothing of it applies. */
|
||||
* and only when the terminal's variable is set (terminal/env.ts). Absent: nothing of it applies. */
|
||||
terminal?: import("./terminal/env.ts").TerminalEnv
|
||||
/** The terminal's display (harness acp.md, *The terminal's display*): the session is offered
|
||||
* the terminal profile's tools and no other, reads no project, has two modes, and gives its
|
||||
@@ -273,10 +274,7 @@ const PENDING_META = "terminal_pending"
|
||||
/** session_meta: the command the agent placed at the person's prompt that was not seen run or dismissed. */
|
||||
const PLACED_META = "terminal_placed"
|
||||
|
||||
const MODE_RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
|
||||
export function stricterMode(a: Mode | undefined, b: Mode): Mode {
|
||||
return a !== undefined && MODE_RANK[a] > MODE_RANK[b] ? a : b
|
||||
}
|
||||
export { stricterMode }
|
||||
|
||||
export function createApp(o: AppOptions): App {
|
||||
const project = findProject(o.cwd)
|
||||
|
||||
+82
-35
@@ -52,27 +52,27 @@ Usage:
|
||||
lembas config schema [--link]
|
||||
write JSON Schemas for editors (--link: point the files at them)
|
||||
lembas login [address] [--ca file] [--default] [--keep-services] [--json]
|
||||
sign in to a LLeMbas instance: its models, voice and search
|
||||
sign in to a LLeMbas server: its models, voice and search
|
||||
(again: read them now; --default pins its default model;
|
||||
--json: one JSON object per line, for a program to read)
|
||||
… | lembas login --token-stdin --server <url> [--ca file] [--json]
|
||||
sign in with a token a program already holds (lmb_…, read
|
||||
from stdin only), checked against the server first
|
||||
lembas logout [connection] sign out of one, and remove what login wrote
|
||||
lembas logout [name] sign out, and remove what login wrote
|
||||
lembas serve --stdio an ACP agent on stdin/stdout, for an editor that speaks ACP
|
||||
lembas service install | uninstall | status | logs [-f] | run
|
||||
work from a LLeMbas instance as a background service (remote:)
|
||||
work from the LLeMbas server as a background service (remote:)
|
||||
lembas service scheduled [on|off]
|
||||
Accept scheduled work: your schedules may run here as agent
|
||||
turns (remote.scheduled, off by default)
|
||||
lembas remote list | add <dir>… | remove <dir>… | enable | disable
|
||||
| mode <manual|edit|auto|plan> | terminal <on|off> | scheduled <on|off>
|
||||
| files-that-run-code <on|off> [--json]
|
||||
what the instance may do here (remote:): the directories it may
|
||||
what the server may do here (remote:): the directories it may
|
||||
work in (add turns remote work on), the most permissive mode,
|
||||
terminals; a running service applies a change within seconds
|
||||
(--json: one object, {enabled, roots, max_mode, terminal,
|
||||
scheduled})
|
||||
scheduled, files_that_run_code})
|
||||
lembas mcp [list] connect the MCP servers and list their tools and prompts
|
||||
lembas mcp auth <server> sign in to a remote MCP server (OAuth)
|
||||
lembas mcp logout <server> forget a server's stored sign-in
|
||||
@@ -80,7 +80,9 @@ Usage:
|
||||
lembas voice say "…" [-o f] speak (or write a WAV); voice transcribe <file>
|
||||
lembas trust [--readonly] trust the current project (its .agent/ config is then honoured)
|
||||
lembas update [--check] [--channel stable|beta] [vX.Y.Z] [--rollback]
|
||||
install the newest release (or that one; --rollback: the one before)
|
||||
install the newest release of this major version (or the one named,
|
||||
any major; --rollback: the one before). A version named or rolled
|
||||
back to stays until lembas update is run again
|
||||
lembas kb [create|add|docs|search|rm|reindex]
|
||||
knowledge bases the agent can search (lembas kb help)
|
||||
lembas uninstall [--purge] [--yes]
|
||||
@@ -105,7 +107,8 @@ Local mode:
|
||||
start asks, and the answer is kept in the local directory.
|
||||
|
||||
Options for run:
|
||||
-m, --model conn/model model to use (default: the project's \`model\`, else the one last used in
|
||||
-m, --model ID a model the server serves, by its id — lembas models lists them
|
||||
(default: the project's \`model\`, else the one last used in
|
||||
this directory, else config.yaml \`model\`). With no terminal at
|
||||
all (cron, a pipeline) a model for interactive use only is refused:
|
||||
run it at a terminal (ssh -t), or name another model
|
||||
@@ -117,7 +120,7 @@ Options for run:
|
||||
--no-store do not record the session
|
||||
--no-wait do not wait for background jobs the prompt started; stop them
|
||||
|
||||
In a LLeMbas terminal (LLEMBAS_TTY set), for the TUI and for run:
|
||||
In a LLeMbas terminal (LLEMBAS_TERM set), for the TUI and for run:
|
||||
--terminal-context FILE
|
||||
what the terminal showed (a file it wrote; read once and removed),
|
||||
attached to your next message; in the TUI also /terminal-context FILE
|
||||
@@ -167,9 +170,9 @@ async function loginCommand(cmd: "login" | "logout", args: string[]) {
|
||||
}
|
||||
if (cmd === "logout") {
|
||||
const name = positionals[0] ?? (Object.keys(known).length === 1 ? Object.keys(known)[0]! : "")
|
||||
if (!name) fail(Object.keys(known).length ? `which one? lembas logout <${Object.keys(known).join("|")}>` : "not logged in to any instance", 2)
|
||||
if (!name) fail(Object.keys(known).length ? `which one? lembas logout <${Object.keys(known).join("|")}>` : "not logged in to a LLeMbas server", 2)
|
||||
const r = await logout(name)
|
||||
console.log(`Signed out of ${name}${r.revoked ? "" : " here (the instance could not be told — revoke it under User → Security → Devices there)"}; its connection is removed.`)
|
||||
console.log(`Signed out of ${name}${r.revoked ? "" : " here (the server could not be told — revoke it under User → Security → Devices there)"}; its sign-in is removed here.`)
|
||||
if (r.modelLeft) console.log(`config.yaml still starts on ${r.modelLeft}: choose another with lembas config set model <id>.`)
|
||||
return
|
||||
}
|
||||
@@ -187,7 +190,7 @@ async function loginCommand(cmd: "login" | "logout", args: string[]) {
|
||||
// and "run login again" would send the person straight back here. Sign in afresh instead;
|
||||
// the new login replaces the old one.
|
||||
if (!(e instanceof SignInRejected)) throw e
|
||||
if (!json) console.error("The instance no longer accepts the sign-in kept here: signing in again.")
|
||||
if (!json) console.error("The LLeMbas server no longer accepts the sign-in kept here: signing in again.")
|
||||
address = again.base_url
|
||||
}
|
||||
}
|
||||
@@ -195,8 +198,8 @@ async function loginCommand(cmd: "login" | "logout", args: string[]) {
|
||||
// again, at the address it had.
|
||||
if (again && !address) address = again.base_url
|
||||
if (!address) {
|
||||
if (!process.stdin.isTTY || json) fail("usage: lembas login <instance address>", 2)
|
||||
process.stdout.write("LLeMbas instance address: ")
|
||||
if (!process.stdin.isTTY || json) fail("usage: lembas login <server address>", 2)
|
||||
process.stdout.write("LLeMbas server address: ")
|
||||
for await (const line of console) {
|
||||
address = line.trim()
|
||||
break
|
||||
@@ -361,7 +364,7 @@ async function main() {
|
||||
}
|
||||
process.exit(remoteCommand(["scheduled", ...argv.slice(2)]))
|
||||
}
|
||||
fail("usage: lembas service install | uninstall | status | logs [-f] | run [connection] | scheduled [on|off]", 2)
|
||||
fail("usage: lembas service install | uninstall | status | logs [-f] | run [name] | scheduled [on|off]", 2)
|
||||
}
|
||||
|
||||
if (cmd === "run") {
|
||||
@@ -419,12 +422,26 @@ async function main() {
|
||||
}
|
||||
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())
|
||||
// One way out (shutdown.ts): the first Ctrl+C stops the turn and the wait for background
|
||||
// jobs — the run then ends by itself, 130; a second one, or SIGTERM/SIGHUP, ends it now.
|
||||
// Either way nothing the run started is left behind.
|
||||
const interrupted = new AbortController()
|
||||
const { onSignals } = await import("./shutdown.ts")
|
||||
onSignals({
|
||||
gentle: () => {
|
||||
interrupted.abort()
|
||||
app.engine.cancel()
|
||||
},
|
||||
last: (left) => {
|
||||
if (left) process.stderr.write(`lembas: stopping ${left} command${left === 1 ? "" : "s"} still running\n`)
|
||||
},
|
||||
})
|
||||
// The transcript's one line for it, not the content.
|
||||
if (shown && app.terminal) app.bus.emit({ type: "notice", level: "info", message: app.terminal.accept(shown.context) })
|
||||
// One prompt, so the MCP servers' tools must be there before it (each server has its own
|
||||
// connect timeout; a failure is a notice, not a stop).
|
||||
await app.mcpReady
|
||||
await Promise.race([app.mcpReady, new Promise((r) => interrupted.signal.addEventListener("abort", r, { once: true }))])
|
||||
if (interrupted.signal.aborted) process.exit(130)
|
||||
// A command that only says something (/mcp, /agents, /team — what the TUI shows as a menu):
|
||||
// its text, and no model is asked.
|
||||
// /reports reads the server, so it is answered here rather than among the commands that only
|
||||
@@ -465,11 +482,13 @@ async function main() {
|
||||
// Through the turns, like every front end: a job's note wakes the session the same way.
|
||||
const reason = await app.turns.prompt(prompt, atts.flatMap((a) => (a.image ? [a.text, a.image] : [a.text])))
|
||||
// Jobs the prompt started: their notes come back as turns of their own, unless told not to wait.
|
||||
await settleJobs(app, !values["no-wait"])
|
||||
// Not after a prompt that failed or was stopped: the jobs' notes would start turns that fail
|
||||
// the same way, or that nobody asked for, and a job that never ends would hold the run for ever.
|
||||
await settleJobs(app, !values["no-wait"] && reason !== "error" && reason !== "cancelled" && !interrupted.signal.aborted, { stop: interrupted.signal, say: (t) => process.stderr.write(`lembas: ${t}\n`) })
|
||||
// Refused before the prompt was written (capacity, a cancel at once): no empty session is left
|
||||
// to crowd `lembas sessions`. Never shared, so nobody else is told.
|
||||
app.discardIfEmpty()
|
||||
process.exit(reason === "stop" ? 0 : reason === "steps" || reason === "budget" ? 3 : reason === "cancelled" ? 130 : 1)
|
||||
process.exit(interrupted.signal.aborted ? 130 : reason === "stop" ? 0 : reason === "steps" || reason === "budget" ? 3 : reason === "cancelled" ? 130 : 1)
|
||||
}
|
||||
|
||||
if (cmd === "models") {
|
||||
@@ -736,7 +755,7 @@ async function main() {
|
||||
}
|
||||
|
||||
if (cmd === "update") {
|
||||
const { autoUpdate, check, install, installTag, lock, rollback, installedBinary } = await import("./update/index.ts")
|
||||
const { check, hold, heldVersion, install, installTag, lock, rollback, installedBinary } = await import("./update/index.ts")
|
||||
const { values, positionals } = parseArgs({
|
||||
args: argv.slice(1),
|
||||
allowPositionals: true,
|
||||
@@ -747,24 +766,52 @@ async function main() {
|
||||
const unlock = lock()
|
||||
if (!unlock) fail("another LLeMbas CLI is updating right now; try again in a minute")
|
||||
process.on("exit", () => unlock())
|
||||
if (values.rollback) {
|
||||
const v = rollback()
|
||||
console.log(`rolled back to ${v} (run it again to undo)`)
|
||||
// An update that fails for an ordinary reason (no network, nothing kept to roll back to) is said
|
||||
// in one line, never as a program's stack.
|
||||
const PAUSED = "Automatic updates are paused until you run lembas update."
|
||||
try {
|
||||
if (values.rollback) {
|
||||
const v = rollback()
|
||||
hold(v)
|
||||
console.log(`rolled back to ${v} (--rollback again goes back). ${PAUSED}`)
|
||||
return
|
||||
}
|
||||
const config = { ...loadConfig().config.update, ...(values.channel ? { channel: values.channel as "stable" | "beta" } : {}) }
|
||||
const later = (major?: string) => (major ? `\n${major} is out: a new major version is installed only when you name it — lembas update v${major}` : "")
|
||||
const say = (r: Awaited<ReturnType<typeof install>>) => {
|
||||
if (r.kind === "installed") console.log(`updated ${r.previous} → ${r.version} (${installedBinary()}); restart lembas, or /reload in a running one`)
|
||||
else if (r.kind === "current") console.log(`${r.version} is the newest ${config.channel ?? "stable"} release of its major version${later(r.major)}`)
|
||||
else if (r.kind === "available") console.log(`${r.version} is out — lembas update installs it${later(r.major)}`)
|
||||
else if (r.kind === "skipped") console.log(r.reason)
|
||||
else fail(r.reason)
|
||||
}
|
||||
if (positionals[0]) {
|
||||
const r = await installTag(positionals[0], { config })
|
||||
if (r.kind === "installed") {
|
||||
hold(r.version)
|
||||
say(r)
|
||||
console.log(`${PAUSED} (It stays on ${r.version}.)`)
|
||||
return
|
||||
}
|
||||
return say(r)
|
||||
}
|
||||
const found = await check({ config })
|
||||
if (values.check) {
|
||||
const held = heldVersion()
|
||||
if (held) console.log(`held at ${held}, which you chose. ${PAUSED}`)
|
||||
if ("kind" in found) return say(found)
|
||||
return say({ kind: "available", version: found.release.tag.replace(/^v/, ""), ...(found.major ? { major: found.major } : {}) })
|
||||
}
|
||||
// Run by hand: whatever was held is let go of, and automatic updates go on.
|
||||
hold(undefined)
|
||||
if ("kind" in found) return say(found)
|
||||
const r = await install(found.release, found.version, { config })
|
||||
say(r)
|
||||
if (found.major) console.log(later(found.major).trim())
|
||||
return
|
||||
} catch (e) {
|
||||
fail((e as Error).message)
|
||||
}
|
||||
const config = { ...loadConfig().config.update, ...(values.channel ? { channel: values.channel as "stable" | "beta" } : {}) }
|
||||
const say = (r: Awaited<ReturnType<typeof autoUpdate>>) => {
|
||||
if (r.kind === "installed") console.log(`updated ${r.previous} → ${r.version} (${installedBinary()}); restart lembas, or /reload in a running one`)
|
||||
else if (r.kind === "current") console.log(`${r.version} is the newest ${config.channel ?? "stable"} release`)
|
||||
else if (r.kind === "available") console.log(`${r.version} is out — lembas update installs it`)
|
||||
else if (r.kind === "skipped") console.log(r.reason)
|
||||
else fail(r.reason)
|
||||
}
|
||||
if (positionals[0]) return say(await installTag(positionals[0], { config }))
|
||||
const found = await check({ config })
|
||||
if ("kind" in found) return say(found)
|
||||
if (values.check) return say({ kind: "available", version: found.release.tag.replace(/^v/, "") })
|
||||
return say(await install(found.release, found.version, { config }))
|
||||
}
|
||||
|
||||
if (cmd === "kb") {
|
||||
|
||||
+16
-11
@@ -1,8 +1,10 @@
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
|
||||
import { match as wildcardMatch } from "../permission/wildcard.ts"
|
||||
import { MODE_RANK } from "../permission/modes.ts"
|
||||
import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { isScalar, parse, parseDocument } from "yaml"
|
||||
import { z } from "zod"
|
||||
import { connectionFiles, isLocal, paths } from "./paths.ts"
|
||||
import { connectionFiles, isLocal, ownDir, paths } from "./paths.ts"
|
||||
import { asMode, Config, McpServer, PERSONALITIES, renamePermissionKeys, WebuiConnection, type Connection, type PermissionConfig } from "./schema.ts"
|
||||
import { substituteDeep } from "./substitute.ts"
|
||||
import { expandWebui, refreshFailures, type WebuiMark } from "../lembas/webui.ts"
|
||||
@@ -56,7 +58,6 @@ function validate<S extends z.ZodType>(schema: S, value: unknown, file: string):
|
||||
|
||||
/** config.yaml: everything substituted except `mcp` and `voice`, whose parts are substituted one
|
||||
* by one later (a missing variable for one server or endpoint must not break the whole file). */
|
||||
const MODE_RANK = { auto: 0, edit: 1, manual: 2, plan: 3 } as const
|
||||
|
||||
/** A project's change to a global server, kept only where it narrows: off, fewer tools, less in
|
||||
* the prompt, shorter waits. It never turns on what the user turned off. */
|
||||
@@ -235,9 +236,13 @@ export function loadConfig(opts: { projectConfigDir?: string; trusted?: boolean
|
||||
for (const at of placeholders) warnings.push(`${projectFile}: ${at} uses {env:} or {file:}, which only the global config may; ignored`)
|
||||
files.push(projectFile)
|
||||
// The settings tool's gate is global-only (settings_tool); a project rule for it would open it.
|
||||
if (project.permission && "settings" in project.permission) {
|
||||
delete project.permission.settings
|
||||
warnings.push(`${projectFile}: permission.settings is honoured only in the global config (settings_tool); ignored`)
|
||||
// By any key that names it: `settings`, or a pattern that matches the name (`sett*`). A key
|
||||
// that takes in every tool (`*`) stays, and is simply not read for this one
|
||||
// (permission/evaluate.ts, defaults.json `user_only`).
|
||||
for (const key of Object.keys(project.permission ?? {})) {
|
||||
if (key === "*" || !wildcardMatch("settings", key)) continue
|
||||
delete project.permission![key]
|
||||
warnings.push(`${projectFile}: permission.${key} names the settings tool, whose rules are honoured only in the global config (settings_tool); ignored`)
|
||||
}
|
||||
if (project.permission) permissions.push(project.permission), permissionSources.push("project")
|
||||
// A project may make the starting mode stricter than the user's, never looser.
|
||||
@@ -324,10 +329,10 @@ export function loadConfig(opts: { projectConfigDir?: string; trusted?: boolean
|
||||
/** The server a voice half or the search goes through: the login (`connection:` may still name
|
||||
* it). A string says why there is none. */
|
||||
const webuiFor = (named?: string): { name: string; c: Loaded["connections"][string] } | string => {
|
||||
if (named) return connections[named]?.webui ? { name: named, c: connections[named]! } : broken[named] ? `${named} is unusable: ${broken[named]}` : `there is no webui connection named ${named}`
|
||||
if (named) return connections[named]?.webui ? { name: named, c: connections[named]! } : broken[named] ? `${named} is unusable: ${broken[named]}` : `there is no sign-in named ${named}`
|
||||
const all = Object.entries(connections).filter(([, c]) => c.webui)
|
||||
if (all.length === 1) return { name: all[0]![0], c: all[0]![1] }
|
||||
return all.length ? `there are several webui connections (${all.map(([n]) => n).join(", ")}); name one with connection:` : "there is no webui connection (lembas login)"
|
||||
return all.length ? `there are several sign-ins (${all.map(([n]) => n).join(", ")}); name one with connection:` : "not signed in to a LLeMbas server (lembas login)"
|
||||
}
|
||||
|
||||
const mcp: Loaded["mcp"] = {}
|
||||
@@ -465,7 +470,7 @@ function migrateRef(file: string, key: string, old: string, now: string) {
|
||||
}
|
||||
}
|
||||
done[id] = now
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
writeFileSync(record, JSON.stringify(done, null, 2) + "\n")
|
||||
} catch {}
|
||||
}
|
||||
@@ -475,7 +480,7 @@ function localOnly(config: Config, connections: Loaded["connections"], warnings:
|
||||
const out = { ...config }
|
||||
if (out.search) {
|
||||
const sr = { ...out.search }
|
||||
if (sr.order?.includes("webui") || sr.webui || sr.fetch === "webui") warnings.push("local mode: web search and fetch do not go through the LLeMbas instance")
|
||||
if (sr.order?.includes("webui") || sr.webui || sr.fetch === "webui") warnings.push("local mode: web search and fetch do not go through the LLeMbas server")
|
||||
if (sr.order) sr.order = sr.order.filter((p) => p !== "webui")
|
||||
delete sr.webui
|
||||
if (sr.fetch === "webui") sr.fetch = "local"
|
||||
@@ -485,7 +490,7 @@ function localOnly(config: Config, connections: Loaded["connections"], warnings:
|
||||
out.library = "local"
|
||||
const emb = out.embedding?.split("/")[0]
|
||||
if (out.embedding && emb && connections[emb]?.webui) {
|
||||
warnings.push(`local mode: embedding ${out.embedding} would go through the LLeMbas instance; the library is searched by words only`)
|
||||
warnings.push(`local mode: embedding ${out.embedding} would go through the LLeMbas server; the library is searched by words only`)
|
||||
delete out.embedding
|
||||
}
|
||||
if (out.hardline_disable?.length) {
|
||||
|
||||
+25
-1
@@ -1,4 +1,4 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync } from "node:fs"
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync } from "node:fs"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { isAbsolute, join } from "node:path"
|
||||
|
||||
@@ -59,6 +59,30 @@ export const paths = {
|
||||
},
|
||||
}
|
||||
|
||||
/** One of LLeMbas CLI's own data or state directories: made 0700, and tightened to 0700 when it
|
||||
* already exists with a looser mode (whichever writer came first used to decide, and sessions.db
|
||||
* was readable by every local user). Returns the directory. */
|
||||
export function ownDir(p: string): string {
|
||||
mkdirSync(p, { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
chmodSync(p, 0o700)
|
||||
} catch {}
|
||||
return p
|
||||
}
|
||||
|
||||
/** A file of the person's that holds what they wrote or were told (a database, a history): 0600,
|
||||
* existing files included. Missing is fine. */
|
||||
export function ownFile(f: string) {
|
||||
try {
|
||||
chmodSync(f, 0o600)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** The CLI's own directories: its configuration, data and state — the user's, and local mode's. */
|
||||
export function ownDirs(): string[] {
|
||||
return [...new Set([paths.config, paths.data, paths.state, globalPaths.config, globalPaths.data, globalPaths.state])]
|
||||
}
|
||||
|
||||
export function expandHome(p: string): string {
|
||||
if (p === "~") return homedir()
|
||||
if (p.startsWith("~/")) return join(homedir(), p.slice(2))
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// machine over the link. A running service asks for it whenever it decides something (a session
|
||||
// opened, a directory listed, a terminal shared), so `lembas remote …` or an edit of config.yaml
|
||||
// applies without a restart. The file is parsed again only when its mtime or size changed.
|
||||
import { within } from "../within.ts"
|
||||
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
|
||||
import { isAbsolute, join, relative, resolve } from "node:path"
|
||||
import { parse } from "yaml"
|
||||
@@ -93,8 +94,7 @@ export function realOrResolved(p: string): string {
|
||||
export function coveredBy(dir: string, roots: string[]): string | undefined {
|
||||
const target = realOrResolved(dir)
|
||||
return roots.find((r) => {
|
||||
const rel = relative(realOrResolved(r), target)
|
||||
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))
|
||||
return within(target, realOrResolved(r))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -100,7 +100,7 @@ export interface Connection {
|
||||
* their settings, and — where config.yaml says `provider: webui` — the voice and the web search come
|
||||
* from the instance at every start. `lembas login` writes it. */
|
||||
export const WebuiConnection = z.strictObject({
|
||||
type: z.literal("webui").describe("A LLeMbas instance: its models, their settings, its voice and its web search."),
|
||||
type: z.literal("webui").describe("A LLeMbas server: its models, their settings, its voice and its web search."),
|
||||
url: Url.describe("The instance's address, e.g. https://ai.example.org (no /v1)."),
|
||||
api_key: z.string().optional().describe("This machine's token, as login wrote it: {file:~/.config/lembas/lembas/<name>.key}."),
|
||||
tls: Tls.optional().describe("For an instance behind a private CA: `ca`, the PEM file that signed its certificate."),
|
||||
@@ -139,11 +139,11 @@ const VoiceEndpoint = {
|
||||
/** `provider: webui`: through a LLeMbas instance's own speech servers, with the account's
|
||||
* voice, speed and language. */
|
||||
const WebuiVoice = {
|
||||
connection: z.string().optional().describe("webui: which webui connection (default: the only one there is)."),
|
||||
connection: z.string().optional().describe("webui: which sign-in (default: the only one there is)."),
|
||||
}
|
||||
|
||||
const SttEndpoint = z.strictObject({
|
||||
provider: z.enum(["openai", "whispercpp", "webui"]).optional().describe("openai: POST {base_url}/audio/transcriptions (OpenAI, whisper.cpp's server with its OpenAI path, faster-whisper servers). whispercpp: POST {base_url}/inference (whisper.cpp's own). webui: the LLeMbas instance's."),
|
||||
provider: z.enum(["openai", "whispercpp", "webui"]).optional().describe("openai: POST {base_url}/audio/transcriptions (OpenAI, whisper.cpp's server with its OpenAI path, faster-whisper servers). whispercpp: POST {base_url}/inference (whisper.cpp's own). webui: the LLeMbas server's."),
|
||||
...VoiceEndpoint,
|
||||
...WebuiVoice,
|
||||
model: z.string().optional(),
|
||||
@@ -152,7 +152,7 @@ const SttEndpoint = z.strictObject({
|
||||
})
|
||||
|
||||
const TtsEndpoint = z.strictObject({
|
||||
provider: z.enum(["openai", "piper-http", "piper-cli", "webui"]).optional().describe("openai: POST {base_url}/audio/speech (OpenAI, Kokoro-FastAPI). piper-http: POST {base_url} with {text} (piper's http_server). piper-cli: the piper program. webui: the LLeMbas instance's, in the account's voice."),
|
||||
provider: z.enum(["openai", "piper-http", "piper-cli", "webui"]).optional().describe("openai: POST {base_url}/audio/speech (OpenAI, Kokoro-FastAPI). piper-http: POST {base_url} with {text} (piper's http_server). piper-cli: the piper program. webui: the LLeMbas server's, in the account's voice."),
|
||||
...VoiceEndpoint,
|
||||
...WebuiVoice,
|
||||
model: z.string().optional(),
|
||||
@@ -220,7 +220,7 @@ export const Update = z.strictObject({
|
||||
source: z
|
||||
.strictObject({
|
||||
type: z.enum(["github", "gitea", "static"]).describe("github or gitea (Forgejo too): their releases API. static: any web directory with files `stable` and `beta` naming a tag, and the assets under <tag>/."),
|
||||
url: Url.optional().describe("gitea: the forge (https://git.example.org). github: the API (default https://api.github.com). static: the directory."),
|
||||
url: Url.optional().describe("gitea: the address of the Gitea server (https://git.example.org). github: the API (default https://api.github.com). static: the directory."),
|
||||
repo: z.string().regex(/^(?!\.\.?\/)[\w.-]+\/(?!\.\.?$)[\w.-]+$/).optional().describe("owner/name, for github and gitea."),
|
||||
token: z.string().optional().describe("For a private repository: {env:NAME} or {file:~/path}, never pasted. Or key_cmd."),
|
||||
key_cmd: z.string().optional(),
|
||||
@@ -290,13 +290,13 @@ export const Config = z.strictObject({
|
||||
instruction_files: z.array(z.string()).optional().describe("More instruction files for the system prompt, besides AGENTS.md / CLAUDE.md."),
|
||||
search: z
|
||||
.strictObject({
|
||||
order: z.array(z.enum(["webui", "searxng", "firecrawl", "ddg"])).optional().describe("Providers to try, in order; the first that answers wins. Default: those configured (webui first), then ddg. webui: the LLeMbas instance's own search."),
|
||||
order: z.array(z.enum(["webui", "searxng", "firecrawl", "ddg"])).optional().describe("Providers to try, in order; the first that answers wins. Default: those configured (webui first), then ddg. webui: the LLeMbas server's own search."),
|
||||
max_results: z.number().int().min(1).max(30).optional().describe("Results per search (default 8)."),
|
||||
searxng: z.strictObject({ base_url: Url, api_key: z.string().optional(), tls: Tls.optional(), categories: z.string().optional(), language: z.string().optional() }).optional(),
|
||||
firecrawl: z.strictObject({ base_url: Url.optional(), api_key: z.string().optional(), tls: Tls.optional() }).optional().describe("API (api.firecrawl.dev, with a key) or self-hosted (its own URL, no key needed)."),
|
||||
ddg: z.strictObject({ region: z.string().optional(), safe: z.enum(["strict", "moderate", "off"]).optional() }).optional(),
|
||||
webui: z.strictObject({ connection: z.string().optional().describe("Which webui connection (default: the only one there is).") }).optional().describe("Search through a LLeMbas instance: its provider, its settings, its keys."),
|
||||
fetch: z.enum(["local", "firecrawl", "webui"]).optional().describe("How web_fetch reads a page: here, through Firecrawl's scrape, or through the LLeMbas instance."),
|
||||
webui: z.strictObject({ connection: z.string().optional().describe("Which sign-in (default: the only one there is).") }).optional().describe("Search through the LLeMbas server: its provider, its settings, its keys."),
|
||||
fetch: z.enum(["local", "firecrawl", "webui"]).optional().describe("How web_fetch reads a page: here, through Firecrawl's scrape, or through the LLeMbas server."),
|
||||
})
|
||||
.optional(),
|
||||
voice: Voice.optional().describe("Voice in and out. Global only — it carries endpoints and keys, like a connection."),
|
||||
@@ -318,17 +318,17 @@ export const Config = z.strictObject({
|
||||
library: z.enum(["local", "lembas"]).optional().describe("Global config only. Where memory lives. lembas (the default when the login may reach it): the account's memory records on the LLeMbas server, through its /mcp — the same records its chats have. local: this machine's memory files. Notes, knowledge bases and skills are this machine's either way."),
|
||||
remote: z
|
||||
.strictObject({
|
||||
enabled: z.boolean().optional().describe("Accept work from a LLeMbas instance this machine is logged in to (lembas service). Default false."),
|
||||
enabled: z.boolean().optional().describe("Accept work from the LLeMbas server this machine is signed in to (lembas service). Default false."),
|
||||
roots: z.array(z.string()).optional().describe("The directories a remote session may be opened in, and anything under them. Empty: none."),
|
||||
max_mode: z.enum(MODES).optional().describe("The most permissive mode a remote session may run in (default edit). auto only when set here."),
|
||||
approval_timeout: z.number().int().positive().optional().describe("Seconds an approval waits for an answer from the web before it counts as a denial (default 600)."),
|
||||
require_trust: z.boolean().optional().describe("Only projects trusted on this machine (default true)."),
|
||||
terminal: z.boolean().optional().describe("Let the web UI open a terminal here (LLeMbas's terminal panel on a chat on this device): a login shell as this user, in a directory remote sessions may use. Default false."),
|
||||
scheduled: z.boolean().optional().describe("Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas instance run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off."),
|
||||
scheduled: z.boolean().optional().describe("Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas server run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off."),
|
||||
files_that_run_code: z.boolean().optional().describe("Let the file manager of the web UI and the apps change files that run code here (harness acp.md, spec 3.11.0): git's hooks and configuration, a project's agent configuration, your shell's start-up files. Default false: they can be read from there, and are changed only on this machine."),
|
||||
terminal_integration: z.boolean().optional().describe("Shell integration in those terminals (bash, zsh, fish): after your own startup files, the shell marks each prompt, command and exit status (OSC 133) and its directory (OSC 7), so the web UI shows the directory, a mark beside each finished command, and can jump between commands. false: the shell starts as it is. Default true."),
|
||||
})
|
||||
.optional()
|
||||
.describe("Global config only. What a LLeMbas instance may ask of this machine over the link: the device decides, never the server."),
|
||||
.describe("Global config only. What the LLeMbas server may ask of this machine over the link: the device decides, never the server."),
|
||||
})
|
||||
export type Config = z.infer<typeof Config>
|
||||
+1
-1
@@ -315,7 +315,7 @@ export const LOOP: {
|
||||
search_max: number
|
||||
upload_max_bytes: number
|
||||
indexes_max: number
|
||||
runs_code: { segments: string[]; project_dir: string; project: string[]; home: string[] }
|
||||
runs_code: { segments: string[]; project_dirs: string[]; project: string[]; home: string[] }
|
||||
show: { text_max_bytes: number; media_max_bytes: number; media_wait_seconds: number }
|
||||
}
|
||||
/** A terminal as the client (spec 3.12.0, harness/acp.md): the environment, the user vars, the
|
||||
|
||||
+11
-3
@@ -125,12 +125,20 @@ export function renderJson(bus: Bus) {
|
||||
/** After the prompt: wait for the jobs it started — their notes start turns of their own, which may
|
||||
* start more — then stop whatever still runs (the spec's lifecycle: nobody is there to ask).
|
||||
* `wait: false` (--no-wait) stops them at once. */
|
||||
export async function settleJobs(app: import("./app.ts").App, wait: boolean): Promise<void> {
|
||||
export async function settleJobs(app: import("./app.ts").App, wait: boolean, o: { stop?: AbortSignal; say?: (text: string) => void } = {}): Promise<void> {
|
||||
const sid = app.jobsSessionId()
|
||||
if (wait) while (app.turns.current || app.registry.running(sid).length) await Bun.sleep(200)
|
||||
if (wait) while (!o.stop?.aborted && (app.turns.current || app.registry.running(sid).length)) await Bun.sleep(200)
|
||||
// Interrupted while a job's own turn runs: that turn is stopped too.
|
||||
if (o.stop?.aborted && app.turns.current) app.engine.cancel()
|
||||
// Quietly: a note about a job stopped on the way out would only start a turn nobody reads.
|
||||
const running = app.registry.running(sid)
|
||||
if (running.length && o.stop?.aborted) o.say?.(`stopping ${running.length} background job${running.length === 1 ? "" : "s"}: ${running.map((j) => `${j.id} (${j.description})`).join(", ")}`)
|
||||
const left = app.registry.stopAll(sid, true)
|
||||
if (left) await Bun.sleep(100)
|
||||
if (!left) return
|
||||
// TERM was sent; what does not take it within the grace is killed as the program leaves
|
||||
// (shutdown.ts) — the wait here is only for the common case, so the exit is clean.
|
||||
const until = Date.now() + 2500
|
||||
while (Date.now() < until && app.registry.running(sid).length) await Bun.sleep(50)
|
||||
}
|
||||
|
||||
/** Asks on the terminal when there is one; otherwise follows --yes, or refuses. One question at a
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// decides whether the note goes in mid-turn or starts a turn of its own; a session nobody has open
|
||||
// keeps the note on its row until it is resumed. Processes die with this one: on exit every group
|
||||
// gets SIGTERM, then SIGKILL, synchronously — an unref'd timer never fires at exit.
|
||||
import { trackGroup } from "../shutdown.ts"
|
||||
import { spawn, type ChildProcess } from "node:child_process"
|
||||
import type { Bus } from "../bus/index.ts"
|
||||
import type { Engine } from "../session/engine.ts"
|
||||
@@ -277,6 +278,7 @@ export class JobRegistry {
|
||||
const max = this.runningMax(o.sessionId)
|
||||
if (commands.length >= max) throw new Error(`This session already has ${commands.length} background command${commands.length === 1 ? "" : "s"} running (limits.jobs: ${max}). Stop one with job_stop, or wait for one to end.`)
|
||||
const child = spawn("bash", ["-c", `exec 2>&1\n${o.command}`], { cwd: o.cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], env: o.env })
|
||||
trackGroup(child.pid)
|
||||
return this.adopt({ ...o, child, output: "", read: 0, started: Date.now() })
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -155,7 +155,7 @@ export function writeConnection(connection: string, d: Discovery, tls: Tls | und
|
||||
doc.setIn(["connections", connection], doc.createNode(entry))
|
||||
const node = doc.getIn(["connections", connection], true) as { commentBefore?: string } | undefined
|
||||
if (node)
|
||||
node.commentBefore = ` ${d.name ?? "LLeMbas"} at ${base}, written by \`lembas login\`. Its models and their settings come from the instance at every start; \`lembas logout ${connection}\` removes it.`
|
||||
node.commentBefore = ` ${d.name ?? "LLeMbas"} at ${base}, written by \`lembas login\`. Its models and their settings come from the server at every start; \`lembas logout ${connection}\` removes it.`
|
||||
writeYamlDoc(connectionsFile(), doc, 0o600)
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ function replaceOld(old: string, now: string, instanceDefault: string | undefine
|
||||
if (typeof model === "string" && model.startsWith(`${old}/`)) {
|
||||
if (instanceDefault && model === `${old}/${instanceDefault}`) {
|
||||
cfg.delete("model")
|
||||
said.push(`config.yaml no longer pins ${model}: sessions start on the instance's default`)
|
||||
said.push(`config.yaml no longer pins ${model}: sessions start on the server's default`)
|
||||
} else {
|
||||
cfg.set("model", renamed(model, old, now))
|
||||
said.push(`config.yaml starts on ${renamed(model, old, now)}`)
|
||||
@@ -401,12 +401,12 @@ export function loginSummary(r: LoginResult, fresh: boolean): string[] {
|
||||
const out: string[] = []
|
||||
const who = r.instance.email ? ` as ${r.instance.email}` : ""
|
||||
const label = r.instance.instance_name ? `${r.instance.instance_name} (${r.instance.base_url})` : r.instance.base_url
|
||||
out.push(fresh ? `Signed in to ${label}${who}. Connection ${r.connection}: ${r.models.length} model${r.models.length === 1 ? "" : "s"}, read from the instance at every start.` : `${r.connection}: ${r.models.length} model${r.models.length === 1 ? "" : "s"} from ${label} (LLeMbas ${r.version}).`)
|
||||
out.push(fresh ? `Signed in to ${label}${who} as ${r.connection}: ${r.models.length} model${r.models.length === 1 ? "" : "s"}, read from the server at every start.` : `${r.connection}: ${r.models.length} model${r.models.length === 1 ? "" : "s"} from ${label} (LLeMbas ${r.version}).`)
|
||||
const refOf = (id: string) => r.refs?.[id] ?? `${r.connection}/${id}`
|
||||
for (const m of r.models) out.push(` ${refOf(m.id)}${m.context ? ` ${Math.round(m.context / 1024)}k` : ""}${m.id === r.instanceDefault ? " (the instance's default)" : ""}`)
|
||||
for (const m of r.models) out.push(` ${refOf(m.id)}${m.context ? ` ${Math.round(m.context / 1024)}k` : ""}${m.id === r.instanceDefault ? " (the server's default)" : ""}`)
|
||||
const model = currentModel()
|
||||
if (r.defaultSet) out.push(`Sessions start on ${r.defaultSet}.`)
|
||||
else if (!model && r.instanceDefault) out.push(`Sessions start on the instance's default, ${refOf(r.instanceDefault)}.`)
|
||||
else if (!model && r.instanceDefault) out.push(`Sessions start on the server's default, ${refOf(r.instanceDefault)}.`)
|
||||
else if (model) out.push(`Sessions start on ${model} (config.yaml).`)
|
||||
for (const c of r.changes) out.push(`· ${c}`)
|
||||
if (r.instance.ca) out.push(`TLS: trusting ${r.instance.ca} for this connection.`)
|
||||
@@ -477,7 +477,7 @@ async function store(discovery: Discovery, tls: Tls | undefined, granted: Grante
|
||||
if (!old?.token || old.token === granted.access_token) return
|
||||
const here = sameServer(old.at, base)
|
||||
const done = here ? await signOut(base, old.token, tls, granted.access_token) : await signOut(old.at, old.token, tls)
|
||||
if (!done) changes.push("the previous login could not be signed out: revoke it under User → Security → Devices on the instance")
|
||||
if (!done) changes.push("the previous login could not be signed out: revoke it under User → Security → Devices on the server")
|
||||
}
|
||||
await handOver(replaced)
|
||||
// One server at a time (2.0: the CLI is LLeMbas-server-specific): a login to another one signs
|
||||
|
||||
@@ -64,7 +64,7 @@ export function withInstancePersonalization(config: Config): { config: Config; c
|
||||
export async function pushPersonalization(key: (typeof PERSONAL_KEYS)[number], value: string): Promise<Personalization | undefined> {
|
||||
if (isLocal()) throw new LembasError("local mode (-l) keeps settings in the project, not in the account")
|
||||
const one = soleInstance()
|
||||
if (!one) throw new LembasError("not logged in to one LLeMbas instance")
|
||||
if (!one) throw new LembasError("not signed in to a LLeMbas server (/login)")
|
||||
const saved = await savePersonalization(one.instance.base_url, one.token, one.instance.ca ? { ca: one.instance.ca } : undefined, { enabled: true, [key]: value })
|
||||
const cache = readCache(one.instance.connection)
|
||||
if (cache) writeCache(one.instance.connection, { ...cache, personalization: saved ?? { ...(cache.personalization ?? { personality: "", personality_custom: "", instructions: "", available: true }), [key]: value, enabled: true } })
|
||||
|
||||
@@ -63,7 +63,7 @@ export interface Compiled {
|
||||
/** One call to the schedule (and report) routes; the server's own refusal (`detail`) as the error. */
|
||||
export async function api(method: string, path: string, body?: unknown, what = "schedules"): Promise<any> {
|
||||
const one = soleInstance()
|
||||
if (!one) throw new LembasError("not logged in to one LLeMbas server (/login)")
|
||||
if (!one) throw new LembasError("not signed in to a LLeMbas server (/login)")
|
||||
const r = await apiCall(one.instance.base_url, one.token, one.instance.ca ? { ca: one.instance.ca } : undefined, method, `/api/v2${path}`, body)
|
||||
const detail = typeof r.json?.detail === "string" ? r.json.detail : undefined
|
||||
if (r.status === 401 && !detail) throw new SignInRejected("the server no longer accepts this sign-in — /login again")
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
// bases it searches (`knowledge:` in its config).
|
||||
import { Database } from "bun:sqlite"
|
||||
import { createHash } from "node:crypto"
|
||||
import { mkdirSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, ownFile, paths } from "../config/paths.ts"
|
||||
import { anyOf, ftsQuery } from "../tool/session_search.ts"
|
||||
import { split } from "./chunks.ts"
|
||||
|
||||
@@ -121,9 +120,10 @@ export class Library {
|
||||
readonly db: Database
|
||||
|
||||
constructor(file = join(paths.data, "library.db")) {
|
||||
mkdirSync(paths.data, { recursive: true })
|
||||
ownDir(paths.data)
|
||||
this.db = new Database(file, { create: true })
|
||||
this.db.run("PRAGMA journal_mode = WAL")
|
||||
for (const f of [file, `${file}-wal`, `${file}-shm`]) ownFile(f)
|
||||
this.db.run("PRAGMA foreign_keys = ON")
|
||||
this.db.exec(SCHEMA)
|
||||
}
|
||||
|
||||
+3
-3
@@ -4,11 +4,11 @@
|
||||
// ~/.local/share/lembas/mcp-auth.json (mode 600), keyed by server and checked against its URL,
|
||||
// and catches the redirect on 127.0.0.1. A sign-in's state and PKCE verifier stay in memory, with
|
||||
// the sign-in: another LLeMbas CLI connecting meanwhile must not replace them.
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from "node:fs"
|
||||
import { existsSync, readFileSync, renameSync, writeFileSync, chmodSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
|
||||
import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, paths } from "../config/paths.ts"
|
||||
import type { McpServer } from "../config/schema.ts"
|
||||
|
||||
export const CALLBACK_PORT = 19876
|
||||
@@ -35,7 +35,7 @@ function readAll(strict = false): Record<string, Entry> {
|
||||
}
|
||||
|
||||
function writeAll(all: Record<string, Entry>) {
|
||||
mkdirSync(paths.data, { recursive: true })
|
||||
ownDir(paths.data)
|
||||
const tmp = `${file()}.${process.pid}.tmp`
|
||||
writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 })
|
||||
chmodSync(tmp, 0o600)
|
||||
|
||||
@@ -5,7 +5,9 @@ export function prefix(tokens: string[]) {
|
||||
// Options before the subcommand do not count ("options never count", in the table's rules): `git -C dir
|
||||
// commit` is `git commit` — and an "always" for `git -C *` would cover every git command.
|
||||
if (tokens.length > 1 && tokens.slice(1).some((t) => t.startsWith("-")) && ARITY[tokens[0]!] !== undefined && ARITY[tokens[0]!]! > 1 && tokens[1]!.startsWith("-")) return tokens
|
||||
for (let len = tokens.length; len > 0; len--) {
|
||||
// No key of the table is longer than LONGEST words: nothing longer is ever joined (a command
|
||||
// of thirty thousand words was joined thirty thousand times here).
|
||||
for (let len = Math.min(tokens.length, LONGEST); len > 0; len--) {
|
||||
const prefix = tokens.slice(0, len).join(" ")
|
||||
const arity = ARITY[prefix]
|
||||
if (arity !== undefined) return tokens.slice(0, arity)
|
||||
@@ -19,3 +21,4 @@ export function prefix(tokens: string[]) {
|
||||
// the command, options never count, the longest matching prefix wins.
|
||||
const ARITY: Record<string, number> = SPEC.arity
|
||||
|
||||
const LONGEST = Math.max(1, ...Object.keys(ARITY).map((k) => k.split(" ").length))
|
||||
@@ -144,3 +144,62 @@ export function words(command: string): string[] {
|
||||
while (out.length > 1 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(out[0]!)) out.shift()
|
||||
return out
|
||||
}
|
||||
|
||||
/** A shell word with its quoting kept: `mask[i]` says how `text[i]` was written — `u` unquoted,
|
||||
* `d` inside double quotes (a `$` still expands there), `s` inside single quotes or after a
|
||||
* backslash (nothing expands). What `words` reads, for a reader that must know whether a `~`,
|
||||
* `$`, `{` or `>` is the shell's or the text's own. */
|
||||
export interface Word {
|
||||
text: string
|
||||
mask: string
|
||||
}
|
||||
|
||||
/** Every word of a simple command, quoting kept (leading VAR=value assignments included). */
|
||||
export function shellWords(command: string): Word[] {
|
||||
const out: Word[] = []
|
||||
let text = ""
|
||||
let mask = ""
|
||||
let quote: string | null = null
|
||||
let started = false
|
||||
const end = () => {
|
||||
if (started) out.push({ text, mask })
|
||||
text = ""
|
||||
mask = ""
|
||||
started = false
|
||||
}
|
||||
for (let i = 0; i < command.length; i++) {
|
||||
const ch = command[i]!
|
||||
if (quote) {
|
||||
if (ch === quote) quote = null
|
||||
// Inside double quotes a backslash makes the next of $ ` " \\ literal, and is text otherwise.
|
||||
else if (quote === '"' && ch === "\\" && i + 1 < command.length && '$`"\\'.includes(command[i + 1]!)) {
|
||||
text += command[++i]
|
||||
mask += "s"
|
||||
} else {
|
||||
text += ch
|
||||
mask += quote === "'" ? "s" : "d"
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (ch === "'" || ch === '"') {
|
||||
quote = ch
|
||||
started = true
|
||||
continue
|
||||
}
|
||||
if (ch === "\\" && i + 1 < command.length) {
|
||||
text += command[++i]
|
||||
mask += "s"
|
||||
started = true
|
||||
continue
|
||||
}
|
||||
if (/\s/.test(ch)) {
|
||||
end()
|
||||
continue
|
||||
}
|
||||
text += ch
|
||||
mask += "u"
|
||||
started = true
|
||||
}
|
||||
end()
|
||||
return out
|
||||
}
|
||||
+62
-84
@@ -1,5 +1,7 @@
|
||||
// Permission evaluation: rules (OpenCode's shape — last match wins), modes (LLeMbas CLI's four),
|
||||
// and the hardline floor (Hermes) underneath everything.
|
||||
import { projectRunsCode } from "../runs-code.ts"
|
||||
import { within } from "../within.ts"
|
||||
import { lstatSync, readlinkSync, realpathSync } from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { basename, dirname, join, relative, resolve } from "node:path"
|
||||
@@ -8,6 +10,7 @@ import { renamePermissionKeys, type Action, type Mode, type PermissionConfig } f
|
||||
import { prefix } from "./arity.ts"
|
||||
import { splitCommand, words } from "./bash.ts"
|
||||
import { hardlineCommand, plainCommands, protectedPath, type HardlineRule } from "./hardline.ts"
|
||||
import { MAX_COMMAND_BYTES, touched } from "./touch.ts"
|
||||
import { match } from "./wildcard.ts"
|
||||
import DEFAULTS from "../../harness/permission/defaults.json"
|
||||
import ARITY from "../../harness/permission/arity.json"
|
||||
@@ -55,11 +58,28 @@ export interface Decision {
|
||||
reason: string
|
||||
/** Suggested "always allow" patterns for this request. */
|
||||
always: string[]
|
||||
/** The paths outside the project that the call is asked about (`external_directory`): an
|
||||
* "always" answer makes a rule for each of them too (rules.md §3), or it would change nothing. */
|
||||
outside?: string[]
|
||||
}
|
||||
|
||||
/** The rules an "always" answer to `d` makes (permission/rules.md §3, spec 3.15.0): one per
|
||||
* offered pattern under the call's permission, and one `external_directory` rule per path outside
|
||||
* the project the call was asked about. `save`: whether it may be written to a project's
|
||||
* configuration — never for a path outside the project (a machine's paths are not the project's). */
|
||||
export function alwaysRules(req: Pick<PermissionRequest, "permission">, d: Decision): { rule: Rule; save: boolean }[] {
|
||||
const made = d.always.map((pattern) => ({ rule: { permission: req.permission, pattern, action: "allow" as const, learned: true }, save: true }))
|
||||
// Without a rule of its permission, an outside path stays asked whatever was remembered for the call.
|
||||
if (!made.length) return []
|
||||
for (const pattern of d.outside ?? []) made.push({ rule: { permission: "external_directory", pattern, action: "allow" as const, learned: true }, save: false })
|
||||
return made
|
||||
}
|
||||
|
||||
// The rules every session starts from: the harness spec's (harness/permission/defaults.json).
|
||||
// A key the spec still writes under a former name (defaults.json says `todo`) is read as the key
|
||||
// it is now, as a user's config is.
|
||||
const USER_ONLY = new Set<string>(DEFAULTS.user_only)
|
||||
|
||||
export const DEFAULT_RULES = renamePermissionKeys(DEFAULTS.rules) as PermissionConfig
|
||||
|
||||
export function toRules(config: PermissionConfig, source?: Rule["source"]): Rule[] {
|
||||
@@ -106,7 +126,11 @@ export function ruleAction(permission: string, pattern: string, rules: Rule[]):
|
||||
* answer (their config's last matching rule, of any breadth); and, for an "always" answer, a
|
||||
* written deny. A candidate from the defaults or the person's own config decides as it is. */
|
||||
function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule | undefined {
|
||||
const matches = (r: Rule) => match(permission, r.permission) && match(pattern, r.pattern)
|
||||
// A user-only permission (defaults.json `user_only`: the settings tool) is decided by the
|
||||
// defaults and the person's own config alone: no project's rule and none made in a session is
|
||||
// read for it, by whatever key it matches (`sett*`, `*`).
|
||||
const own = USER_ONLY.has(permission)
|
||||
const matches = (r: Rule) => !(own && (r.source === "project" || r.learned || r.source === undefined)) && match(permission, r.permission) && match(pattern, r.pattern)
|
||||
const hit = rules.findLast(matches)
|
||||
if (!hit || !(hit.source === "project" || hit.learned)) return hit
|
||||
// A narrower rule that a later one narrows again is set aside (spec 3.9.0): `read *.env.*: ask`
|
||||
@@ -114,8 +138,8 @@ function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule |
|
||||
const narrower = rules.filter((r) => r !== hit && !r.learned && matches(r) && narrowerThan(r, hit))
|
||||
// …or writes again: the same permission and pattern, later, is the rule as it stands now.
|
||||
const floors: Rule[] = narrower.filter((r, i) => !narrower.slice(i + 1).some((later) => narrowerThan(later, r) || (later.permission === r.permission && later.pattern === r.pattern)))
|
||||
const own = rules.findLast((r) => r.source === "global" && !r.learned && matches(r))
|
||||
if (own) floors.push(own)
|
||||
const mine = rules.findLast((r) => r.source === "global" && !r.learned && matches(r))
|
||||
if (mine) floors.push(mine)
|
||||
if (hit.learned) {
|
||||
const written = rules.findLast((r) => !r.learned && matches(r))
|
||||
if (written?.action === "deny") floors.push(written)
|
||||
@@ -157,9 +181,23 @@ export interface Context {
|
||||
planDir?: string
|
||||
/** The project directory (.agent): its config, agents, commands and skills are not edits. */
|
||||
projectDir?: string
|
||||
/** The branch checked out in a directory, for the floor's reading of a bare forced push
|
||||
* (default: asked of git). */
|
||||
branch?: (cwd: string) => string | undefined
|
||||
}
|
||||
|
||||
const inside = (p: string, dir: string) => p === dir || p.startsWith(dir.endsWith("/") ? dir : dir + "/")
|
||||
/** The branch checked out in `cwd`; undefined when there is none or git does not say. */
|
||||
export function currentBranch(cwd: string): string | undefined {
|
||||
try {
|
||||
const r = Bun.spawnSync(["git", "-C", cwd, "symbolic-ref", "--short", "-q", "HEAD"], { stdout: "pipe", stderr: "ignore", stdin: "ignore", timeout: 2000 })
|
||||
const out = r.exitCode === 0 ? r.stdout.toString().trim() : ""
|
||||
return out || undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const inside = within
|
||||
|
||||
/** A path as the filesystem will see it: symlinks in its longest existing part resolved. So a
|
||||
* link inside the project that points out of it is outside, and one to ~/.ssh is ~/.ssh. */
|
||||
@@ -186,83 +224,7 @@ export function realPath(p: string, depth = 0): string {
|
||||
/** Files edit mode does not change unasked: git's own (config and hooks run programs) and the
|
||||
* project's config, agents, commands and skills (they change what LLeMbas CLI itself does). */
|
||||
function guardedEdit(p: string, projectDir?: string): boolean {
|
||||
if (p.split("/").includes(".git")) return true
|
||||
if (!projectDir || !inside(p, projectDir)) return false
|
||||
const rel = relative(projectDir, p)
|
||||
return rel.endsWith("config.yaml") || /^(agents|commands|skills)(\/|$)/.test(rel)
|
||||
}
|
||||
|
||||
const DEVICES = /^\/dev\/(null|zero|stdin|stdout|stderr|tty|u?random)$/
|
||||
const PATTERN_FIRST = new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack"])
|
||||
|
||||
const MAX_GLOB = 500
|
||||
|
||||
/** What a glob names, as the shell would expand it — dotfiles included, to be safe. Undefined
|
||||
* when it names too many to judge one by one. */
|
||||
function expandGlob(abs: string): string[] | undefined {
|
||||
const parts = abs.split("/")
|
||||
const at = parts.findIndex((x) => /[*?[]/.test(x))
|
||||
const base = parts.slice(0, at).join("/") || "/"
|
||||
const out: string[] = []
|
||||
try {
|
||||
for (const f of new Bun.Glob(parts.slice(at).join("/")).scanSync({ cwd: base, dot: true, onlyFiles: false, followSymlinks: false })) {
|
||||
out.push(join(base, f))
|
||||
if (out.length > MAX_GLOB) return undefined
|
||||
}
|
||||
} catch {}
|
||||
return out.length ? out : [abs]
|
||||
}
|
||||
|
||||
/** The files a command names, absolute: its arguments that are not options (a search tool's
|
||||
* pattern excepted), what an input redirection reads, and what a glob expands to. A word that is
|
||||
* not really a path resolves inside the directory, harmlessly. `unsure`: a glob too wide to judge. */
|
||||
function commandPaths(commands: string[], cwd: string): { paths: string[]; unsure: boolean } {
|
||||
const out: string[] = []
|
||||
let unsure = false
|
||||
const add = (a: string) => {
|
||||
const home = a === "~" || a.startsWith("~/") ? join(homedir(), a.slice(1)) : a.replace(/^\$\{?HOME\}?(?=\/|$)/, homedir())
|
||||
const abs = resolve(cwd, home)
|
||||
if (!/[*?[]/.test(abs)) return void out.push(abs)
|
||||
const all = expandGlob(abs)
|
||||
if (all) out.push(...all)
|
||||
else unsure = true
|
||||
}
|
||||
for (const c of commands) {
|
||||
const w = words(c)
|
||||
// rg --files lists files: there is no pattern to skip, the first word is a path.
|
||||
let skipPattern = PATTERN_FIRST.has(basename(w[0] ?? "")) && !w.some((x) => x === "-e" || x.startsWith("--regexp") || x === "-f" || x === "--files")
|
||||
let afterRedirect = false
|
||||
let readNext = false
|
||||
for (const a of w.slice(1)) {
|
||||
// An input redirection reads a file just as an argument does: `cat < f`, `cat 0<f`.
|
||||
const input = /^\d*<(?![<>(])(.*)$/.exec(a)
|
||||
if (input) {
|
||||
if (input[1]) add(input[1])
|
||||
else readNext = true
|
||||
continue
|
||||
}
|
||||
if (readNext) {
|
||||
readNext = false
|
||||
add(a)
|
||||
continue
|
||||
}
|
||||
if (/^\d*>/.test(a) || a === "&>" || a === "&>>") {
|
||||
afterRedirect = true
|
||||
continue
|
||||
}
|
||||
if (afterRedirect) {
|
||||
afterRedirect = false
|
||||
continue
|
||||
}
|
||||
if (!a || a.startsWith("-") || DEVICES.test(a)) continue
|
||||
if (skipPattern) {
|
||||
skipPattern = false
|
||||
continue
|
||||
}
|
||||
add(a)
|
||||
}
|
||||
}
|
||||
return { paths: out, unsure }
|
||||
return projectRunsCode(p, projectDir)
|
||||
}
|
||||
|
||||
export function evaluate(req: PermissionRequest, ctx: Context): Decision {
|
||||
@@ -275,6 +237,8 @@ export function evaluate(req: PermissionRequest, ctx: Context): Decision {
|
||||
/** rules.md §4: a command typed into the person's terminal. */
|
||||
function evaluateTyped(req: PermissionRequest, ctx: Context): Decision {
|
||||
const line = req.command!
|
||||
// A line too long to read is never typed unasked, and never placed (rules.md §5).
|
||||
if (tooLong(line)) return { action: ctx.mode === "plan" ? "deny" : "ask", reason: TOO_LONG, always: [] }
|
||||
// 1. As bash would judge it: the hardline, bash's rules, the files it names, plan mode.
|
||||
const { typed: _typed, placed: _placed, ...rest } = req
|
||||
const asBash = evaluateRules({ ...rest, permission: "bash" }, ctx)
|
||||
@@ -291,10 +255,17 @@ function evaluateTyped(req: PermissionRequest, ctx: Context): Decision {
|
||||
return { action: "ask", reason: req.typed!, always: [] }
|
||||
}
|
||||
|
||||
const TOO_LONG = `the command is longer than ${MAX_COMMAND_BYTES / 1024} KiB: too long to check, so it is asked about in every mode`
|
||||
const tooLong = (line: string) => Buffer.byteLength(line, "utf8") > MAX_COMMAND_BYTES
|
||||
|
||||
function evaluateRules(req: PermissionRequest, ctx: Context): Decision {
|
||||
// 0. A line too long to read is not read (rules.md §5): neither the floor nor the rules could
|
||||
// be trusted on it in bounded time, so it is asked about — in auto mode too — and refused
|
||||
// where a mode refuses what it cannot allow.
|
||||
if (req.command !== undefined && tooLong(req.command)) return { action: ctx.mode === "plan" ? "deny" : "ask", reason: TOO_LONG, always: [] }
|
||||
// 1. The floor.
|
||||
if (req.command) {
|
||||
const hit = hardlineCommand(req.command, ctx.hardline)
|
||||
const hit = hardlineCommand(req.command, ctx.hardline, () => ({ branch: ctx.branch ? ctx.branch(req.paths?.[0] ?? ctx.root) : currentBranch(req.paths?.[0] ?? ctx.root) }))
|
||||
if (hit) return { action: "deny", reason: `refused: ${hit.description} (hardline rule ${hit.id})`, always: [] }
|
||||
}
|
||||
// Where each path really is: a symlink is judged by what it points to.
|
||||
@@ -334,8 +305,15 @@ function evaluateRules(req: PermissionRequest, ctx: Context): Decision {
|
||||
// outside the project, whatever the allow rule for `cat *` says.
|
||||
let named: string[] = []
|
||||
if (req.command !== undefined) {
|
||||
const c = commandPaths(patterns, real[0] ?? root)
|
||||
const c = touched(req.command, real[0] ?? root)
|
||||
// The protected paths hold for a command as for a tool (modes.json `floor`): what a line
|
||||
// may write there is refused in every mode. Reading is not: that is asked, as outside.
|
||||
for (const p of c.writes) {
|
||||
const guarded = protectedPath(p) ?? protectedPath(realPath(p))
|
||||
if (guarded) return { action: "deny", reason: `refused: ${guarded} is never written by a tool, and this command names it without being one that only reads`, always: [] }
|
||||
}
|
||||
named = c.paths.map(realPath)
|
||||
// A word that could not be read as a definite path or a definite non-path: not known safe.
|
||||
if (c.unsure && ruled === "allow") ruled = "ask"
|
||||
}
|
||||
// Reading a file by another tool (grep, glob, list) or a command follows the read rules too.
|
||||
@@ -401,7 +379,7 @@ function evaluateRules(req: PermissionRequest, ctx: Context): Decision {
|
||||
function withExternal(ruled: Action, ext: Action, external: string[], always: string[]): Decision {
|
||||
const action = strictest(ruled, ext)
|
||||
const reason = action === "allow" ? "allowed by rules" : ext !== "allow" ? `outside the project: ${external.join(", ")}` : "needs approval"
|
||||
return { action, reason, always }
|
||||
return { action, reason, always, ...(action === "ask" && ext === "ask" && always.length ? { outside: external } : {}) }
|
||||
}
|
||||
|
||||
/** Commands that run another command, or can: approving one with `*` would approve anything. */
|
||||
|
||||
+122
-36
@@ -1,6 +1,7 @@
|
||||
// The floor: commands that are refused in every mode, auto included, and that no
|
||||
// project config can re-enable. Patterns ported from Hermes Agent tools/approval_detection.py
|
||||
// HARDLINE_PATTERNS (MIT, © 2025 Nous Research), plus LLeMbas CLI's own (force-push to main).
|
||||
import { within } from "../within.ts"
|
||||
import { homedir } from "node:os"
|
||||
import { basename, join, posix, resolve } from "node:path"
|
||||
import { globalPaths, localRoot, paths } from "../config/paths.ts"
|
||||
@@ -10,14 +11,76 @@ import SPEC from "../../harness/permission/hardline.json"
|
||||
export interface HardlineRule {
|
||||
id: string
|
||||
description: string
|
||||
re: RegExp
|
||||
/** A pattern over the raw line and each plain spelling… */
|
||||
re?: RegExp
|
||||
/** …or a reader of one plain spelling (the spec's `check`). */
|
||||
check?: (plain: string, known: HardlineKnown) => boolean
|
||||
}
|
||||
|
||||
/** What the caller knows that a line does not say. */
|
||||
export interface HardlineKnown {
|
||||
/** The branch checked out where the command runs, when it is known. */
|
||||
branch?: string
|
||||
}
|
||||
|
||||
const rule = (id: string, description: string, src: string): HardlineRule => ({ id, description, re: new RegExp(src, SPEC.flags) })
|
||||
|
||||
interface PushSpec {
|
||||
branches: string[]
|
||||
value_options: string[]
|
||||
force_options: string[]
|
||||
delete_options: string[]
|
||||
all_options: string[]
|
||||
}
|
||||
|
||||
/** The spec's `git_push` check: a push read by its refspecs (hardline.json, force-push-main). */
|
||||
export function pushRefused(plain: string, spec: PushSpec, known: HardlineKnown = {}): boolean {
|
||||
const w = words(plain)
|
||||
if (basename(w[0] ?? "") !== "git" || w[1] !== "push") return false
|
||||
const has = (a: string, list: string[]) => list.some((o) => (o.startsWith("--") ? a === o || a.startsWith(o + "=") : /^-[A-Za-z]+$/.test(a) && a.includes(o.slice(1))))
|
||||
let forced = false
|
||||
let deletes = false
|
||||
let all = false
|
||||
const rest: string[] = []
|
||||
for (let i = 2; i < w.length; i++) {
|
||||
const a = w[i]!
|
||||
if (a === "--") {
|
||||
rest.push(...w.slice(i + 1))
|
||||
break
|
||||
}
|
||||
if (!a.startsWith("-") || a === "-") {
|
||||
rest.push(a)
|
||||
continue
|
||||
}
|
||||
if (has(a, spec.force_options)) forced = true
|
||||
if (has(a, spec.delete_options)) deletes = true
|
||||
if (has(a, spec.all_options)) all = true
|
||||
if (spec.value_options.includes(a)) i++
|
||||
}
|
||||
const refspecs = rest.slice(1)
|
||||
const guarded = (name: string) => spec.branches.includes(name.replace(/^refs\/heads\//, ""))
|
||||
let named = false
|
||||
for (const r of refspecs) {
|
||||
const plus = r.startsWith("+")
|
||||
const body = plus ? r.slice(1) : r
|
||||
const colon = body.indexOf(":")
|
||||
const src = colon < 0 ? body : body.slice(0, colon)
|
||||
const dst = colon < 0 ? body : body.slice(colon + 1)
|
||||
if (dst !== "HEAD" && dst !== "") named = true
|
||||
if (!guarded(dst)) continue
|
||||
if (deletes || (colon >= 0 && src === "")) return true
|
||||
if (forced || plus) return true
|
||||
}
|
||||
if (forced && all) return true
|
||||
if (forced && !named && known.branch !== undefined && spec.branches.includes(known.branch)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
// The rules themselves are the harness spec's (harness/permission/hardline.json), which LLeMbas
|
||||
// checks commands against too.
|
||||
export const BUILTIN_HARDLINE: HardlineRule[] = SPEC.rules.map((r) => rule(r.id, r.description, r.pattern))
|
||||
export const BUILTIN_HARDLINE: HardlineRule[] = (SPEC.rules as ({ id: string; description: string; pattern?: string; check?: string } & Partial<PushSpec>)[]).map((r) =>
|
||||
r.check === "git_push" ? { id: r.id, description: r.description, check: (plain, known) => pushRefused(plain, r as unknown as PushSpec, known) } : rule(r.id, r.description, r.pattern!),
|
||||
)
|
||||
|
||||
export interface HardlineOptions {
|
||||
extra?: string[]
|
||||
@@ -33,9 +96,17 @@ export function hardlineRules(opts: HardlineOptions = {}): HardlineRule[] {
|
||||
|
||||
/** The rule a command line trips, if any. Checked on the raw line, so splitting cannot hide one,
|
||||
* and on each command in a plain spelling, so writing it differently cannot hide one either. */
|
||||
export function hardlineCommand(line: string, rules: HardlineRule[]): HardlineRule | undefined {
|
||||
for (const l of [line, ...plainCommands(line)]) {
|
||||
const hit = rules.find((r) => r.re.test(l))
|
||||
export function hardlineCommand(line: string, rules: HardlineRule[], known: HardlineKnown | (() => HardlineKnown) = {}): HardlineRule | undefined {
|
||||
const plain = plainCommands(line)
|
||||
for (const l of [line, ...plain]) {
|
||||
const hit = rules.find((r) => r.re?.test(l))
|
||||
if (hit) return hit
|
||||
}
|
||||
const readers = rules.filter((r) => r.check)
|
||||
if (!readers.length || !plain.some((l) => /^git push( |$)/.test(l))) return undefined
|
||||
const k = typeof known === "function" ? known() : known
|
||||
for (const l of plain) {
|
||||
const hit = readers.find((r) => r.check!(l, k))
|
||||
if (hit) return hit
|
||||
}
|
||||
return undefined
|
||||
@@ -59,6 +130,49 @@ function plainPath(a: string): string {
|
||||
return p
|
||||
}
|
||||
|
||||
/** A command's words without what merely runs it: shell keywords, VAR= assignments and wrapper
|
||||
* programs with their options (`sudo -u x`, `env A=1`, `timeout 5`…). `inner` is given the
|
||||
* command line `env -S` carries. */
|
||||
export function unwrap(words: string[], inner?: (line: string) => void): string[] {
|
||||
let w = words
|
||||
for (;;) {
|
||||
while (w.length && (KEYWORDS.has(w[0]!) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]!))) w = w.slice(1)
|
||||
const prog = basename(w[0] ?? "")
|
||||
const takes = WRAPPERS[prog]
|
||||
if (!takes) return w
|
||||
let i = 1
|
||||
while (i < w.length) {
|
||||
const a = w[i]!
|
||||
if (a === "--") {
|
||||
i++
|
||||
break
|
||||
}
|
||||
if (prog === "env" && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (prog === "env" && (a === "-S" || a.startsWith("--split-string"))) {
|
||||
const line = a.includes("=") ? a.slice(a.indexOf("=") + 1) : w[i + 1]
|
||||
if (line) inner?.(line)
|
||||
i = w.length
|
||||
break
|
||||
}
|
||||
if (!a.startsWith("-")) break
|
||||
i += takes.includes(a) ? 2 : 1
|
||||
}
|
||||
// timeout's first word after its options is the duration.
|
||||
if (prog === "timeout" && i < w.length) i++
|
||||
w = w.slice(i)
|
||||
}
|
||||
}
|
||||
|
||||
/** The command line a shell's -c carries, if these words are such a call. */
|
||||
export function shellInner(w: string[]): string | undefined {
|
||||
if (!SHELLS.has(basename(w[0] ?? ""))) return undefined
|
||||
const flag = w.findIndex((a, i) => i > 0 && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(a))
|
||||
return flag >= 0 ? w[flag + 1] : undefined
|
||||
}
|
||||
|
||||
/** Each simple command of a line, rewritten plainly: no VAR= prefixes, wrappers (sudo -u x, env
|
||||
* -i, timeout 5, xargs…), quotes, escapes or program paths; paths normalised (`/etc/` is /etc,
|
||||
* the home directory is ~); `sh -c "…"` read as the line it runs. */
|
||||
@@ -71,35 +185,7 @@ export function plainCommands(line: string, depth = 0): string[] {
|
||||
for (const inner of substitutions(line)) out.push(...plainCommands(inner, depth + 1))
|
||||
for (const c of splitCommand(line).commands) {
|
||||
let w = words(c).map((x) => x.replace(/^\(+/, "").replace(/\)+$/, "")).filter((x) => x !== "")
|
||||
for (;;) {
|
||||
while (w.length && (KEYWORDS.has(w[0]!) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]!))) w = w.slice(1)
|
||||
const prog = basename(w[0] ?? "")
|
||||
const takes = WRAPPERS[prog]
|
||||
if (!takes) break
|
||||
let i = 1
|
||||
while (i < w.length) {
|
||||
const a = w[i]!
|
||||
if (a === "--") {
|
||||
i++
|
||||
break
|
||||
}
|
||||
if (prog === "env" && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (prog === "env" && (a === "-S" || a.startsWith("--split-string"))) {
|
||||
const inner = a.includes("=") ? a.slice(a.indexOf("=") + 1) : w[i + 1]
|
||||
if (inner) out.push(...plainCommands(inner, depth + 1))
|
||||
i = w.length
|
||||
break
|
||||
}
|
||||
if (!a.startsWith("-")) break
|
||||
i += takes.includes(a) ? 2 : 1
|
||||
}
|
||||
// timeout's first word after its options is the duration.
|
||||
if (prog === "timeout" && i < w.length) i++
|
||||
w = w.slice(i)
|
||||
}
|
||||
w = unwrap(w, (inner) => out.push(...plainCommands(inner, depth + 1)))
|
||||
if (!w.length) continue
|
||||
const prog = basename(w[0]!)
|
||||
let args = w.slice(1)
|
||||
@@ -180,12 +266,12 @@ export function protectedPath(abs: string): string | undefined {
|
||||
? configs.map((c): [string, string] => [resolve(c, g.path.slice("<config>/".length)), g.label ?? g.path])
|
||||
: [[g.path.startsWith("~/") ? resolve(home, g.path.slice(2)) : g.path, g.label ?? g.path] as [string, string]],
|
||||
)
|
||||
for (const [p, label] of guarded) if (abs === p || abs.startsWith(p + "/")) return label
|
||||
for (const [p, label] of guarded) if (within(abs, p)) return label
|
||||
// Local mode keeps its config, keys, trust and sessions inside the project, where edit mode would
|
||||
// otherwise let a tool rewrite them: no tool writes there — the program does, as it does in
|
||||
// ~/.config. Except the worktrees, which are where a session may work.
|
||||
const root = localRoot()
|
||||
const inside = (p: string) => abs === p || abs.startsWith(p + "/")
|
||||
const inside = (p: string) => within(abs, p)
|
||||
if (root && inside(root) && !inside(join(root, "data", "worktrees"))) return "local mode's own files"
|
||||
return undefined
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// The permission modes' order (harness permission/modes.json `order`, loosest first) and the three
|
||||
// questions asked of it — which is stricter, the stricter of two, a mode lowered to a ceiling. Five
|
||||
// files had a table of their own; this is the one.
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import MODES_JSON from "../../harness/permission/modes.json"
|
||||
|
||||
/** Loosest first: auto, edit, manual, plan. */
|
||||
export const MODE_ORDER = MODES_JSON.order as Mode[]
|
||||
|
||||
/** A mode's place in the order: higher is stricter. */
|
||||
export const MODE_RANK = Object.fromEntries(MODE_ORDER.map((m, i) => [m, i])) as Record<Mode, number>
|
||||
|
||||
/** a is looser than b. */
|
||||
export const looser = (a: Mode, b: Mode) => MODE_RANK[a] < MODE_RANK[b]
|
||||
/** a is stricter than b. */
|
||||
export const stricter = (a: Mode, b: Mode) => MODE_RANK[a] > MODE_RANK[b]
|
||||
|
||||
/** The stricter of the two; `a` may be absent. */
|
||||
export function stricterMode(a: Mode | undefined, b: Mode): Mode {
|
||||
return a !== undefined && stricter(a, b) ? a : b
|
||||
}
|
||||
|
||||
/** A mode lowered to `max`: never looser than it. */
|
||||
export const clampMode = (wanted: Mode, max: Mode): Mode => (looser(wanted, max) ? max : wanted)
|
||||
@@ -0,0 +1,251 @@
|
||||
// What a command line touches (harness permission/rules.md §5): the files its words name, read
|
||||
// the way the shell and the program will read them — and, where a word cannot be read that way,
|
||||
// the answer "not sure", which is never "safe".
|
||||
import { homedir } from "node:os"
|
||||
import { basename, join, resolve } from "node:path"
|
||||
import { shellWords, splitCommand, type Word } from "./bash.ts"
|
||||
import { shellInner, substitutions, unwrap } from "./hardline.ts"
|
||||
import SPEC from "../../harness/permission/hardline.json"
|
||||
|
||||
const C = SPEC.commands
|
||||
const KNOWN = new Set(C.known_variables)
|
||||
const READERS = new Set(C.readers)
|
||||
const PATTERN_FIRST = new Set(C.pattern_first)
|
||||
const CD = new Set(C.cd)
|
||||
const DEVICES = /^\/dev\/(null|zero|stdin|stdout|stderr|tty|u?random)$/
|
||||
const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/
|
||||
|
||||
/** The longest command line that is analysed at all (UTF-8 bytes). */
|
||||
export const MAX_COMMAND_BYTES = C.max_bytes
|
||||
|
||||
export interface Touched {
|
||||
/** Every path the line names, absolute (not yet real). */
|
||||
paths: string[]
|
||||
/** Those it may write: a redirection's target, and every path named by a command that is not
|
||||
* known to only read what it names. */
|
||||
writes: string[]
|
||||
/** A word could not be resolved to a definite path or a definite non-path. */
|
||||
unsure: boolean
|
||||
}
|
||||
|
||||
/** What a glob names, as the shell would expand it — dotfiles included, to be safe. Undefined
|
||||
* when it names too many to judge one by one. */
|
||||
function expandGlob(abs: string): string[] | undefined {
|
||||
const parts = abs.split("/")
|
||||
const at = parts.findIndex((x) => /[*?[]/.test(x))
|
||||
const base = parts.slice(0, at).join("/") || "/"
|
||||
const out: string[] = []
|
||||
try {
|
||||
for (const f of new Bun.Glob(parts.slice(at).join("/")).scanSync({ cwd: base, dot: true, onlyFiles: false, followSymlinks: false })) {
|
||||
out.push(join(base, f))
|
||||
if (out.length > C.glob_max) return undefined
|
||||
}
|
||||
} catch {}
|
||||
return out.length ? out : [abs]
|
||||
}
|
||||
|
||||
const sub = (w: Word, from: number, to = w.text.length): Word => ({ text: w.text.slice(from, to), mask: w.mask.slice(from, to) })
|
||||
const cat = (...ws: Word[]): Word => ({ text: ws.map((w) => w.text).join(""), mask: ws.map((w) => w.mask).join("") })
|
||||
|
||||
/** Brace expansion, the shell's first step: `a{b,c}d` is `abd acd`. Undefined for what is not
|
||||
* modelled (a sequence `{1..9}`, or more words than the spec's cap). A brace without an
|
||||
* unquoted comma is text (`HEAD@{1}`). */
|
||||
function braces(w: Word, budget = { n: C.brace_max }): Word[] | undefined {
|
||||
for (let i = 0; i < w.text.length; i++) {
|
||||
if (w.text[i] !== "{" || w.mask[i] !== "u") continue
|
||||
// `${` is a parameter expansion, not a brace list.
|
||||
if (i > 0 && w.text[i - 1] === "$" && w.mask[i - 1] !== "s") continue
|
||||
let depth = 0
|
||||
const cuts: number[] = []
|
||||
let close = -1
|
||||
for (let j = i; j < w.text.length; j++) {
|
||||
if (w.mask[j] !== "u") continue
|
||||
const ch = w.text[j]
|
||||
if (ch === "{") depth++
|
||||
else if (ch === "}" && --depth === 0) {
|
||||
close = j
|
||||
break
|
||||
} else if (ch === "," && depth === 1) cuts.push(j)
|
||||
}
|
||||
if (close < 0) return [w]
|
||||
if (!cuts.length) {
|
||||
if (/^.+\.\..+$/.test(w.text.slice(i + 1, close))) return undefined
|
||||
continue
|
||||
}
|
||||
const out: Word[] = []
|
||||
const marks = [i, ...cuts, close]
|
||||
for (let k = 0; k + 1 < marks.length; k++) {
|
||||
const part = cat(sub(w, 0, i), sub(w, marks[k]! + 1, marks[k + 1]!), sub(w, close + 1))
|
||||
const more = braces(part, budget)
|
||||
if (!more) return undefined
|
||||
out.push(...more)
|
||||
if ((budget.n -= more.length) < 0) return undefined
|
||||
}
|
||||
return out
|
||||
}
|
||||
return [w]
|
||||
}
|
||||
|
||||
/** Tilde and parameter expansion of one word. Undefined when the word holds an expansion that is
|
||||
* not modelled: `~name`, any variable but the known ones, a command substitution, a special
|
||||
* parameter. What comes out is text (quoted), except that glob characters stay live. */
|
||||
function expand(w: Word, vars: Record<string, string>): string | undefined {
|
||||
let out = ""
|
||||
let i = 0
|
||||
if (w.text[0] === "~" && w.mask[0] === "u") {
|
||||
if (w.text.length > 1 && w.text[1] !== "/") return undefined
|
||||
out = vars.HOME!
|
||||
i = 1
|
||||
}
|
||||
for (; i < w.text.length; i++) {
|
||||
const ch = w.text[i]!
|
||||
const live = w.mask[i] !== "s"
|
||||
if (ch === "`" && live) return undefined
|
||||
if (ch !== "$" || !live) {
|
||||
out += ch
|
||||
continue
|
||||
}
|
||||
const rest = w.text.slice(i + 1)
|
||||
const name = /^(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/.exec(rest)
|
||||
if (name) {
|
||||
const v = name[1] ?? name[2]!
|
||||
if (!KNOWN.has(v) || vars[v] === undefined) return undefined
|
||||
out += vars[v]
|
||||
i += name[0].length
|
||||
continue
|
||||
}
|
||||
// `$(`, `${…}` of another shape, `$?`, `$1`, `$@`…: the shell puts something there.
|
||||
if (/^[({?$!@*#\-0-9]/.test(rest)) return undefined
|
||||
out += ch
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function unparen(w: Word): Word {
|
||||
let a = 0
|
||||
let b = w.text.length
|
||||
while (a < b && w.text[a] === "(" && w.mask[a] === "u" && w.text[a + 1] !== ")") a++
|
||||
while (b > a && w.text[b - 1] === ")" && w.mask[b - 1] === "u") b--
|
||||
// `<(`, `>(`, `$(` keep their parenthesis: they are judged as what they are.
|
||||
return a === 0 && b === w.text.length ? w : sub(w, a, b)
|
||||
}
|
||||
|
||||
export function touched(line: string, cwd: string): Touched {
|
||||
const t: Touched = { paths: [], writes: [], unsure: false }
|
||||
if (Buffer.byteLength(line, "utf8") > MAX_COMMAND_BYTES) return { ...t, unsure: true }
|
||||
read(line, [resolve(cwd)], t, 0)
|
||||
t.paths = [...new Set(t.paths)]
|
||||
t.writes = [...new Set(t.writes)]
|
||||
return t
|
||||
}
|
||||
|
||||
function read(line: string, start: string[], t: Touched, depth: number): void {
|
||||
if (depth > 3) return void (t.unsure = true)
|
||||
// What a substitution runs names files too: `echo $(cat .env)`.
|
||||
for (const inner of substitutions(line)) read(inner, start, t, depth + 1)
|
||||
// The directories the line's commands may run in: where it starts, and wherever a `cd` in it
|
||||
// goes. A relative path is judged in each (a `cd` in a subshell does not move the next
|
||||
// command, and one outside does).
|
||||
let dirs = start
|
||||
const open = shellWords(line)
|
||||
.map((x) => [...x.text].map((ch, i) => (x.mask[i] === "u" ? ch : "x")).join(""))
|
||||
.join(" ")
|
||||
.replace(/&&|>&|&>/g, " ")
|
||||
const sequence = !/[()|&{}]/.test(open)
|
||||
for (const c of splitCommand(line).commands) {
|
||||
// A subshell's parentheses are the shell's, not part of a name: `(cd x; cat y)`.
|
||||
let w = shellWords(c).map(unparen).filter((x) => x.text !== "")
|
||||
while (w.length > 1 && ASSIGN.test(w[0]!.text)) w = w.slice(1)
|
||||
const texts = w.map((x) => x.text)
|
||||
const plain = unwrap(texts, (inner) => read(inner, dirs, t, depth + 1))
|
||||
const prog = basename(plain[0] ?? "")
|
||||
const inner = shellInner(plain)
|
||||
if (inner !== undefined) read(inner, dirs, t, depth + 1)
|
||||
const reader = READERS.has(prog)
|
||||
const vars = (dir: string): Record<string, string> => ({ HOME: homedir(), PWD: dir })
|
||||
|
||||
/** One candidate path: expanded, resolved in every directory, recorded. */
|
||||
const name = (cand: Word, write: boolean): string[] => {
|
||||
const found: string[] = []
|
||||
if (!cand.text) return found
|
||||
const parts = braces(cand)
|
||||
if (!parts) return (t.unsure = true), found
|
||||
for (const part of parts)
|
||||
for (const dir of dirs) {
|
||||
const text = expand(part, vars(dir))
|
||||
if (text === undefined) {
|
||||
t.unsure = true
|
||||
continue
|
||||
}
|
||||
if (DEVICES.test(text)) continue
|
||||
const abs = resolve(dir, text)
|
||||
const names = /[*?[]/.test(abs) ? expandGlob(abs) : [abs]
|
||||
if (!names) {
|
||||
t.unsure = true
|
||||
continue
|
||||
}
|
||||
found.push(...names)
|
||||
t.paths.push(...names)
|
||||
if (write) t.writes.push(...names)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
let skipPattern = PATTERN_FIRST.has(prog) && !texts.some((x) => C.pattern_options.some((o) => x === o || x.startsWith(o + "=")) || /^-[A-Za-z]*[ef]/.test(x))
|
||||
let pending: "read" | "write" | "skip" | undefined
|
||||
const moved: string[] = []
|
||||
for (const a of w.slice(1)) {
|
||||
if (pending) {
|
||||
if (pending !== "skip") name(a, pending === "write")
|
||||
pending = undefined
|
||||
continue
|
||||
}
|
||||
// A redirection, where the operator is the shell's own (not quoted).
|
||||
const op = /^(\d*|&)(<<<|<<-?|<>|<|>>|>\||>)(&?)/.exec(a.text)
|
||||
if (op && !a.mask.slice(0, op[0].length).includes("s") && !a.mask.slice(0, op[0].length).includes("d") && !a.text.startsWith("<(") && !a.text.startsWith(">(")) {
|
||||
const target = sub(a, op[0].length)
|
||||
const kind = op[2]!.startsWith("<<") ? "skip" : op[2] === "<" ? "read" : "write"
|
||||
// `2>&1`, `>&-`: a descriptor, not a file.
|
||||
if (op[3] && /^(\d+|-)$/.test(target.text)) continue
|
||||
if (!target.text) pending = kind
|
||||
else if (kind !== "skip") name(target, kind === "write")
|
||||
continue
|
||||
}
|
||||
if (a.text === "-" || a.text === "--") continue
|
||||
if (a.text.startsWith("-")) {
|
||||
// A path may ride on an option: `--file=PATH`, `-fPATH`. Every value an option could
|
||||
// carry is judged as a path; one that is not a path resolves harmlessly.
|
||||
const eq = a.text.indexOf("=")
|
||||
if (eq > 0) name(sub(a, eq + 1), !reader)
|
||||
if (!a.text.startsWith("--")) {
|
||||
if (a.text.length > 256) t.unsure = true
|
||||
else for (let i = 2; i < a.text.length && /^[A-Za-z0-9]$/.test(a.text[i - 1]!); i++) name(sub(a, i), !reader)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (skipPattern) {
|
||||
skipPattern = false
|
||||
// The pattern is the shell's word first: an expansion in it is still not known.
|
||||
if (braces(a) === undefined || expand(a, vars(dirs[0]!)) === undefined) t.unsure = true
|
||||
continue
|
||||
}
|
||||
const found = name(a, !reader)
|
||||
// `if=PATH`, `VAR=PATH` as an operand.
|
||||
const eq = a.text.indexOf("=")
|
||||
if (eq > 0) name(sub(a, eq + 1), !reader)
|
||||
if (CD.has(prog) && !moved.length) moved.push(...found)
|
||||
}
|
||||
if (CD.has(prog)) {
|
||||
const to = moved.length ? moved : w.length === 1 ? [homedir()] : []
|
||||
// `cd -`, `cd "$d"`: somewhere this reader does not know.
|
||||
if (!to.length) t.unsure = true
|
||||
// In a plain sequence the next command runs where `cd` went; inside a subshell, a pipe or
|
||||
// a background job it may not, so both places are judged.
|
||||
dirs = to.length && sequence ? [...new Set(to)] : [...new Set([...dirs, ...to])]
|
||||
if (dirs.length > 16) {
|
||||
dirs = dirs.slice(0, 16)
|
||||
t.unsure = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
-10
@@ -2,7 +2,8 @@
|
||||
// project) .agent/commands/. The file name is the command; YAML frontmatter may give a
|
||||
// description, a model and a mode; the body is the prompt. In the body:
|
||||
// $ARGUMENTS everything after the command $1 … $9 the arguments one by one
|
||||
// !`command` replaced by that command's output (run in the project, the hardline applies)
|
||||
// !`command` replaced by that command's output — run in the project only when the session
|
||||
// would run it as a bash call without asking; the arguments are its $1 … $9
|
||||
// @path attached like any @reference
|
||||
import { existsSync, readdirSync, readFileSync } from "node:fs"
|
||||
import { basename, join } from "node:path"
|
||||
@@ -10,6 +11,7 @@ import { parse } from "yaml"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { hardlineCommand, type HardlineRule } from "../permission/hardline.ts"
|
||||
import { words } from "../permission/bash.ts"
|
||||
import { ENV } from "../tool/bash.ts"
|
||||
|
||||
export interface CustomCommand {
|
||||
name: string
|
||||
@@ -55,15 +57,37 @@ export function customCommands(projectDir: string | undefined): CustomCommand[]
|
||||
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name))
|
||||
}
|
||||
|
||||
/** The prompt a command sends. */
|
||||
export function expandCommand(cmd: CustomCommand, args: string, root: string, hardline: HardlineRule[]): string {
|
||||
/** What is decided for one `` !`…` `` before it runs: the session's own answer for a `bash` call
|
||||
* of that line (harness permission/rules.md §6). */
|
||||
export type SubstitutionJudge = (command: string) => { action: "allow" | "ask" | "deny"; reason: string }
|
||||
|
||||
/** How long a substitution may take: it is a quick look, read before the prompt is sent. */
|
||||
export const SUBSTITUTION_TIMEOUT_MS = 10_000
|
||||
|
||||
/** The prompt a command sends (rules.md §6). `$ARGUMENTS` and `$1…$9` are filled in the text —
|
||||
* in one pass, so nothing in the arguments is read as a placeholder again. Inside a
|
||||
* `` !`…` `` nothing is filled in: the line is run as written, with the arguments as the
|
||||
* shell's own positional parameters and `$ARGUMENTS` in its environment — data, never part of
|
||||
* the command line — and only when `judge` allows a `bash` call of it without asking. */
|
||||
export function expandCommand(cmd: CustomCommand, args: string, root: string, hardline: HardlineRule[], judge: SubstitutionJudge): string {
|
||||
const list = words(args)
|
||||
let text = cmd.body.replaceAll("$ARGUMENTS", args).replace(/\$(\d)/g, (_, n: string) => list[Number(n) - 1] ?? "")
|
||||
text = text.replace(/!`([^`]+)`/g, (_, command: string) => {
|
||||
const hit = hardlineCommand(command, hardline)
|
||||
const fill = (text: string) => text.replace(/\$(ARGUMENTS|\d)/g, (_, n: string) => (n === "ARGUMENTS" ? args : (list[Number(n) - 1] ?? "")))
|
||||
const run = (command: string): string => {
|
||||
// The floor, on the line as written and as it reads with the arguments in place.
|
||||
const hit = hardlineCommand(command, hardline) ?? hardlineCommand(fill(command), hardline)
|
||||
if (hit) return `[not run — ${hit.description}]`
|
||||
const r = Bun.spawnSync(["bash", "-c", command], { cwd: root, stdout: "pipe", stderr: "pipe" })
|
||||
return (r.stdout.toString() + r.stderr.toString()).trim()
|
||||
})
|
||||
return text.trim()
|
||||
const d = judge(command)
|
||||
if (d.action === "deny") return `[not run — ${d.reason}]`
|
||||
if (d.action === "ask") return `[not run — \`${command}\` needs the person's approval here; run it with bash if its output is needed]`
|
||||
const r = Bun.spawnSync(["bash", "-c", command, "lembas", ...list], { cwd: root, stdout: "pipe", stderr: "pipe", stdin: "ignore", timeout: SUBSTITUTION_TIMEOUT_MS, env: { ...ENV, ARGUMENTS: args } })
|
||||
const out = (r.stdout.toString() + r.stderr.toString()).trim()
|
||||
return r.exitedDueToTimeout ? `${out}\n[stopped after ${SUBSTITUTION_TIMEOUT_MS / 1000} s]`.trim() : out
|
||||
}
|
||||
let out = ""
|
||||
let at = 0
|
||||
for (const m of cmd.body.matchAll(/!`([^`]+)`/g)) {
|
||||
out += fill(cmd.body.slice(at, m.index)) + run(m[1]!)
|
||||
at = m.index + m[0].length
|
||||
}
|
||||
return (out + fill(cmd.body.slice(at))).trim()
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
// The project's file list for @ completion: ripgrep when present (honours .gitignore), a walk
|
||||
// otherwise; refreshed at most every few seconds. Ranked with fuzzysort, nudged by frecency.
|
||||
import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import { readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import fuzzysort from "fuzzysort"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, paths } from "../config/paths.ts"
|
||||
|
||||
const MAX = 50_000
|
||||
const IGNORED = ["node_modules", ".git", "dist", "build", ".venv", "venv", "__pycache__", "target", ".next", ".cache"]
|
||||
@@ -86,7 +86,7 @@ export class FileIndex {
|
||||
const all = readFrecency()
|
||||
all[this.root] = this.frecency
|
||||
try {
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
writeFileSync(join(paths.state, "frecency.json"), JSON.stringify(all))
|
||||
} catch {}
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
// The first time LLeMbas CLI opens a directory: trust, git, and the .agent skeleton.
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import { join, relative } from "node:path"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, paths } from "../config/paths.ts"
|
||||
import type { Project } from "./root.ts"
|
||||
|
||||
const CONFIG_TEMPLATE = `# LLeMbas CLI settings for this project. Merged over ~/.config/lembas/config.yaml,
|
||||
@@ -66,6 +66,6 @@ export function neverGitInit(root: string): boolean {
|
||||
export function setNeverGitInit(root: string) {
|
||||
const p = readPrefs()
|
||||
p[root] = { ...p[root], gitInit: "never" }
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
writeFileSync(prefsFile(), JSON.stringify(p, null, 2))
|
||||
}
|
||||
+4
-3
@@ -1,7 +1,8 @@
|
||||
import { within } from "../within.ts"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import { dirname, join, resolve } from "node:path"
|
||||
import { parseDocument } from "yaml"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, paths } from "../config/paths.ts"
|
||||
import type { Rule } from "../permission/evaluate.ts"
|
||||
import { assertProjectFile } from "./safe.ts"
|
||||
|
||||
@@ -103,13 +104,13 @@ export function trustedRoots(): string[] {
|
||||
* happen anywhere in there. */
|
||||
export function trustedWithin(dir: string): boolean {
|
||||
const target = resolve(dir)
|
||||
return trustedRoots().some((t) => target === t || target.startsWith(t.endsWith("/") ? t : `${t}/`))
|
||||
return trustedRoots().some((t) => within(target, t))
|
||||
}
|
||||
|
||||
export function setTrust(root: string, level: TrustLevel) {
|
||||
const t = readTrust()
|
||||
t[resolve(root)] = level
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
writeFileSync(trustFile(), JSON.stringify(t, null, 2))
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,10 +1,11 @@
|
||||
// Files LLeMbas CLI itself writes or reads inside a project (.agent/config.yaml, tasks.md,
|
||||
// decisions.md, local/MEMORY.md): a cloned repository can commit any of them as a symbolic link,
|
||||
// and a write that follows one lands wherever it points. Such a file is refused.
|
||||
import { within } from "../within.ts"
|
||||
import { lstatSync, realpathSync } from "node:fs"
|
||||
import { dirname } from "node:path"
|
||||
|
||||
const inside = (p: string, dir: string) => p === dir || p.startsWith(dir.endsWith("/") ? dir : `${dir}/`)
|
||||
const inside = within
|
||||
|
||||
/** Why `file` (in `root`) may not be used, or undefined when it is an ordinary file — or not there
|
||||
* yet — in a directory that really is inside the root. */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { relativeWithin } from "../within.ts"
|
||||
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
|
||||
import { homedir, platform, release } from "node:os"
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
|
||||
@@ -291,17 +292,17 @@ export function envLines(root: string, started: string): string[] {
|
||||
const r = resolve(root)
|
||||
const name = basename(r) || r
|
||||
const lines = [fillPrompt(LOOP.context.env.project, { name })]
|
||||
const rel = relative(r, resolve(started))
|
||||
if (rel && !rel.startsWith("..") && !isAbsolute(rel)) lines.push(fillPrompt(LOOP.context.env.started, { path: rel }))
|
||||
const rel = relativeWithin(resolve(started), r)
|
||||
if (rel) lines.push(fillPrompt(LOOP.context.env.started, { path: rel }))
|
||||
return lines
|
||||
}
|
||||
|
||||
/** A path as a prompt names it (context.md §11): relative to the project root inside it, `~/…`
|
||||
* under the person's home, absolute only outside both. */
|
||||
export function promptPath(root: string, path: string): string {
|
||||
const rel = relative(resolve(root), path)
|
||||
const rel = relativeWithin(resolve(path), resolve(root))
|
||||
if (rel === "") return "."
|
||||
if (!rel.startsWith("..") && !isAbsolute(rel)) return rel
|
||||
if (rel !== undefined) return rel
|
||||
const home = homedir()
|
||||
if (home && home !== "/" && (path === home || path.startsWith(home + sep))) return `~${path.slice(home.length)}`
|
||||
return path
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// The files of a project that run code (harness loop.json `files.runs_code`; acp.md, *Files that
|
||||
// run code*): git's own directory — hooks and config run programs — and the agent's own
|
||||
// configuration in the project: its config (rules, MCP servers), agents, commands and skills.
|
||||
// One definition, for the two places that ask: edit mode, which does not change them unasked
|
||||
// (permission/evaluate.ts), and device files, which change them only where the device says so
|
||||
// (acp/files.ts). They differed: the second knew the directory by one of its two names.
|
||||
import { LOOP } from "./harness.ts"
|
||||
import { within } from "./within.ts"
|
||||
|
||||
const R = LOOP.files.runs_code
|
||||
|
||||
/** Whether a change at `p` (absolute) would change what runs in its project: a path with a
|
||||
* `.git` in it; or, under a project's agent directory — any directory named `.agent` or
|
||||
* `.lembas`, and `projectDir` when the caller knows the real one — the directory itself or one
|
||||
* of the names that run. */
|
||||
export function projectRunsCode(p: string, projectDir?: string, spec: typeof R = R): boolean {
|
||||
const parts = p.split("/")
|
||||
if (parts.some((x) => spec.segments.includes(x))) return true
|
||||
const under = (rest: string[]) => !rest.length || spec.project.includes(rest[0]!)
|
||||
const at = Math.max(...spec.project_dirs.map((d) => parts.lastIndexOf(d)))
|
||||
if (at >= 0 && under(parts.slice(at + 1))) return true
|
||||
if (projectDir && within(p, projectDir)) return under(p.slice(projectDir.length).split("/").filter(Boolean))
|
||||
return false
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ export interface WebuiSearch {
|
||||
|
||||
function target(c: SearchConfig): Required<Pick<WebuiSearch, "base_url">> & WebuiSearch {
|
||||
const w = c.webui as WebuiSearch | undefined
|
||||
if (!w?.base_url) throw new SearchError("not configured (a webui connection: lembas login)")
|
||||
if (!w?.base_url) throw new SearchError("not signed in to a LLeMbas server (lembas login)")
|
||||
return w as Required<Pick<WebuiSearch, "base_url">> & WebuiSearch
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@
|
||||
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { paths } from "./config/paths.ts"
|
||||
import { ownDir, paths } from "./config/paths.ts"
|
||||
import { LinkError, limitsFromConfig, runLink, type LinkStatus } from "./acp/link.ts"
|
||||
import { Hub } from "./acp/hub.ts"
|
||||
|
||||
@@ -151,7 +151,7 @@ export function holdsLock(pid: number): boolean {
|
||||
* made exclusively (never checked and then written: two starting together would both pass the
|
||||
* check), and a lock whose holder is gone is taken over. */
|
||||
export function takeLock(file = lockFile()): () => void {
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
ownDir(paths.state)
|
||||
const release = () => {
|
||||
// Only this process's own: a lock taken over meanwhile is the other's.
|
||||
try {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
// The TUI runs the same builders (review, changelog, init) and the same rules (a built-in name wins
|
||||
// over a custom command's, a custom command's over a skill's; @files come from what was typed, never
|
||||
// from a command's own text), so a command does the same thing whichever keyboard typed it.
|
||||
import { stricterMode } from "../permission/modes.ts"
|
||||
import { existsSync } from "node:fs"
|
||||
import type { App } from "../app.ts"
|
||||
import { MODES, type Mode } from "../config/schema.ts"
|
||||
@@ -317,7 +318,7 @@ export function expandSlash(app: App, text: string, o: { plain?: boolean } = {})
|
||||
// A project's command may make the mode stricter for its prompt, never looser; your own may.
|
||||
const own = cc.mode && (MODES as readonly string[]).includes(cc.mode) ? (cc.mode as Mode) : undefined
|
||||
const mode = own && cc.source === "project" ? stricter(own, app.engine.mode) : own
|
||||
return { kind: "prompt", name, prompt: expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline), shown: t, attachFrom: arg, model: cc.model, ...(mode ? { mode } : {}) }
|
||||
return { kind: "prompt", name, prompt: expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline, (line) => app.engine.judgeCommand(line, app.project.root)), shown: t, attachFrom: arg, model: cc.model, ...(mode ? { mode } : {}) }
|
||||
}
|
||||
const sk = src.skills().find((s) => slug(s.name) === wanted)
|
||||
if (sk) return { kind: "prompt", name, prompt: skillMessage(sk, words), shown: t, attachFrom: words }
|
||||
@@ -325,7 +326,4 @@ export function expandSlash(app: App, text: string, o: { plain?: boolean } = {})
|
||||
return undefined
|
||||
}
|
||||
|
||||
const RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
|
||||
function stricter(a: Mode, b: Mode): Mode {
|
||||
return RANK[a] > RANK[b] ? a : b
|
||||
}
|
||||
const stricter = (a: Mode, b: Mode): Mode => stricterMode(a, b)
|
||||
+24
-6
@@ -4,11 +4,11 @@
|
||||
// backstop, not a budget (LLeMbas generation._run / _wrap_up).
|
||||
// The text is the harness spec's, so LLeMbas's Continue sends the same words.
|
||||
import continueText from "../../harness/prompts/tasks/continue.md" with { type: "text" }
|
||||
import { isAbsolute } from "node:path"
|
||||
import { isAbsolute, relative } from "node:path"
|
||||
import type { Asker, AttachmentInfo, Bus } from "../bus/index.ts"
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import type { Level } from "../provider/effort.ts"
|
||||
import { evaluate, judgeNewRule, ruleAction, shadowsDeny, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
|
||||
import { alwaysRules, evaluate, judgeNewRule, ruleAction, shadowsDeny, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
|
||||
import { ProviderError, type Client, type ImagePart, type Message, type ResolvedModel, type ToolCallPart, type Usage } from "../provider/types.ts"
|
||||
import type { Plan } from "../plan/plan.ts"
|
||||
import { LOOP } from "../harness.ts"
|
||||
@@ -364,6 +364,18 @@ export class Engine {
|
||||
}
|
||||
|
||||
/** What is met now, for a call: the mode for plan, the display as it is; the rest are fixed. */
|
||||
/** What a `bash` call of this line would be answered right now, by the rules and the mode. */
|
||||
judgeCommand(line: string, cwd?: string): { action: "allow" | "ask" | "deny"; reason: string } {
|
||||
const ctx: PermContext = { ...this.o.perm, mode: this.mode, rules: [...this.o.perm.rules, ...this.sessionRules] }
|
||||
return evaluate({ permission: "bash", class: "execute", patterns: [line], command: line, paths: [cwd ?? ctx.root] }, ctx)
|
||||
}
|
||||
|
||||
/** Whether the read tool would read this file unasked right now (ToolContext.mayRead). */
|
||||
mayRead(abs: string): boolean {
|
||||
const ctx: PermContext = { ...this.o.perm, mode: this.mode, rules: [...this.o.perm.rules, ...this.sessionRules] }
|
||||
return evaluate({ permission: "read", class: "read", patterns: [relative(ctx.root, abs) || "."], paths: [abs] }, ctx).action === "allow"
|
||||
}
|
||||
|
||||
private met(): Set<Requirement> {
|
||||
const met = this.could()
|
||||
if (this.mode !== "plan") met.delete("plan")
|
||||
@@ -1165,6 +1177,7 @@ export class Engine {
|
||||
...this.o.toolCtx,
|
||||
signal,
|
||||
backgroundNow: bgNow.signal,
|
||||
mayRead: (abs) => this.mayRead(abs),
|
||||
question: this.o.asker.question ? (req, id) => this.waiting(this.o.asker.question!(req, id), "question") : undefined,
|
||||
plan: {
|
||||
get: () => this.plan,
|
||||
@@ -1368,13 +1381,18 @@ export class Engine {
|
||||
edited = line
|
||||
}
|
||||
if (reply.kind === "session" || reply.kind === "project") {
|
||||
for (const pattern of decision.always) {
|
||||
// Learned: an approval never overrides a deny somebody wrote (see evaluate).
|
||||
const rule: Rule = { permission: request.permission, pattern, action: "allow", learned: true }
|
||||
// Learned: an approval never overrides a deny somebody wrote (see evaluate). A path outside
|
||||
// the project gets its external_directory rule too, for this session only (rules.md §3).
|
||||
for (const { rule, save } of alwaysRules(request, decision)) {
|
||||
this.sessionRules.push(rule)
|
||||
// Written to the project, it would come back as an ordinary rule and win over such a
|
||||
// deny by coming last; it stays for this session only instead.
|
||||
if (reply.kind === "project" && !shadowsDeny(rule, this.o.perm.rules)) this.o.persistRule?.({ permission: rule.permission, pattern, action: "allow" })
|
||||
// A project file that cannot be written (a link, read-only) keeps the rule for the session:
|
||||
// the approved call still runs.
|
||||
if (reply.kind === "project" && save && !shadowsDeny(rule, this.o.perm.rules))
|
||||
try {
|
||||
this.o.persistRule?.({ permission: rule.permission, pattern: rule.pattern, action: "allow" })
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Database } from "bun:sqlite"
|
||||
import { mkdirSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, ownFile, paths } from "../config/paths.ts"
|
||||
import type { Message, Usage } from "../provider/types.ts"
|
||||
import { isNote } from "./prefix.ts"
|
||||
|
||||
@@ -109,9 +108,11 @@ export class Store {
|
||||
readonly db: Database
|
||||
|
||||
constructor(file = join(paths.data, "sessions.db")) {
|
||||
if (file !== ":memory:") mkdirSync(paths.data, { recursive: true })
|
||||
if (file !== ":memory:") ownDir(paths.data)
|
||||
this.db = new Database(file, { create: true })
|
||||
this.db.run("PRAGMA journal_mode = WAL")
|
||||
// Every conversation is in here: the person's alone, an existing file tightened too.
|
||||
if (file !== ":memory:") for (const f of [file, `${file}-wal`, `${file}-shm`]) ownFile(f)
|
||||
// Several writers share this file: every terminal, the service, and in the service one
|
||||
// connection per session it holds. Without a timeout a write that meets another's lock fails at
|
||||
// once with "database is locked" — a delete from the web UI among them, which the instance then
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// One way out for every front end. Every command the program starts runs in a process group of
|
||||
// its own; the groups are remembered here, and whatever is left in one when the program ends is
|
||||
// stopped — TERM, a grace, KILL — whether the end is /quit, the last line of `lembas run`, or a
|
||||
// signal. A program meant to outlive lembas has to leave its group (`setsid`); `nohup cmd &`
|
||||
// alone does not.
|
||||
const groups = new Set<number>()
|
||||
let hooked = false
|
||||
let prune: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
/** Whether anything is left in the process group. */
|
||||
export function groupAlive(pgid: number): boolean {
|
||||
try {
|
||||
process.kill(-pgid, 0)
|
||||
return true
|
||||
} catch (e) {
|
||||
// EPERM: something is there that is not ours to signal.
|
||||
return (e as NodeJS.ErrnoException).code === "EPERM"
|
||||
}
|
||||
}
|
||||
|
||||
/** Remember a command's process group (its leader's pid) until it is empty. */
|
||||
export function trackGroup(pgid: number | undefined): void {
|
||||
if (!pgid) return
|
||||
groups.add(pgid)
|
||||
if (!hooked) {
|
||||
hooked = true
|
||||
process.once("exit", () => killGroupsSync())
|
||||
}
|
||||
// An emptied group is forgotten soon, so that its number is never signalled once it could
|
||||
// belong to something else.
|
||||
prune ??= setInterval(() => {
|
||||
for (const g of groups) if (!groupAlive(g)) groups.delete(g)
|
||||
if (!groups.size) {
|
||||
clearInterval(prune)
|
||||
prune = undefined
|
||||
}
|
||||
}, 15_000)
|
||||
prune.unref?.()
|
||||
}
|
||||
|
||||
/** The groups that still hold a process. */
|
||||
export function liveGroups(): number[] {
|
||||
for (const g of groups) if (!groupAlive(g)) groups.delete(g)
|
||||
return [...groups]
|
||||
}
|
||||
|
||||
/** TERM every group left, a grace, then KILL — synchronously: nothing runs after this. */
|
||||
export function killGroupsSync(graceMs = 300): number {
|
||||
const alive = liveGroups()
|
||||
if (!alive.length) return 0
|
||||
for (const g of alive)
|
||||
try {
|
||||
process.kill(-g, "SIGTERM")
|
||||
} catch {}
|
||||
const until = Date.now() + graceMs
|
||||
while (Date.now() < until && alive.some(groupAlive)) Bun.sleepSync(20)
|
||||
for (const g of alive)
|
||||
try {
|
||||
process.kill(-g, "SIGKILL")
|
||||
} catch {}
|
||||
groups.clear()
|
||||
return alive.length
|
||||
}
|
||||
|
||||
export const SIGNAL_EXIT = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 } as const
|
||||
|
||||
/** The signals of a front end with no screen (`lembas run`): the first Ctrl+C is `gentle` — stop
|
||||
* the turn, stop waiting; a second Ctrl+C, or one SIGTERM or SIGHUP, is the hard way: `last`
|
||||
* (say what is being stopped), every group killed, and the signal's exit status. Returns what
|
||||
* takes the handlers off again. */
|
||||
export function onSignals(o: { gentle(): void; last?(left: number): void }): () => void {
|
||||
let interrupted = false
|
||||
const hard = (sig: keyof typeof SIGNAL_EXIT) => {
|
||||
const left = liveGroups().length
|
||||
try {
|
||||
o.last?.(left)
|
||||
} catch {}
|
||||
killGroupsSync()
|
||||
process.exit(SIGNAL_EXIT[sig])
|
||||
}
|
||||
const int = () => {
|
||||
if (interrupted) return hard("SIGINT")
|
||||
interrupted = true
|
||||
o.gentle()
|
||||
}
|
||||
const term = () => hard("SIGTERM")
|
||||
const hup = () => hard("SIGHUP")
|
||||
process.on("SIGINT", int)
|
||||
process.on("SIGTERM", term)
|
||||
process.on("SIGHUP", hup)
|
||||
return () => {
|
||||
process.off("SIGINT", int)
|
||||
process.off("SIGTERM", term)
|
||||
process.off("SIGHUP", hup)
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -6,6 +6,7 @@
|
||||
//
|
||||
// Where they are found, a same-named skill in an earlier place winning:
|
||||
// .agent/skills/ (a trusted project) → ~/.config/lembas/skills/ → config skills.external_dirs
|
||||
import { within as inDir } from "../within.ts"
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"
|
||||
import { platform } from "node:os"
|
||||
import { basename, join, relative } from "node:path"
|
||||
@@ -199,7 +200,7 @@ export function within(dir: string, p: string): boolean {
|
||||
try {
|
||||
const real = join(realpathSync(head), ...rest)
|
||||
const base = realpathSync(dir)
|
||||
return real === base || real.startsWith(base + "/")
|
||||
return inDir(real, base)
|
||||
} catch {
|
||||
const up = join(head, "..")
|
||||
if (up === head) return false
|
||||
|
||||
+4
-10
@@ -5,21 +5,15 @@ import { LOOP } from "../harness.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import { evaluate, type Context as PermContext, type Decision, type PermissionRequest, type Rule, type ToolClass } from "../permission/evaluate.ts"
|
||||
import MODES_JSON from "../../harness/permission/modes.json"
|
||||
|
||||
const TEXTS = LOOP.team.texts
|
||||
const fill = (t: string, v: Record<string, string>) => fillPrompt(t, v)
|
||||
|
||||
/** Loosest first (permission/modes.json `order`). */
|
||||
export const MODE_ORDER = MODES_JSON.order as Mode[]
|
||||
const rank = (m: Mode) => MODE_ORDER.indexOf(m)
|
||||
|
||||
/** a is looser than b. */
|
||||
export const looser = (a: Mode, b: Mode) => rank(a) < rank(b)
|
||||
/** a is stricter than b. */
|
||||
export const stricter = (a: Mode, b: Mode) => rank(a) > rank(b)
|
||||
/** The modes' order and its questions: permission/modes.ts, the one table. */
|
||||
export { MODE_ORDER, looser, stricter } from "../permission/modes.ts"
|
||||
import { looser, stricter, stricterMode } from "../permission/modes.ts"
|
||||
/** The stricter of the two. */
|
||||
export const strictest = (a: Mode, b: Mode): Mode => (stricter(a, b) ? a : b)
|
||||
export const strictest = (a: Mode, b: Mode): Mode => stricterMode(a, b)
|
||||
|
||||
export const REQUEST_KINDS = LOOP.team.request.kinds as ToolClass[]
|
||||
|
||||
|
||||
+3
-2
@@ -180,9 +180,10 @@ export async function terminalCommand(args: string[]): Promise<number> {
|
||||
const hold = holdWindow(window)
|
||||
if ("taken" in hold) return err(fillPrompt(S.texts.taken, { window, pid: String(hold.taken) })), S.exit.taken
|
||||
process.once("exit", () => hold.release())
|
||||
// A context that is refused does not keep the display from starting (spec 3.15.0): it starts and
|
||||
// says so, as /terminal-context in a running one does.
|
||||
const shown = values["terminal-context"] !== undefined ? contextFromFlag(values["terminal-context"], env) : undefined
|
||||
if (shown && "refused" in shown) return hold.release(), err(shown.refused), S.exit.usage
|
||||
await (await import("../lembas/webui.ts")).refreshWebui({ timeoutMs: 3000 })
|
||||
const { runSurface } = await import("../tui/terminal_surface.tsx")
|
||||
return runSurface({ cwd: process.cwd(), window, terminal: env, ...(pane !== undefined ? { pane } : {}), ...(values.model ? { model: values.model } : {}), ...(mode ? { mode } : {}), ...(values.new ? { fresh: true } : {}), ...(shown ? { terminalContext: shown.context } : {}) }, hold)
|
||||
return runSurface({ cwd: process.cwd(), window, terminal: env, ...(pane !== undefined ? { pane } : {}), ...(values.model ? { model: values.model } : {}), ...(mode ? { mode } : {}), ...(values.new ? { fresh: true } : {}), ...(shown && "context" in shown ? { terminalContext: shown.context } : {}), ...(shown && "refused" in shown ? { contextRefused: shown.refused } : {}) }, hold)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { LOOP } from "../harness.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { ESCAPES, saidDir } from "./context.ts"
|
||||
import { completeModel } from "./models.ts"
|
||||
import { secretIn } from "./secrets.ts"
|
||||
import { gate, settingsFor, type Effective } from "./settings.ts"
|
||||
|
||||
const C = LOOP.terminal.complete
|
||||
@@ -22,7 +23,6 @@ const TX = C.texts
|
||||
export type Shell = "bash" | "zsh" | "fish"
|
||||
export const isShell = (s: unknown): s is Shell => typeof s === "string" && (C.shells as string[]).includes(s)
|
||||
|
||||
const SECRET = new RegExp(C.history_secret, "i")
|
||||
const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g
|
||||
|
||||
/** The commands of a history file's text, oldest first, as the shell writes them. */
|
||||
@@ -57,7 +57,7 @@ export function recentCommands(text: string, shell: Shell, max = C.history_lines
|
||||
const out: string[] = []
|
||||
for (const raw of historyCommands(text, shell)) {
|
||||
const line = raw.replace(ESCAPES, "").replace(CONTROL, " ").replace(/\s+/g, " ").trim().slice(0, C.history_line_max_chars)
|
||||
if (!line || SECRET.test(line) || out[out.length - 1] === line) continue
|
||||
if (!line || secretIn(line, "history") || out[out.length - 1] === line) continue
|
||||
out.push(line)
|
||||
}
|
||||
return out.slice(-max)
|
||||
@@ -155,6 +155,10 @@ export async function completeCommand(args: string[], io: CompleteIO): Promise<n
|
||||
debug(`shell ${values.shell}, cwd ${cwd ?? "not given"}, timeout ${timeout} ms, standard input ${Buffer.byteLength(io.stdin, "utf8")} bytes`)
|
||||
const line = typedLine(io.stdin)
|
||||
if (line === undefined) return debug(`nothing to complete: the line is ${!io.stdin.replace(/\r?\n$/, "").trim() ? "empty" : /[\r\n]/.test(io.stdin.replace(/\r?\n$/, "")) ? "of several lines" : `longer than ${C.line_max_bytes} bytes`} — no request`), 0
|
||||
// A line that looks as if it holds a secret is not sent anywhere (loop.json terminal.secrets):
|
||||
// said, and the rule named in the debug line — never the line.
|
||||
const secret = secretIn(line)
|
||||
if (secret) return debug(`the line looks as if it holds a secret (rule ${secret}) — no request`), io.err(TX.secret), 0
|
||||
// The terminal's settings for that directory (acp.md, *The terminal's settings*): where
|
||||
// autocomplete was set to false nothing is asked. A default is not a refusal.
|
||||
let settings: Effective | undefined
|
||||
|
||||
+36
-19
@@ -5,12 +5,15 @@
|
||||
// Everything in the file is somebody's screen: text a program printed, which may be anything.
|
||||
// It is made plain here, cut to the spec's limits, and told to the model as data. Nothing is
|
||||
// done because of it.
|
||||
import { ownDirs } from "../config/paths.ts"
|
||||
import { within } from "../within.ts"
|
||||
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, unlinkSync } from "node:fs"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { dirname, isAbsolute, join, relative, resolve, basename } from "node:path"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { paneId } from "./env.ts"
|
||||
import { SECRET_PLACEHOLDER, secretIn } from "./secrets.ts"
|
||||
|
||||
const C = LOOP.terminal.context
|
||||
const TX = C.texts
|
||||
@@ -63,7 +66,7 @@ export function contextRoots(env: Record<string, string | undefined> = process.e
|
||||
return [...new Set(roots.filter((r): r is string => !!r && r !== "/"))]
|
||||
}
|
||||
|
||||
const inside = (p: string, dir: string) => p === dir || p.startsWith(dir.endsWith("/") ? dir : dir + "/")
|
||||
const inside = within
|
||||
|
||||
/** What the file system says of a path, as much as the rule reads: injected in the conformance
|
||||
* cases, the real one otherwise. */
|
||||
@@ -96,7 +99,7 @@ const diskFacts = (): FileFacts => ({
|
||||
|
||||
/** Whether the file may be read (and then removed) — or the refusal, which leaves it where it is
|
||||
* (`kind: file`). Answers the path to open: the real directory and the file's own name. */
|
||||
export function judgeFile(path: string, o: { cwd: string; roots: string[]; facts?: FileFacts }): string {
|
||||
export function judgeFile(path: string, o: { cwd: string; roots: string[]; own?: string[]; facts?: FileFacts }): string {
|
||||
const facts = o.facts ?? diskFacts()
|
||||
const said = path.trim()
|
||||
if (!said) throw new TerminalContextError("no_path")
|
||||
@@ -106,6 +109,9 @@ export function judgeFile(path: string, o: { cwd: string; roots: string[]; facts
|
||||
const at = join(dir, basename(abs))
|
||||
const roots = o.roots.map((r) => facts.real(r)).filter((r): r is string => r !== undefined && r !== "/")
|
||||
if (!roots.some((r) => inside(dir, r))) throw new TerminalContextError("outside", { path: abs })
|
||||
// Never one of the CLI's own files (its sessions, its sign-in), which lie inside those roots.
|
||||
const own = (o.own ?? []).flatMap((d) => [d, facts.real(d)]).filter((d): d is string => d !== undefined && d !== "/")
|
||||
if (own.some((d) => inside(at, d) || inside(abs, d))) throw new TerminalContextError("own", { path: abs })
|
||||
const st = facts.stat(at)
|
||||
if (!st) throw new TerminalContextError("missing", { path: abs })
|
||||
if (st.kind === "link") throw new TerminalContextError("symlink", { path: abs })
|
||||
@@ -115,19 +121,17 @@ export function judgeFile(path: string, o: { cwd: string; roots: string[]; facts
|
||||
return at
|
||||
}
|
||||
|
||||
/** Read the file once and remove it: its text, or the refusal. A path that may not be read is
|
||||
* left where it is; one that was opened is removed whatever it held. */
|
||||
export function takeFile(path: string, o: { cwd?: string; roots?: string[] } = {}): string {
|
||||
const at = judgeFile(path, { cwd: o.cwd ?? process.cwd(), roots: o.roots ?? contextRoots() })
|
||||
/** Read the file once: its text, and the path it was read at — or the refusal. Nothing is
|
||||
* removed here: `takeContext` removes a file only once it has read as a context. */
|
||||
export function readContextFile(path: string, o: { cwd?: string; roots?: string[]; own?: string[] } = {}): { text: string; at: string } {
|
||||
const at = judgeFile(path, { cwd: o.cwd ?? process.cwd(), roots: o.roots ?? contextRoots(), own: o.own ?? ownDirs() })
|
||||
let fd: number
|
||||
try {
|
||||
// Not through a link put there since it was looked at.
|
||||
fd = openSync(at, constants.O_RDONLY | constants.O_NOFOLLOW)
|
||||
// Not through a link put there since it was looked at, and not waiting on a pipe.
|
||||
fd = openSync(at, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
||||
} catch {
|
||||
throw new TerminalContextError("missing", { path: at })
|
||||
}
|
||||
let text: string
|
||||
let tooLarge = false
|
||||
try {
|
||||
// The file opened is the file judged: a regular one of the person's own.
|
||||
const s = fstatSync(fd)
|
||||
@@ -141,19 +145,28 @@ export function takeFile(path: string, o: { cwd?: string; roots?: string[] } = {
|
||||
n += got
|
||||
if (n >= buf.length) break
|
||||
}
|
||||
tooLarge = n > C.max_bytes
|
||||
text = buf.subarray(0, n).toString("utf8")
|
||||
if (n > C.max_bytes) throw new TerminalContextError("too_large", { max: String(C.max_bytes / 1024) })
|
||||
return { text: buf.subarray(0, n).toString("utf8"), at }
|
||||
} finally {
|
||||
closeSync(fd)
|
||||
}
|
||||
// Read once: what a screen showed does not stay on disk.
|
||||
}
|
||||
|
||||
/** Read the file, check it is a context, and only then remove it (spec 3.15.0): what a screen
|
||||
* showed does not stay on disk, and a file that is not a context — a wrong path, somebody's own
|
||||
* file — is never deleted. Throws TerminalContextError with the sentence otherwise. */
|
||||
export function takeContext(path: string, o: { cwd?: string; roots?: string[]; own?: string[] } = {}): TerminalContext {
|
||||
const { text, at } = readContextFile(path, o)
|
||||
const context = parseContext(text)
|
||||
try {
|
||||
unlinkSync(at)
|
||||
} catch {}
|
||||
if (tooLarge) throw new TerminalContextError("too_large", { max: String(C.max_bytes / 1024) })
|
||||
return text
|
||||
return context
|
||||
}
|
||||
|
||||
/** A context that names no command and no screen: valid, and nothing to add. */
|
||||
export const emptyContext = (c: TerminalContext) => !c.blocks.length && !c.screen
|
||||
|
||||
// ── what the file says ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const ESCAPES = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[PX^_][^\x1b]*(?:\x1b\\)?|\x1b[ -/]*[0-~]?|\u009b[0-?]*[ -/]*[@-~]/g
|
||||
@@ -217,10 +230,14 @@ export function parseContext(text: string, limits: Partial<Pick<typeof C, "block
|
||||
for (const b of Array.isArray(f.blocks) ? f.blocks : []) {
|
||||
if (!b || typeof b !== "object" || Array.isArray(b)) continue
|
||||
const r = b as Record<string, unknown>
|
||||
const command = typeof r.command === "string" ? plainText(r.command).trim().slice(0, L.command_max_chars) : ""
|
||||
if (!command) continue
|
||||
const typed = typeof r.command === "string" ? plainText(r.command).trim().slice(0, L.command_max_chars) : ""
|
||||
if (!typed) continue
|
||||
// A command that looks as if it holds a secret reaches the model as a placeholder, and what it
|
||||
// printed not at all (loop.json terminal.secrets, spec 3.15.0).
|
||||
const secret = secretIn(typed) !== undefined
|
||||
const command = secret ? SECRET_PLACEHOLDER : typed
|
||||
const exit = typeof r.exit === "number" && Number.isInteger(r.exit) ? r.exit : null
|
||||
const out = typeof r.output === "string" ? plainText(r.output) : ""
|
||||
const out = typeof r.output === "string" && !secret ? plainText(r.output) : ""
|
||||
const cut = out ? tail(out, L.output_max_lines, L.output_max_chars) : undefined
|
||||
const seq = typeof r.seq === "number" && Number.isInteger(r.seq) && r.seq >= 0 && r.seq <= C.seq_max ? r.seq : undefined
|
||||
blocks.push({ command, exit, ...(cut?.text ? { output: cut.text, ...(cut.elided ? { elided: cut.elided } : {}) } : {}), ...(seq !== undefined ? { seq } : {}) })
|
||||
@@ -228,7 +245,6 @@ export function parseContext(text: string, limits: Partial<Pick<typeof C, "block
|
||||
const dropped = Math.max(0, blocks.length - L.blocks_max)
|
||||
const screenText = typeof f.screen === "string" ? plainText(f.screen) : ""
|
||||
const screen = screenText ? tail(screenText, L.screen_max_lines, L.screen_max_chars).text : ""
|
||||
if (!blocks.length && !screen) throw new TerminalContextError("empty")
|
||||
// A host is said only by version 2 (a file of version 1 that names one is as it always was).
|
||||
const v2 = f.version === 2
|
||||
return {
|
||||
@@ -288,6 +304,7 @@ export function chip(c: TerminalContext, o: { next?: boolean; replaced?: boolean
|
||||
const n = c.blocks.length
|
||||
const parts = [n === 1 ? TX.chip_command : n > 1 ? fillPrompt(TX.chip_commands, { count: String(n) }) : "", c.screen ? TX.chip_screen : ""].filter(Boolean)
|
||||
if (c.increment && !parts.length) return TX.chip_nothing
|
||||
if (!parts.length) return TX.chip_empty
|
||||
const said = fillPrompt(c.increment && !c.increment.first ? TX.chip_new : TX.chip, { what: parts.join(TX.chip_and), pane: c.pane !== undefined ? fillPrompt(TX.chip_pane, { pane: String(c.pane) }) : "" })
|
||||
return said + (o.next ? TX.chip_next : "") + (o.replaced ? TX.chip_replaced : "")
|
||||
}
|
||||
+53
-5
@@ -1,8 +1,14 @@
|
||||
// A terminal as the client (harness/acp.md, spec 3.12.0): recognising a LLeMbas terminal by the
|
||||
// environment it gives every pane, and what this CLI says of itself to one.
|
||||
//
|
||||
// Without LLEMBAS_TTY nothing of src/terminal/ applies: no user var is written, the two tools are
|
||||
// in no list, and a context file is refused in words.
|
||||
// Without LLEMBAS_TERM (or, from a terminal before the rename, LLEMBAS_TTY) nothing of
|
||||
// src/terminal/ applies: no user var is written, the two tools are in no list, and a context file
|
||||
// is refused in words.
|
||||
//
|
||||
// The terminal was renamed (contract 4, spec 3.15.0). THIS FILE IS THE ONE PLACE that knows there
|
||||
// are two spellings: `terminalNames` says which family of names holds in an environment, and
|
||||
// `isMagic` reads a file's first line in either. Nothing else in the program names a variable, a
|
||||
// directory or a first line of the terminal's.
|
||||
import { isAbsolute } from "node:path"
|
||||
import { HARNESS_VERSION, LOOP } from "../harness.ts"
|
||||
import { VERSION } from "../version.ts"
|
||||
@@ -12,6 +18,8 @@ const T = LOOP.terminal
|
||||
export interface TerminalEnv {
|
||||
/** The terminal's version, as it said it. */
|
||||
version: string
|
||||
/** The terminal said it in the names from before the rename (`LLEMBAS_TTY…`). */
|
||||
before?: true
|
||||
/** The pane this process runs in, where the terminal named one. */
|
||||
pane?: number
|
||||
/** The absolute path of the terminal's command-line program, where it named one. */
|
||||
@@ -28,15 +36,55 @@ export function paneId(v: unknown): number | undefined {
|
||||
return typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= T.context.pane_max ? v : undefined
|
||||
}
|
||||
|
||||
/** The names that hold in an environment: the variables the terminal set and the directory its
|
||||
* files are in by default. */
|
||||
export interface TerminalNames {
|
||||
version: string
|
||||
pane: string
|
||||
executable: string
|
||||
status_dir: string
|
||||
dir_name: string
|
||||
/** The family from before the rename. */
|
||||
before: boolean
|
||||
}
|
||||
|
||||
const NAMES: TerminalNames = { version: T.env.version, pane: T.env.pane, executable: T.env.executable, status_dir: T.env.status_dir, dir_name: T.status.dir_name, before: false }
|
||||
const NAMES_BEFORE: TerminalNames = { ...T.env.before, dir_name: T.status.dir_name_before, before: true }
|
||||
|
||||
/** Which family of names holds here — a whole family, never a mix: the new one when its version
|
||||
* variable is set, else the one from before the rename when that one's is, else the new one
|
||||
* (not a terminal). A renamed terminal started from inside an old one inherits the old one's
|
||||
* variables: its own must not be completed from them. */
|
||||
export function terminalNames(env: Record<string, string | undefined> = process.env): TerminalNames {
|
||||
if ((env[NAMES.version] ?? "").trim()) return NAMES
|
||||
if ((env[NAMES_BEFORE.version] ?? "").trim()) return NAMES_BEFORE
|
||||
return NAMES
|
||||
}
|
||||
|
||||
/** The names of the family a recognised terminal spoke in: decided once, when it was recognised. */
|
||||
export const namesOf = (t: TerminalEnv): TerminalNames => (t.before ? NAMES_BEFORE : NAMES)
|
||||
|
||||
/** Every variable either family sets: what a child that must not look like it runs in the
|
||||
* terminal has taken out of its environment. */
|
||||
export const TERMINAL_VARIABLES: readonly string[] = [NAMES, NAMES_BEFORE].flatMap((n) => [n.version, n.pane, n.executable, n.status_dir])
|
||||
|
||||
/** Whether a file's first line is the mark of `what`, in the new spelling or the one before. */
|
||||
export function isMagic(line: string | undefined, what: "status" | "input"): boolean {
|
||||
const m = what === "status" ? T.status : T.place.input
|
||||
return line === `${m.magic}=${m.version}` || line === `${m.magic_before}=${m.version}`
|
||||
}
|
||||
|
||||
/** The terminal this process runs in, or undefined: not one (`kind: env`). */
|
||||
export function terminalEnv(env: Record<string, string | undefined> = process.env): TerminalEnv | undefined {
|
||||
const version = (env[T.env.version] ?? "").trim()
|
||||
const N = terminalNames(env)
|
||||
const version = (env[N.version] ?? "").trim()
|
||||
if (!version) return undefined
|
||||
const pane = paneId(env[T.env.pane] ?? "")
|
||||
const exe = env[T.env.executable] ?? ""
|
||||
const pane = paneId(env[N.pane] ?? "")
|
||||
const exe = env[N.executable] ?? ""
|
||||
const executable = exe && isAbsolute(exe) && !CONTROL.test(exe) ? exe : undefined
|
||||
return {
|
||||
version: version.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, 100),
|
||||
...(N.before ? { before: true as const } : {}),
|
||||
...(pane !== undefined ? { pane } : {}),
|
||||
...(executable ? { executable } : {}),
|
||||
multiplexed: T.env.multiplexers.some((k) => !!env[k]),
|
||||
|
||||
@@ -261,3 +261,15 @@ export function askKeys(e: Expecting): string {
|
||||
if (e.question) return `${e.question.options > 1 ? `1-${e.question.options}` : e.question.options === 1 ? "1" : ""}${S.keys.deny}`
|
||||
return ""
|
||||
}
|
||||
|
||||
const ID = S.ask_id
|
||||
const ID_WORD = new RegExp(`^\\d{1,${ID.digits_max}}$`)
|
||||
|
||||
/** An answer command's argument (`kind: ask_id`): the id it names first, if any, and the rest.
|
||||
* `/answer` takes the option alone as before: one word is the option, two are the id and it. */
|
||||
export function splitAskId(arg: string, answer = false): { id?: string; rest: string } {
|
||||
const words = arg.trim().split(/\s+/).filter(Boolean)
|
||||
if (answer && words.length < 2) return { rest: words.join(" ") }
|
||||
if (words[0] && ID_WORD.test(words[0])) return { id: words[0], rest: words.slice(1).join(" ") }
|
||||
return { rest: words.join(" ") }
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { accessSync, constants, statSync } from "node:fs"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { cannotClose, plainText, tail } from "./context.ts"
|
||||
import { terminalNames } from "./env.ts"
|
||||
|
||||
const T = LOOP.terminal.tools
|
||||
const TX = T.texts
|
||||
@@ -59,7 +60,7 @@ export function runProgram(o: { argv: string[]; stdin?: string; what: string; si
|
||||
if (!statSync(exe).isFile()) throw new Error("not a file")
|
||||
accessSync(exe, constants.X_OK)
|
||||
} catch {
|
||||
return Promise.reject(new PaneError(fillPrompt(TX.no_program, { path: exe })))
|
||||
return Promise.reject(new PaneError(fillPrompt(TX.no_program, { path: exe, variable: terminalNames(o.env ?? process.env).executable })))
|
||||
}
|
||||
const seconds = T.timeout_seconds
|
||||
return new Promise<string>((res, rej) => {
|
||||
|
||||
+11
-7
@@ -11,6 +11,7 @@ import { LOOP } from "../harness.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { plainText } from "./context.ts"
|
||||
import { asked, lastLine, outputAfter, wrapped, type StatusRecord } from "./status.ts"
|
||||
import { isMagic } from "./env.ts"
|
||||
|
||||
const P = LOOP.terminal.place
|
||||
const R = LOOP.terminal.run
|
||||
@@ -29,7 +30,7 @@ export const inputFile = (dir: string, pane: number) => join(dir, fillPrompt(P.i
|
||||
/** The terminal's input mark as text, or undefined: unreadable is no mark. */
|
||||
export function parseInputMark(text: string): InputMark | undefined {
|
||||
const lines = text.replace(/\r\n?/g, "\n").split("\n")
|
||||
if (lines[0] !== `${P.input.magic}=${P.input.version}`) return undefined
|
||||
if (!isMagic(lines[0], "input")) return undefined
|
||||
const f: Record<string, string> = {}
|
||||
for (const l of lines.slice(1)) {
|
||||
const at = l.indexOf("=")
|
||||
@@ -69,7 +70,9 @@ const PROMPT_END = new RegExp(P.prompt_end, "u")
|
||||
* `by`: what decided. Nothing is ever added to what the person typed. */
|
||||
export function promptFree(o: { record: StatusRecord | undefined; input?: InputMark | undefined; paneText: string }): { free: boolean; by: "record" | "input" | "line" } {
|
||||
if (o.record?.state === "running") return { free: false, by: "record" }
|
||||
if (o.input && o.record && o.input.id === o.record.id && o.input.seq === o.record.seq) return { free: !o.input.typed, by: "input" }
|
||||
// A record that came by user var is the remote shell's word (spec 3.15.0): it may say a command
|
||||
// runs — a refusal costs nothing — but never that the prompt is free; the pane is read instead.
|
||||
if (o.input && o.record && !o.record.uservar && o.input.id === o.record.id && o.input.seq === o.record.seq) return { free: !o.input.typed, by: "input" }
|
||||
return { free: PROMPT_END.test(lastLine(o.paneText)), by: "line" }
|
||||
}
|
||||
|
||||
@@ -90,7 +93,7 @@ export function judgePlaced(before: { id: string; seq: number }, now: StatusReco
|
||||
}
|
||||
|
||||
export type PlacedOutcome =
|
||||
| { kind: "ran"; exit?: number; other?: true; host?: string; ms: number }
|
||||
| { kind: "ran"; exit?: number; other?: true; host?: string; ms: number; reported?: true }
|
||||
| { kind: "dismissed"; ms: number }
|
||||
| { kind: "left"; ms: number; stopped?: true }
|
||||
| { kind: "running"; ms: number }
|
||||
@@ -124,9 +127,10 @@ export async function awaitPlaced(o: {
|
||||
let ranAt: number | undefined
|
||||
let nextLook = 0
|
||||
for (;;) {
|
||||
const j = judgePlaced(o.before, o.read(), ranAt !== undefined)
|
||||
const rec = o.read()
|
||||
const j = judgePlaced(o.before, rec, ranAt !== undefined)
|
||||
const ms = now() - start
|
||||
if (j?.outcome === "ran") return { kind: "ran", ...(j.exit !== undefined ? { exit: j.exit } : {}), ...(j.other ? { other: true as const } : {}), ...(j.host ? { host: j.host } : {}), ms }
|
||||
if (j?.outcome === "ran") return { kind: "ran", ...(j.exit !== undefined ? { exit: j.exit } : {}), ...(j.other ? { other: true as const } : {}), ...(j.host ? { host: j.host } : {}), ms, ...(rec?.uservar ? { reported: true as const } : {}) }
|
||||
if (j?.outcome === "dismissed") return { kind: "dismissed", ms }
|
||||
if (j?.outcome === "running" && ranAt === undefined) {
|
||||
// The person pressed Enter: from here it is a typed command that is waited for.
|
||||
@@ -215,8 +219,8 @@ export function placedAnswer(o: { pane: number; command: string; outcome: Placed
|
||||
const shown = o.paneText !== undefined ? outputAfter(o.paneText, line.how === "edited" ? line.actual : o.command) : ""
|
||||
if (out.kind === "ran") {
|
||||
const end = out.other ? fillPrompt(X.other_shell, { host: out.host ? fillPrompt(R.texts.host, { host: out.host }) : "" }) : out.exit === undefined ? X.no_status : fillPrompt(X.exit, { exit: String(out.exit) })
|
||||
const known = out.exit !== undefined && !out.other
|
||||
return { output: [head, how, end, wrapped(o.pane, shown, R.texts.output)].filter(Boolean).join("\n"), fact, ...(known ? { exit: out.exit } : {}) }
|
||||
const known = out.exit !== undefined && !out.other && !out.reported
|
||||
return { output: [head, how, out.reported ? `${end} ${R.texts.unverified}` : end, wrapped(o.pane, shown, R.texts.output)].filter(Boolean).join("\n"), fact, ...(known ? { exit: out.exit } : {}) }
|
||||
}
|
||||
if (out.kind === "waiting") return { output: [head, how, fillPrompt(X.waiting, { what: out.what === "password" ? R.texts.what_password : R.texts.what_confirm }), wrapped(o.pane, shown, R.texts.shown)].filter(Boolean).join("\n"), fact: R.texts.fact_waiting }
|
||||
return { output: [head, how, fillPrompt(X.running, { seconds: String(Math.round(out.ms / 1000)) }), wrapped(o.pane, shown, R.texts.shown)].filter(Boolean).join("\n"), fact: R.texts.fact_running }
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Whether a shell line looks as if it holds a secret (harness loop.json `terminal.secrets`, spec
|
||||
// 3.15.0): the one table for the line typed into `lembas complete --shell`, its history, and the
|
||||
// command blocks of a terminal context. A match keeps the line from leaving the machine — no
|
||||
// request, the history line left out, the command replaced before the model sees it.
|
||||
import { LOOP } from "../harness.ts"
|
||||
|
||||
const S = LOOP.terminal.secrets
|
||||
|
||||
type Entry = { name: string; pattern: string; ignore_case: boolean; only?: string }
|
||||
const ENTRIES = (S.patterns as Entry[]).map((e) => ({ ...e, re: new RegExp(e.pattern, e.ignore_case ? "i" : "") }))
|
||||
const WORD = new RegExp(`[${S.token.chars}]{${S.token.min_length},}`, "g")
|
||||
|
||||
/** Shannon entropy of a string, in bits per character. */
|
||||
function bitsPerChar(s: string): number {
|
||||
const counts = new Map<string, number>()
|
||||
for (const c of s) counts.set(c, (counts.get(c) ?? 0) + 1)
|
||||
let h = 0
|
||||
for (const n of counts.values()) {
|
||||
const p = n / s.length
|
||||
h -= p * Math.log2(p)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
/** A word that looks like a generated key: long, of key characters, mixed, and random enough. */
|
||||
export function secretToken(line: string): string | undefined {
|
||||
for (const m of line.matchAll(WORD)) {
|
||||
const w = m[0]
|
||||
if (/\d/.test(w) && /[a-z]/.test(w) && /[A-Z]/.test(w) && bitsPerChar(w) >= S.token.min_bits_per_char) return w
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** The name of the rule a line matches (for a debug line: never the line itself), or undefined.
|
||||
* `history`: a line of the shell's history, where the broader entries apply too. */
|
||||
export function secretIn(line: string, where: "line" | "history" = "line"): string | undefined {
|
||||
for (const e of ENTRIES) if ((!e.only || e.only === where) && e.re.test(line)) return e.name
|
||||
return secretToken(line) ? "token" : undefined
|
||||
}
|
||||
|
||||
export const SECRET_PLACEHOLDER: string = S.placeholder
|
||||
+12
-9
@@ -1,9 +1,9 @@
|
||||
// A session's side of a LLeMbas terminal (harness/acp.md, *A terminal as the client*): the
|
||||
// context the person sent that still waits for their next message, and the pane they showed —
|
||||
// the one pane terminal_run and terminal_read act on.
|
||||
import { chip, parseContext, takeFile, terminalBlock, TerminalContextError, type TerminalContext } from "./context.ts"
|
||||
import { chip, emptyContext, takeContext, terminalBlock, TerminalContextError, type TerminalContext } from "./context.ts"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import type { TerminalEnv } from "./env.ts"
|
||||
import { namesOf, type TerminalEnv } from "./env.ts"
|
||||
import { increment, typedByAgent, type Seen } from "./increment.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { inputFile, readInputMark, settle, type InputMark, type Placement } from "./place.ts"
|
||||
@@ -38,15 +38,18 @@ export class TerminalSession {
|
||||
private root: string,
|
||||
) {}
|
||||
|
||||
/** Read a context file (once; it is removed), keep it for the next message, and answer the
|
||||
* transcript's line. Throws TerminalContextError with the sentence when it is not used. */
|
||||
/** Read a context file (once; removed once it read as a context), keep it for the next message,
|
||||
* and answer the transcript's line. Throws TerminalContextError with the sentence when it is
|
||||
* not used. */
|
||||
receive(path: string, o: { cwd?: string; next?: boolean } = {}): string {
|
||||
const context = parseContext(takeFile(path, { cwd: o.cwd }))
|
||||
const context = takeContext(path, { cwd: o.cwd })
|
||||
return this.accept(context, o)
|
||||
}
|
||||
|
||||
/** A context already read (the command line read it before the session existed). */
|
||||
accept(context: TerminalContext, o: { next?: boolean } = {}): string {
|
||||
// No command and no screen: a valid context with nothing in it (spec 3.15.0). Nothing waits.
|
||||
if (emptyContext(context)) return chip(context)
|
||||
if (context.pane !== undefined) this.shown = { pane: context.pane, ...(context.cwd ? { cwd: context.cwd } : {}) }
|
||||
else if (context.cwd && this.shown) this.shown = { ...this.shown, cwd: context.cwd }
|
||||
if (this.seen) {
|
||||
@@ -106,7 +109,7 @@ export class TerminalSession {
|
||||
settlePlaced(): { placement: Placement; result: ReturnType<typeof settle> } | undefined {
|
||||
const p = this.placement
|
||||
if (!p || this.placedWaiting) return undefined
|
||||
const result = settle(p, readStatus(statusFile(statusDir(), p.pane)))
|
||||
const result = settle(p, readStatus(statusFile(statusDir(process.env, undefined, namesOf(this.env)), p.pane)))
|
||||
if (result.state === "still") return { placement: p, result }
|
||||
this.setPlaced(undefined)
|
||||
// The model is told with the person's next message, whoever saw it first.
|
||||
@@ -119,7 +122,7 @@ export class TerminalSession {
|
||||
|
||||
/** The terminal's input mark for the pane the tools act on, where the terminal writes one. */
|
||||
input(): InputMark | undefined {
|
||||
return this.shown ? readInputMark(inputFile(statusDir(), this.shown.pane)) : undefined
|
||||
return this.shown ? readInputMark(inputFile(statusDir(process.env, undefined, namesOf(this.env)), this.shown.pane)) : undefined
|
||||
}
|
||||
|
||||
/** What goes with the person's next message: the context that waits, and any note. */
|
||||
@@ -151,7 +154,7 @@ export class TerminalSession {
|
||||
|
||||
/** The status record of the pane the tools act on, as it is now. */
|
||||
status(): StatusRecord | undefined {
|
||||
return this.shown ? readStatus(statusFile(statusDir(), this.shown.pane)) : undefined
|
||||
return this.shown ? readStatus(statusFile(statusDir(process.env, undefined, namesOf(this.env)), this.shown.pane)) : undefined
|
||||
}
|
||||
|
||||
get pending(): boolean {
|
||||
@@ -184,7 +187,7 @@ export class TerminalSession {
|
||||
export function contextFromFlag(path: string, env: TerminalEnv | undefined, cwd = process.cwd()): { context: TerminalContext } | { refused: string } {
|
||||
if (!env) return { refused: LOOP.terminal.context.refusals.not_terminal }
|
||||
try {
|
||||
return { context: parseContext(takeFile(path, { cwd })) }
|
||||
return { context: takeContext(path, { cwd }) }
|
||||
} catch (e) {
|
||||
if (e instanceof TerminalContextError) return { refused: e.message }
|
||||
throw e
|
||||
|
||||
+13
-9
@@ -12,11 +12,11 @@ import { isAbsolute, join } from "node:path"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { cannotClose, plainText, tail } from "./context.ts"
|
||||
import { isMagic, terminalNames, type TerminalNames } from "./env.ts"
|
||||
|
||||
const ST = LOOP.terminal.status
|
||||
const R = LOOP.terminal.run
|
||||
const T = LOOP.terminal.tools
|
||||
const ENV = LOOP.terminal.env
|
||||
|
||||
export interface StatusRecord {
|
||||
id: string
|
||||
@@ -35,14 +35,15 @@ export interface StatusRecord {
|
||||
}
|
||||
|
||||
/** Where the panes' status records are: what the terminal said, else the runtime directory's
|
||||
* `llembas-tty`, else the state directory's. */
|
||||
export function statusDir(env: Record<string, string | undefined> = process.env, home = homedir()): string {
|
||||
* directory of the terminal's name, else the state directory's. The name is the family's that
|
||||
* holds in `env` (env.ts `terminalNames`): a terminal from before the rename keeps its own. */
|
||||
export function statusDir(env: Record<string, string | undefined> = process.env, home = homedir(), N: TerminalNames = terminalNames(env)): string {
|
||||
const abs = (v: string | undefined) => (v && isAbsolute(v) && !/[\u0000-\u001f\u007f]/.test(v) ? v : undefined)
|
||||
const said = abs(env[ENV.status_dir])
|
||||
const said = abs(env[N.status_dir])
|
||||
if (said) return said
|
||||
const run = abs(env.XDG_RUNTIME_DIR)
|
||||
if (run) return join(run, ST.dir_name)
|
||||
return join(abs(env.XDG_STATE_HOME) ?? join(home, ".local", "state"), ST.dir_name)
|
||||
if (run) return join(run, N.dir_name)
|
||||
return join(abs(env.XDG_STATE_HOME) ?? join(home, ".local", "state"), N.dir_name)
|
||||
}
|
||||
|
||||
export const statusFile = (dir: string, pane: number) => join(dir, fillPrompt(ST.file, { pane: String(pane) }))
|
||||
@@ -54,7 +55,7 @@ export function parseStatus(text: string): StatusRecord | undefined {
|
||||
if (Buffer.byteLength(text, "utf8") > ST.max_bytes) return undefined
|
||||
const lines = text.replace(/\r\n?/g, "\n").split("\n")
|
||||
while (lines.length && lines[lines.length - 1] === "") lines.pop()
|
||||
if (lines[0] !== `${ST.magic}=${ST.version}`) return undefined
|
||||
if (!isMagic(lines[0], "status")) return undefined
|
||||
const f: Record<string, string> = {}
|
||||
for (const l of lines.slice(1)) {
|
||||
const at = l.indexOf("=")
|
||||
@@ -189,7 +190,8 @@ export function wrapped(pane: number, text: string, head: string): string {
|
||||
}
|
||||
|
||||
export type RunOutcome =
|
||||
| { kind: "ended"; exit?: number; other?: true; host?: string; ms: number }
|
||||
/** `reported`: the record that said so came by user var — the remote shell's word only. */
|
||||
| { kind: "ended"; exit?: number; other?: true; host?: string; ms: number; reported?: true }
|
||||
| { kind: "running"; ms: number }
|
||||
| { kind: "waiting"; what: "password" | "confirm"; ms: number }
|
||||
| { kind: "typed" }
|
||||
@@ -220,7 +222,7 @@ export async function awaitCommand(o: {
|
||||
if (rec) seen = true
|
||||
const end = judgeAwait(o.before, rec)
|
||||
const ms = now() - start
|
||||
if (end) return { kind: "ended", ...(end.exit !== undefined ? { exit: end.exit } : {}), ...(end.other ? { other: true as const } : {}), ...(end.host ? { host: end.host } : {}), ms }
|
||||
if (end) return { kind: "ended", ...(end.exit !== undefined ? { exit: end.exit } : {}), ...(end.other ? { other: true as const } : {}), ...(end.host ? { host: end.host } : {}), ms, ...(rec?.uservar ? { reported: true as const } : {}) }
|
||||
// A shell that writes no record: nothing will ever say the end.
|
||||
if (!seen && ms >= R.input_first_ms) return { kind: "typed" }
|
||||
if (ms >= waitMs || o.signal?.aborted) return { kind: "running", ms }
|
||||
@@ -254,6 +256,8 @@ export function runAnswer(o: { pane: number; command: string; outcome: RunOutcom
|
||||
: out.exit === undefined
|
||||
? fillPrompt(X.ended_no_status, { ...base, took: secs(out.ms) })
|
||||
: fillPrompt(X.ended, { ...base, took: secs(out.ms), exit: String(out.exit) })
|
||||
// What came only by user var is what anything printing to the pane could have said.
|
||||
if (out.reported) return { output: [`${head} ${X.unverified}`, wrapped(o.pane, shown, X.output)].filter(Boolean).join("\n"), fact: X.fact_ended }
|
||||
const known = out.exit !== undefined && !out.other
|
||||
return { output: [head, wrapped(o.pane, shown, X.output)].filter(Boolean).join("\n"), fact: known ? "" : X.fact_ended, ...(known ? { exit: out.exit } : {}) }
|
||||
}
|
||||
|
||||
+33
-6
@@ -9,7 +9,7 @@ import { clipEnd } from "../tui/layout.ts"
|
||||
import type { Item, View } from "../tui/state.ts"
|
||||
import { callAfter } from "../tui/transcript.ts"
|
||||
import { receiveContext } from "./command.ts"
|
||||
import { askKeys, SurfaceInput, surfaceMode, type Action, type Expecting, type Scroll } from "./input.ts"
|
||||
import { askKeys, splitAskId, SurfaceInput, surfaceMode, type Action, type Expecting, type Scroll } from "./input.ts"
|
||||
import { plainValue } from "./uservars.ts"
|
||||
import { setWindowSession } from "./windows.ts"
|
||||
|
||||
@@ -114,16 +114,35 @@ export function createSurface(app: App, view: View, hooks: SurfaceHooks) {
|
||||
if (e.question) return e.question.options ? fillPrompt(X.hint_question, { count: String(e.question.options), deny: k.deny }) : fillPrompt(X.hint_question_free, { deny: k.deny })
|
||||
return ""
|
||||
}
|
||||
/** `lembas_ask`: the kind, the keys, the text — one line. */
|
||||
/** Each approval, and each question of a card, has an id of its own (spec 3.15.0): an answer
|
||||
* that names one decides only that. Kept by the object asked, so a new one gets a new id. */
|
||||
const ids = new WeakMap<object, string[]>()
|
||||
let lastId = 0
|
||||
const idFor = (o: object, at = 0): string => {
|
||||
const list = ids.get(o) ?? []
|
||||
// A whole number, new for each (1 to digits_max digits, then round again).
|
||||
list[at] ??= String((lastId = (lastId % (10 ** S.ask_id.digits_max - 1)) + 1))
|
||||
ids.set(o, list)
|
||||
return list[at]!
|
||||
}
|
||||
/** The id of what is asked now, if anything with one is. */
|
||||
const askedId = (): string | undefined => {
|
||||
const p = view.state.pending
|
||||
if (p) return idFor(p)
|
||||
const q = question()
|
||||
return q ? idFor(q.req as object, q.at) : undefined
|
||||
}
|
||||
/** `lembas_ask`: the kind, the keys, the id, the text — one line. */
|
||||
const ask = (): string => {
|
||||
const e = expecting()
|
||||
const p = view.state.pending
|
||||
if (p) return plainValue(`approval ${askKeys(e)} ${p.tool}: ${p.request.command ?? p.request.patterns.join(" ")}`)
|
||||
const cut = (v: string) => plainValue(v, undefined, S.ask_id.ellipsis)
|
||||
if (p) return cut(`approval#${idFor(p)} ${askKeys(e)} ${p.tool}: ${p.request.command ?? p.request.patterns.join(" ")}`)
|
||||
const q = question()
|
||||
if (q) return plainValue(`question ${askKeys(e)} ${q.q.question}`)
|
||||
if (q) return cut(`question#${idFor(q.req as object, q.at)} ${askKeys(e)} ${q.q.question}`)
|
||||
// A command stands at the person's prompt: nothing to answer, a kind of its own.
|
||||
const placed = app.terminal?.placed
|
||||
if (placed) return plainValue(fillPrompt(PX.ask, { command: placed.command }))
|
||||
if (placed) return plainValue(fillPrompt(PX.ask, { command: placed.command }), undefined, S.ask_id.ellipsis)
|
||||
return ""
|
||||
}
|
||||
/** The command a call is waiting for the person to run or dismiss, if any. */
|
||||
@@ -174,7 +193,15 @@ export function createSurface(app: App, view: View, hooks: SurfaceHooks) {
|
||||
if (kind === "session" && !p.decision.always.length) return view.info(fillPrompt(X.no_always, { allow: S.keys.allow, deny: S.keys.deny }), "warn")
|
||||
p.resolve({ kind })
|
||||
}
|
||||
const command = async (name: string, arg: string) => {
|
||||
const command = async (name: string, given: string) => {
|
||||
let arg = given
|
||||
if (name === "approve" || name === "always" || name === "deny" || name === "answer") {
|
||||
// An answer bound to what was shown: an id that is not the one asked now decides nothing.
|
||||
const said = splitAskId(given, name === "answer")
|
||||
const now = askedId()
|
||||
if (said.id && said.id !== now) return view.info(fillPrompt(X.wrong_id, { said: said.id, now: now ? ` (${now})` : "" }), "warn")
|
||||
arg = said.rest
|
||||
}
|
||||
if (name === "terminal-context") return receiveContext({ app, view }, arg)
|
||||
if (name === "quit") return hooks.quit()
|
||||
if (name === "stop") return void (busy() && app.engine.cancel())
|
||||
|
||||
@@ -16,17 +16,18 @@ export type TerminalState = "idle" | "waiting" | "thinking" | "tools" | "writing
|
||||
|
||||
/** A value as it is published: control characters and line separators a space, white space run
|
||||
* together, the ends trimmed, at most `max` UTF-8 bytes — cut at a character boundary. */
|
||||
export function plainValue(v: unknown, max = S.max_bytes): string {
|
||||
export function plainValue(v: unknown, max = S.max_bytes, ellipsis = ""): string {
|
||||
const s = String(v ?? "")
|
||||
.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
const b = Buffer.from(s, "utf8")
|
||||
if (b.length <= max) return s
|
||||
let at = max
|
||||
// A value that is cut may end in a mark saying so (lembas_ask: the rest is in the display).
|
||||
let at = max - Buffer.byteLength(ellipsis, "utf8")
|
||||
// Not into the middle of a character: its continuation bytes are 10xxxxxx.
|
||||
while (at > 0 && (b[at]! & 0xc0) === 0x80) at--
|
||||
return b.subarray(0, at).toString("utf8").trimEnd()
|
||||
return b.subarray(0, at).toString("utf8").trimEnd() + ellipsis
|
||||
}
|
||||
|
||||
/** The bytes that set one user var: `ESC ] 1337 ; SetUserVar=name=base64 ESC \`. */
|
||||
|
||||
@@ -128,7 +128,7 @@ export function formatAnswers(req: QuestionRequest, reply: QuestionReply): strin
|
||||
const final = req.questions.map((_, i) => i + 1).filter((n) => !back.includes(n))
|
||||
lines.push(
|
||||
"",
|
||||
`${final.length ? `Q${final.join(", Q")} ${final.length > 1 ? "are" : "is"} answered. ` : ""}Instead of answering Q${back.join(", Q")}, the user asked you a question. Answer it in your reply, then call question again with only Q${back.join(", Q")} — adjusted if your answer changes the options.`,
|
||||
`${final.length ? `Q${final.join(", Q")} ${final.length > 1 ? "are" : "is"} answered. ` : ""}Instead of answering Q${back.join(", Q")}, the user asked you a question. Answer it in your reply, then call ask_user again with only Q${back.join(", Q")} — adjusted if your answer changes the options.`,
|
||||
)
|
||||
}
|
||||
return lines.join("\n")
|
||||
|
||||
+17
-3
@@ -4,6 +4,7 @@ import { absPath, defineTool, showPath, ToolError, truncate } from "./tool.ts"
|
||||
import { duration } from "../duration.ts"
|
||||
import { described } from "../harness.ts"
|
||||
import { commandLine } from "../jobs/note.ts"
|
||||
import { groupAlive, trackGroup } from "../shutdown.ts"
|
||||
|
||||
// git run by the model reads a repository's own config, which can name programs to run (an external
|
||||
// diff, an fsmonitor, a pager) — and "git diff", "git show", "git status" are allowed unasked. These
|
||||
@@ -33,6 +34,10 @@ export const ENV = {
|
||||
...Object.fromEntries(GIT_SAFE.flatMap(([k, v], i) => [[`GIT_CONFIG_KEY_${i}`, k], [`GIT_CONFIG_VALUE_${i}`, v]])),
|
||||
}
|
||||
|
||||
/** Said when a command ended and left a program running (harness loop.json has no text for it:
|
||||
* the CLI's own). */
|
||||
export const LEFT_BEHIND = "the command ended but left a program running; it is not followed as a job and is stopped when lembas exits — start a long-running program with background: true, or with setsid if it must outlive lembas"
|
||||
|
||||
/** How long a background start waits for a first line before returning. */
|
||||
const FIRST_OUTPUT_MS = 100
|
||||
/** Output a foreground command keeps; past it the oldest goes, as a job's buffer does. */
|
||||
@@ -86,6 +91,7 @@ export const bashTool = defineTool({
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: ENV,
|
||||
})
|
||||
trackGroup(child.pid)
|
||||
let out = ""
|
||||
const onData = (d: Buffer) => {
|
||||
out += d.toString()
|
||||
@@ -93,6 +99,7 @@ export const bashTool = defineTool({
|
||||
}
|
||||
child.stdout!.on("data", onData)
|
||||
let killed = ""
|
||||
let spawnError = ""
|
||||
const kill = (why: string) => {
|
||||
killed = why
|
||||
try {
|
||||
@@ -132,7 +139,10 @@ export const bashTool = defineTool({
|
||||
exited = true
|
||||
setTimeout(() => settle({ kind: "exit", code: signal ? null : code }), 300).unref()
|
||||
})
|
||||
child.on("error", () => settle({ kind: "exit", code: null }))
|
||||
child.on("error", (e) => {
|
||||
spawnError = `could not start: ${e.message}`
|
||||
settle({ kind: "exit", code: null })
|
||||
})
|
||||
const timer = setTimeout(() => {
|
||||
if (timeline) settle({ kind: "timeout", why: "timeout" })
|
||||
else kill(`timed out after ${duration(timeout, true)}`)
|
||||
@@ -158,10 +168,14 @@ export const bashTool = defineTool({
|
||||
meta: { job: job.id, cwd: showPath(cwd, ctx) },
|
||||
}
|
||||
}
|
||||
// The call is over: nothing more is read from whatever still holds the pipe.
|
||||
child.stdout!.off("data", onData)
|
||||
const code = outcome.code
|
||||
const status = killed ? killed : code === null ? "stopped (SIGTERM)" : `exit ${code}`
|
||||
const status = killed ? killed : spawnError ? spawnError : code === null ? "stopped (SIGTERM)" : `exit ${code}`
|
||||
// The shell is gone, but something it started is not (`server &`): it is in no job list.
|
||||
const left = !killed && child.pid && groupAlive(child.pid) ? `\n[${LEFT_BEHIND}]` : ""
|
||||
return {
|
||||
output: `${truncate(out.trimEnd()) || "(no output)"}\n\n[${status}]`,
|
||||
output: `${truncate(out.trimEnd()) || "(no output)"}\n\n[${status}]${left}`,
|
||||
title: `${line} · ${status}`,
|
||||
isError: killed !== "" || code !== 0,
|
||||
meta: { exit: code, cwd: showPath(cwd, ctx) },
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
import { within } from "../within.ts"
|
||||
import { existsSync, readFileSync, realpathSync } from "node:fs"
|
||||
import { unsafeProjectFile } from "../project/safe.ts"
|
||||
import { readdir, stat } from "node:fs/promises"
|
||||
@@ -74,7 +75,7 @@ export function readBody(text: string, offset?: number, limit?: number): { body:
|
||||
/** OpenCode's "nearby instructions": reading a file under a directory with its own AGENTS.md or
|
||||
* CLAUDE.md hands the model that file, once per session. The root's is already in the prompt. */
|
||||
function nearbyInstructions(file: string, ctx: import("./tool.ts").ToolContext): string {
|
||||
if (!ctx.instructionsSeen || !file.startsWith(ctx.root + "/")) return ""
|
||||
if (!ctx.instructionsSeen || !within(file, ctx.root)) return ""
|
||||
const out: string[] = []
|
||||
for (let dir = dirname(file); dir.startsWith(ctx.root) && dir !== ctx.root; dir = dirname(dir)) {
|
||||
const hit = ["AGENTS.md", "CLAUDE.md"].map((f) => join(dir, f)).find((f) => existsSync(f))
|
||||
|
||||
+33
-4
@@ -1,5 +1,6 @@
|
||||
import { within } from "../within.ts"
|
||||
import { stat } from "node:fs/promises"
|
||||
import { join, relative } from "node:path"
|
||||
import { isAbsolute, join, relative } from "node:path"
|
||||
import { z } from "zod"
|
||||
import { absPath, defineTool, showPath, ToolError, truncate, type ToolContext } from "./tool.ts"
|
||||
import { described } from "../harness.ts"
|
||||
@@ -35,6 +36,12 @@ async function listFiles(dir: string, glob: string | undefined, ctx: ToolContext
|
||||
return out
|
||||
}
|
||||
|
||||
/** What a search says of the files it did not return lines from (filesystem.md). */
|
||||
export function leftOut(files: string[]): string {
|
||||
const shown = files.slice(0, 5).join(", ") + (files.length > 5 ? ", …" : "")
|
||||
return `(${files.length} ${files.length === 1 ? "file with matches was" : "files with matches were"} left out: reading ${files.length === 1 ? "it" : "them"} needs the person's approval — use read on one to ask: ${shown})`
|
||||
}
|
||||
|
||||
export const globTool = defineTool({
|
||||
...described("glob"),
|
||||
access: "glob",
|
||||
@@ -75,16 +82,36 @@ export const grepTool = defineTool({
|
||||
async run(a, ctx) {
|
||||
const target = absPath(a.path ?? ".", ctx)
|
||||
const lines: string[] = []
|
||||
// A search over a directory reads every file in it. Nothing of a file `read` would ask about
|
||||
// or refuse comes back (the permission above judged the directory, not each file): it is
|
||||
// left out, and said — the model can `read` one, which asks.
|
||||
const left = new Set<string>()
|
||||
const judged = new Map<string, boolean>()
|
||||
const keep = (abs: string): boolean => {
|
||||
// Outside the project the person answered for the directory itself (external_directory),
|
||||
// and the read rules are the project's.
|
||||
if (abs === target || !ctx.mayRead || !within(abs, ctx.root)) return true
|
||||
let ok = judged.get(abs)
|
||||
if (ok === undefined) judged.set(abs, (ok = ctx.mayRead(abs)))
|
||||
if (!ok) left.add(abs)
|
||||
return ok
|
||||
}
|
||||
if (!(await stat(target).catch(() => undefined))) throw new ToolError(`No such file or directory: ${target}`)
|
||||
if (hasRg) {
|
||||
const args = ["rg", "--line-number", "--no-heading", "--color", "never", "--hidden", "--glob", "!.git", "--max-columns", "400", "--max-columns-preview"]
|
||||
// --null: the file's name ends at a NUL, so it is read exactly, whatever it holds.
|
||||
const args = ["rg", "--line-number", "--no-heading", "--with-filename", "--null", "--color", "never", "--hidden", "--glob", "!.git", "--max-columns", "400", "--max-columns-preview"]
|
||||
if (a.ignore_case) args.push("-i")
|
||||
if (a.literal) args.push("-F")
|
||||
if (a.include) args.push("--glob", a.include)
|
||||
args.push("-e", a.pattern, target)
|
||||
const r = await run(args, ctx.root, ctx.signal)
|
||||
if (r.code > 1) throw new ToolError(r.err.trim() || `rg exited ${r.code}`)
|
||||
for (const l of r.out.split("\n")) if (l) lines.push(l)
|
||||
for (const l of r.out.split("\n")) {
|
||||
if (!l) continue
|
||||
const nul = l.indexOf("\0")
|
||||
if (nul < 0) lines.push(l)
|
||||
else if (keep(isAbsolute(l.slice(0, nul)) ? l.slice(0, nul) : join(ctx.root, l.slice(0, nul)))) lines.push(`${l.slice(0, nul)}:${l.slice(nul + 1)}`)
|
||||
}
|
||||
} else {
|
||||
let re: RegExp
|
||||
try {
|
||||
@@ -95,6 +122,7 @@ export const grepTool = defineTool({
|
||||
const st = await stat(target)
|
||||
const files = st.isDirectory() ? (await listFiles(target, a.include, ctx)).map((f) => join(target, f)) : [target]
|
||||
for (const f of files) {
|
||||
if (!keep(f)) continue
|
||||
const text = await Bun.file(f).text().catch(() => "")
|
||||
if (text.includes("\0")) continue
|
||||
text.split("\n").forEach((l, i) => {
|
||||
@@ -106,7 +134,8 @@ export const grepTool = defineTool({
|
||||
const more = lines.length > 200 ? `\n(${lines.length - 200} more matches — narrow the search)` : ""
|
||||
// The commonest miss: searching for code text like `len(x)` as a regex, where ( ) are a group.
|
||||
const hint = !lines.length && !a.literal && /[()[\]{}.*+?|\\^$]/.test(a.pattern) ? " The pattern is a regular expression; to search for the text as written, set literal: true." : ""
|
||||
return { output: truncate(lines.slice(0, 200).join("\n") || "No matches." + hint) + more, title: `/${a.pattern}/ · ${lines.length} matches`, meta: { hits: lines.length } }
|
||||
const out = left.size ? `\n${leftOut([...left])}` : ""
|
||||
return { output: truncate(lines.slice(0, 200).join("\n") || "No matches." + hint) + more + out, title: `/${a.pattern}/ · ${lines.length} matches`, meta: { hits: lines.length } }
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
// first" — and it changes the setting, with the user's approval (settings_tool: ask, the default).
|
||||
// Only what config/settings.ts marks for the agent; never permission rules, the hardline, MCP,
|
||||
// connections, updates, or this tool's own gate. A less strict mode is asked about every time.
|
||||
import { MODE_RANK } from "../permission/modes.ts"
|
||||
import { z } from "zod"
|
||||
import { describe, findSetting, parseValue, show, type Entry } from "../config/settings.ts"
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import { defineTool, ToolError, type ToolContext } from "./tool.ts"
|
||||
import { described } from "../harness.ts"
|
||||
|
||||
const MODE_RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
|
||||
|
||||
const line = (e: Entry) =>
|
||||
`${e.def.key} = ${show(e.value) || "(unset)"} [${e.source}]${e.def.values ? ` — ${e.def.values.join(" | ")}` : ""}${e.def.agent ? "" : " — user only"}${e.def.reload ? " — after a restart" : ""}`
|
||||
|
||||
+9
-3
@@ -1,3 +1,5 @@
|
||||
import { relativeWithin } from "../within.ts"
|
||||
import { within } from "../within.ts"
|
||||
import { existsSync } from "node:fs"
|
||||
import { isAbsolute, relative, resolve } from "node:path"
|
||||
import { z } from "zod"
|
||||
@@ -18,6 +20,11 @@ export interface ToolContext {
|
||||
/** mtime (ms) of each file when it was last read or written by a tool, to detect outside edits. */
|
||||
fileStamps: Map<string, number>
|
||||
bashTimeoutMs: number
|
||||
/** Whether `read` of this file would run without asking, by the rules and the mode as they are
|
||||
* now (set by the engine per step). A tool that reads many files on the model's behalf (grep)
|
||||
* returns nothing of a file this refuses (filesystem.md, *A search does not read what `read`
|
||||
* would ask about*). Absent: nothing is filtered (a caller with no permissions of its own). */
|
||||
mayRead?: (abs: string) => boolean
|
||||
/** Instruction files (AGENTS.md / CLAUDE.md) the model has already been given. */
|
||||
instructionsSeen?: Set<string>
|
||||
/** Ask the user questions (the ask_user tool). Absent where nobody can answer. */
|
||||
@@ -272,15 +279,14 @@ export function absPath(p: string, ctx: ToolContext): string {
|
||||
// relative reading does not exist and the absolute one does, inside the project, take that.
|
||||
if (!existsSync(rel)) {
|
||||
const abs = resolve("/", p)
|
||||
if ((abs === ctx.root || abs.startsWith(ctx.root + "/")) && existsSync(abs)) return abs
|
||||
if (within(abs, ctx.root) && existsSync(abs)) return abs
|
||||
}
|
||||
return rel
|
||||
}
|
||||
|
||||
/** For display and rule matching: relative to the root when inside it. */
|
||||
export function showPath(abs: string, ctx: ToolContext): string {
|
||||
const rel = relative(ctx.root, abs)
|
||||
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : abs
|
||||
return relativeWithin(resolve(abs), resolve(ctx.root)) || abs
|
||||
}
|
||||
|
||||
export class ToolError extends Error {}
|
||||
|
||||
+1
-1
@@ -633,7 +633,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
/** A custom command: its expanded body is the prompt; its frontmatter's model and mode hold for
|
||||
* this one prompt. */
|
||||
const runCustom = (cc: CustomCommand, arg: string, typed: string) =>
|
||||
sendAs(expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline), typed, {
|
||||
sendAs(expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline, (line) => app.engine.judgeCommand(line, app.project.root)), typed, {
|
||||
// @files come from what was typed, not from the command's own text.
|
||||
attachFrom: arg,
|
||||
model: cc.model,
|
||||
|
||||
+18
-9
@@ -1,5 +1,6 @@
|
||||
// Built-in slash commands; custom markdown commands, skills and MCP prompts join them in the
|
||||
// palette.
|
||||
import { initProjectDir } from "../project/init.ts"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import { terminalCommands } from "../terminal/command.ts"
|
||||
import { join } from "node:path"
|
||||
@@ -1077,7 +1078,7 @@ export const COMMANDS: Command[] = [
|
||||
{
|
||||
name: "login",
|
||||
args: "[address]",
|
||||
description: "sign in to a LLeMbas instance: its models, voice and search (again: read them now)",
|
||||
description: "sign in to a LLeMbas server: its models, voice and search (again: read them now)",
|
||||
async run(c, arg) {
|
||||
const { codeInstructions, instances, isWebuiEntry, login, loginSummary, sync } = await import("../lembas/login.ts")
|
||||
const known = instances()
|
||||
@@ -1100,7 +1101,7 @@ export const COMMANDS: Command[] = [
|
||||
}
|
||||
if (arg.trim()) return go(arg.trim())
|
||||
c.openDialog({
|
||||
title: "Log in to a LLeMbas instance",
|
||||
title: "Sign in to a LLeMbas server",
|
||||
options: Object.values(known).map((i) => ({ label: i.base_url, value: i.base_url, description: `refresh ${i.connection}${i.email ? ` · ${i.email}` : ""}` })),
|
||||
custom: { label: "Log in to", onSubmit: (text) => void go(text) },
|
||||
onSelect: (value) => void go(value),
|
||||
@@ -1109,13 +1110,13 @@ export const COMMANDS: Command[] = [
|
||||
},
|
||||
{
|
||||
name: "usage",
|
||||
description: "your account's usage on the LLeMbas instance: this month's tokens and cost, this device's tokens",
|
||||
description: "your account's usage on the LLeMbas server: this month's tokens and cost, this device's tokens",
|
||||
async run(c) {
|
||||
// /v1/usage of the account this machine is logged in to.
|
||||
const { accountUsage, spendLabel, usageLines } = await import("../lembas/personal.ts")
|
||||
try {
|
||||
const r = await accountUsage()
|
||||
if (!r) return c.view.info("no usage to show — not logged in to one LLeMbas instance (/login), or it does not keep any")
|
||||
if (!r) return c.view.info("no usage to show — not signed in to a LLeMbas server (/login), or it does not keep any")
|
||||
c.setSpend?.(spendLabel(r.usage))
|
||||
c.view.info(usageLines(r.connection, r.usage).join("\n"))
|
||||
} catch (e) {
|
||||
@@ -1218,21 +1219,21 @@ export const COMMANDS: Command[] = [
|
||||
{
|
||||
name: "logout",
|
||||
args: "[connection]",
|
||||
description: "sign out of a LLeMbas instance, and remove the connection login wrote",
|
||||
description: "sign out of the LLeMbas server, and remove what login wrote",
|
||||
async run(c, arg) {
|
||||
const { instances, logout } = await import("../lembas/login.ts")
|
||||
const known = Object.keys(instances())
|
||||
const go = async (name: string) => {
|
||||
try {
|
||||
const r = await logout(name)
|
||||
c.view.info(`Signed out of ${name}${r.revoked ? "" : " here — the instance could not be told; revoke it under User → Security → Devices there"}.${r.modelLeft ? ` config.yaml still starts on ${r.modelLeft}; /model picks another.` : ""}`)
|
||||
c.view.info(`Signed out of ${name}${r.revoked ? "" : " here — the server could not be told; revoke it under User → Security → Devices there"}.${r.modelLeft ? ` config.yaml still starts on ${r.modelLeft}; /model picks another.` : ""}`)
|
||||
c.reload()
|
||||
} catch (e) {
|
||||
c.view.info(`logout: ${(e as Error).message}`, "warn")
|
||||
}
|
||||
}
|
||||
if (arg.trim()) return go(arg.trim())
|
||||
if (!known.length) return c.view.info("not logged in to any LLeMbas instance — /login <address>")
|
||||
if (!known.length) return c.view.info("not signed in to a LLeMbas server — /login <address>")
|
||||
if (known.length === 1) return go(known[0]!)
|
||||
c.openDialog({ title: "Sign out of", options: known.map((k) => ({ label: k, value: k })), onSelect: (v) => void go(v) })
|
||||
},
|
||||
@@ -1394,10 +1395,18 @@ export const COMMANDS: Command[] = [
|
||||
},
|
||||
{
|
||||
name: "trust",
|
||||
description: "trust this project (its .agent config is then honoured — restart to apply)",
|
||||
description: "trust this project: its project directory is made if there is none, and its config honoured after /reload",
|
||||
run(c) {
|
||||
setTrust(c.app.project.root, "trusted")
|
||||
c.view.info(`${c.app.project.root} is trusted. Restart lembas to load its config.`)
|
||||
// The first-run screen makes the project directory only when it is answered "trust"; a
|
||||
// project first opened read-only gets it here, so /tasks, /decide and the rest have a place.
|
||||
let made: string[] = []
|
||||
try {
|
||||
made = initProjectDir(c.app.project)
|
||||
} catch (e) {
|
||||
c.view.info(`could not make ${c.app.project.dir}: ${(e as Error).message}`, "warn")
|
||||
}
|
||||
c.view.info(`${c.app.project.root} is trusted${made.length ? ` (made ${made.join(", ")})` : ""}. /reload loads its config.`)
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -77,7 +77,7 @@ export function Setup(p: { error: Error; onRetry: () => void; onQuit: () => void
|
||||
>
|
||||
<box flexDirection="column">
|
||||
<text fg={c().title} attributes={TextAttributes.BOLD}>
|
||||
Log in to a LLeMbas instance
|
||||
Sign in to a LLeMbas server
|
||||
</text>
|
||||
<text fg={c().text}>Address: {address()}▏</text>
|
||||
</box>
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
import { appendFileSync, mkdirSync, readFileSync } from "node:fs"
|
||||
import { appendFileSync, readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { ownDir, ownFile, paths } from "../config/paths.ts"
|
||||
|
||||
// Prompt history, shared across projects, newest last: ~/.local/state/lembas/history.jsonl.
|
||||
const MAX = 500
|
||||
@@ -24,8 +24,9 @@ export class History {
|
||||
if (!text.trim() || this.items[this.items.length - 1] === text) return this.reset()
|
||||
this.items.push(text)
|
||||
try {
|
||||
mkdirSync(paths.state, { recursive: true })
|
||||
appendFileSync(this.file, JSON.stringify(text) + "\n")
|
||||
ownDir(paths.state)
|
||||
appendFileSync(this.file, JSON.stringify(text) + "\n", { mode: 0o600 })
|
||||
ownFile(this.file)
|
||||
} catch {}
|
||||
this.reset()
|
||||
}
|
||||
|
||||
@@ -94,6 +94,8 @@ export function Boot(p: { options: TuiOptions; onQuit: () => void; onReload?: (a
|
||||
} else if (r.kind === "available") view.info(`LLeMbas CLI ${r.version} is out — \`lembas update\` installs it`)
|
||||
else if (r.kind === "failed" && r.security) view.info(`update refused: ${r.reason}`, "warn")
|
||||
else if (r.kind === "failed" && r.repeated) view.info(`${r.reason} — lembas update says more`, "warn")
|
||||
// A new major version is never installed unasked (it may need a newer server): said, once an hour at most.
|
||||
if ((r.kind === "current" || r.kind === "available") && r.major) view.info(`LLeMbas CLI ${r.major}, a new major version, is out — \`lembas update v${r.major}\` installs it`)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ export interface SurfaceOptions {
|
||||
fresh?: boolean
|
||||
terminal: TerminalEnv
|
||||
terminalContext?: TerminalContext
|
||||
/** The sentence a context named on the command line was refused with: said, and the display runs. */
|
||||
contextRefused?: string
|
||||
store?: Store | false
|
||||
/** false: the conversation is named from its first question only (tests). */
|
||||
modelTitles?: false
|
||||
@@ -83,6 +85,7 @@ export function openSurface(o: SurfaceOptions, view: View, bus: Bus): { app: App
|
||||
} else if (o.model && app.store && app.engine.sessionId) app.store.setMeta(app.engine.sessionId, MODEL_META, app.engine.model.ref)
|
||||
if (app.engine.sessionId) setWindowSession(o.window, app.engine.sessionId)
|
||||
if (o.terminalContext && app.terminal) view.info(app.terminal.accept(o.terminalContext, { next: true }))
|
||||
if (o.contextRefused) view.info(o.contextRefused, "warn")
|
||||
return { app, resumed: existing !== undefined }
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user