diff --git a/CHANGELOG.md b/CHANGELOG.md index 896027f..7685f06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,73 @@ All notable changes to LLeMbas CLI. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). +## Unreleased + +### Connection — one way for every LLeMbas product to connect + +- **Harness: LLeMbas connection 1** (`harness/connection.md`, `harness/connection.json`; + conformance `address`, `version`, `errors`). The address rule and which address is stored, + discovery and its outcomes, how a product names itself, versions judged both ways and + `min_clients`, a refused token, the link's handshake, close codes and liveness, one reconnect + schedule, state between programs as codes, and the table of conditions, codes and sentences. + +### Added + +- **`code` beside the sentence**, so no program reads English: in the service's `service.json` + (`linked`, `connecting`, `unreachable`, `timeout`, `tls_untrusted`, `not_lembas`, + `server_error`, `server_too_old`, `client_too_old`, `signed_out`, `replaced`, `not_logged_in`, + `disabled`, `stopped`, …) and in the `error` event of `lembas login --json`. +- **A failed turn says so in the prompt's answer** over ACP: `_meta.lembas.error = { code, message }`, + as well as the `error` event (which now carries `code` too). An editor that draws only the + answer no longer shows a turn that ended with nothing and no reason. +- **`User-Agent: llembas-cli/`** on every request to the server and on the link's + upgrade request; the device code's `client_id` is the same string. +- **`serve --stdio` reads and logs the client's `clientInfo`**, answers a client that says a + higher protocol with its own (and `_meta.lembas.notice`, one sentence), and passes on the + server's minimum version for the client's own product (`_meta.lembas.min_client`). +- **`min_clients` in the server's discovery** is honoured: a CLI below the server's minimum is + told so at discovery, with both versions. +- **Liveness on the link:** a WebSocket ping every 30 s; after 60 s with nothing heard the link + is closed and dialled again, instead of saying `linked` for ever on a dead connection. +- **`Retry-After` is honoured** on a 429: a model request is made again after it (twice at most, + capped at five minutes, given up when the turn is stopped), and a sign-in's poll waits it out. + +### Changed + +- **`lembas login` stores the address that was typed**, normalised — not the `base_url` the + server's discovery names, which is now only shown. An existing login keeps working untouched, + and signing in again at the server's real address replaces it rather than adding a second one. + An endpoint discovery names on another origin is not followed, and said. +- **`lembas service` no longer exits when it is not logged in, its token is refused, or a newer + link of the same device took its place.** It stays, says `stopped` with the code, and links + again by itself once `lembas login` has run — a machine nobody sits at recovers without a + restart. (The unit is `Restart=on-failure`: exiting 0 left it down for good, and a missing key + file exited 1 and restarted every ten seconds for ever.) +- **`linked` is said only after the server's `initialize` was answered**, not at the open socket; + connect and handshake together get 30 s. +- **The link's backoff** is 1 s doubling to 60 s with ±20 % jitter, and starts over only after a + link stayed healthy for 30 s: a server that accepts and drops is no longer dialled every second. +- **Close code 4409** (replaced by a newer link of the same device) stops the link with + `replaced` instead of dialling again. +- A discovery that fails is no longer followed by a socket dial that would fail the same way. +- The sentences for a server that cannot be reached, is not LLeMbas, fails, or is too old or too + new are the harness's own (`connection.json`); a 5xx from discovery is "answered N", never + "not a LLeMbas instance". + +### Fixed + +- **After `lembas login` replaced the token, a running service stopped and stayed stopped.** The + key file is read at every dial, and a refusal after the key changed dials again with the new one. +- **A 401 is a sign-out only when it is the server's own** (`WWW-Authenticate: Bearer + realm="lembas"`): a model provider's 401, which the server's `/v1` passes through, is shown + in its own words and no longer reads as "sign in again". +- One rule decides whether two addresses are the same server (`lembas login` again, the token + hand-over, an earlier login to replace), instead of two different comparisons. +- The service's lock file is created exclusively and no longer trusts a recycled pid; the status + file is replaced in one step. +- `serve --stdio` gives up a connection whose client sends a line of more than 64 MB without + ending it, instead of reading it into memory. + ## [2.0.0-beta.17] — 2026-11-27 ### Fixed diff --git a/harness/README.md b/harness/README.md index 2ddccde..980e95c 100644 --- a/harness/README.md +++ b/harness/README.md @@ -35,7 +35,7 @@ page *Harness-parity* in LLeMbas CLI's wiki. | `interactive.md` | Interactive-only models (3.9.0): the field, what counts as a person's own turn, scheduled work that never runs on one, and where a session's background calls (title, compaction) go instead | | `display.md` | Display (3.7.0): one display in every client — a tool call's title, its four states, the duration and the facts beside it, the kinds of block; how `stopped` and `failed` stay on a finished reply; what the approval, question and plan cards offer; numbers in the client's locale | | `quirks.json` | What real servers do, and how both harnesses cope | -| `connection.md`, `connection.json` | LLeMbas connection 1: how every LLeMbas product connects to another — the one address rule, discovery and its outcomes, how a product names itself (`llembas-/`), 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 | +| `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-/`), 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/.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) | diff --git a/harness/acp.md b/harness/acp.md index df4d594..88169cc 100644 --- a/harness/acp.md +++ b/harness/acp.md @@ -24,9 +24,10 @@ change to the protocol is a change here first, then in both projects. could still log in; 3 raises it on purpose, so a 1.x CLI's login is refused there (it says the server speaks protocol 3 and to update the older of the two). - A **2.0 CLI** logs in only where discovery lists 3 (`protocols`, falling back to `protocol`). - To a server that does not, at login and again at every dial of the link, it says *<server> - runs LLeMbas X, which speaks link protocol 1 and 2; this LLeMbas CLI needs a LLeMbas 2.0 server - (protocol 3) — update the server, or use LLeMbas CLI 1.x with it*, and the link stops. + To a server that does not, at login and again at every dial of the link, it says + `server_too_old` in the words of `connection.json` — *<server> runs LLeMbas X, which is too + old for this LLeMbas CLI. Update the server. Or use LLeMbas CLI 1.x with it.* — and the link + stops; to one that lists only higher protocols, `client_too_old` and to update the CLI. - A **2.0 server** closes a link whose hello says 1 or 2 with **4400** and the reason *update LLeMbas CLI to 2.0*; a 1.x CLI stops on 4400 without redialling. A 2.0 CLI's hello says 3, and a 1.x server closes it with 4400 likewise; the CLI stops and says the server needs updating. @@ -125,7 +126,11 @@ Result: `_meta.lembas.protocol` is the agent's own, whatever the client said; `_meta.lembas.notice` is there only for a client that said a higher one — one sentence saying both numbers and that the -lower is used (*Versions*). +lower is used (*Versions*). **`_meta.lembas.min_client`** (on `serve --stdio` only; a version +string, or absent) is the lowest version of the client's own product that the server this device +is logged in to still serves — discovery's `min_clients`, looked up by the product in +`clientInfo.name` (`connection.md` §5). A client below it says so and stops; absent means no +minimum is known. `limits` is `null` on `serve --stdio`. `limits.files_that_run_code` (spec 3.11.0, capability `fs`): whether device files may change files that run code (`remote.files_that_run_code`, *Files that run code*). `limits.scheduled` (spec 3.5.0, capability `scheduled`): whether this device accepts scheduled work now (`remote.scheduled`, *Scheduled work on a linked computer*). `connection` is the device's name for the instance — the @@ -240,7 +245,7 @@ where `_meta.lembas` may also carry: | `undone: { prompt, files } \| null` | `/undo` (null: nothing to undo) | | `mode: string` | `/plan` without a task: the mode now | | `message: string` | a command that had nothing to do (`/review` with no changes), said instead | -| `error: { code: string, message: string }` | **the turn failed**: the model's server could not be reached, refused the sign-in, or failed, and the turn ended with no reply or with part of one. `message` is one line for a person; `code` is one of `connection.json` `codes` — `unreachable`, `timeout`, `tls_untrusted`, `signed_out`, `not_allowed`, `busy`, `server_error`, or `failed` for anything else. `stopReason` is `end_turn` as before (ACP has no stop reason for a failure): **a client shows `error` wherever it shows the reply**, so a turn that ends with nothing says why. The same failure is the `error` event of `_lembas/event` for a client that reads events; the answer is for every client, and for one that reads both it is the same failure, shown once | +| `error: { code: string, message: string }` | **the turn failed**: the model's server could not be reached, refused the sign-in, or failed, and the turn ended with no reply or with part of one. `message` is one line for a person; `code` is one of `connection.json` `codes` — `unreachable`, `timeout`, `tls_untrusted`, `signed_out` (a 401 with the server's own challenge only: `connection.md` §6), `not_allowed`, `busy`, `server_error`, or `failed` for anything else, a model provider's own 401 included. `stopReason` is `end_turn` as before (ACP has no stop reason for a failure): **a client shows `error` wherever it shows the reply**, so a turn that ends with nothing says why. The same failure is the `error` event of `_lembas/event` for a client that reads events; the answer is for every client, and for one that reads both it is the same failure, shown once | ### `session/set_mode` — client → agent diff --git a/harness/conformance/address.json b/harness/conformance/address.json index 3febc50..102bb98 100644 --- a/harness/conformance/address.json +++ b/harness/conformance/address.json @@ -1,5 +1,5 @@ { - "about": "LLeMbas connection 1 (connection.md §1). What a person typed as a server's address, as the base address a product stores, shows and compares. `typed` → `{ base, scheme_given }`, or `{ error: \"invalid_address\" }`. Trimmed; `https://` added when no scheme was typed (a scheme is read in any case of letters); http and https only; the scheme and the host in lower case; a port kept unless it is the scheme's default; path, query, fragment, user name and a trailing slash dropped. `kind: same` — whether two addresses are one server: `a` and `b` → true or false. Equal once both are normalised; and an address typed without a scheme is the same server as one on either scheme. Host names here are ASCII: an internationalised name is not covered by these cases.", + "about": "LLeMbas connection 1 (connection.md §1). What a person typed as a server's address, as the base address a product stores, shows and compares. `typed` → `{ base, scheme_given }`, or `{ error: \"invalid_address\" }`. Trimmed; `https://` added when no scheme was typed (a scheme is read in any case of letters); http and https only; the scheme and the host in lower case; a port kept unless it is the scheme's default; path, query, fragment, user name and a trailing slash dropped. `kind: same` — whether two addresses are one server: `a` and `b` → true or false. Equal once both are normalised; and an address typed without a scheme is the same server as one on either scheme. Host names here are ASCII: an internationalised name is not covered by these cases. `kind: login` — whether a login kept on a device is for the server now being signed in to, so that it is replaced and never given a twin: `stored` (the address kept with the login), `typed` (the address typed now), `discovery_base_url` (what discovery of the typed address names as the server's own `base_url`; advisory) → true or false. True when stored and typed are one server; or when the stored address is the one the server's discovery names — a login kept from before the typed address was what is stored. `kind: origin` — whether an endpoint discovery names may be used: `base` (the stored base address), `url` → true only when the url is a full http or https address on the same scheme, host and port.", "cases": [ { "typed": "example.org", @@ -307,6 +307,191 @@ "a": "https://example.org", "b": "example.org:80", "expect": false + }, + { + "kind": "login", + "stored": "https://ai.example.org", + "typed": "ai.example.org", + "expect": true + }, + { + "kind": "login", + "stored": "https://ai.example.org", + "typed": "ai.example.org", + "discovery_base_url": "https://ai.example.org", + "expect": true + }, + { + "kind": "login", + "stored": "https://ai.example.org", + "typed": "https://AI.example.org/chat", + "expect": true + }, + { + "kind": "login", + "stored": "http://backend.example.org:8080", + "typed": "ai.example.org", + "discovery_base_url": "http://backend.example.org:8080", + "expect": true + }, + { + "kind": "login", + "stored": "http://backend.example.org:8080/", + "typed": "https://ai.example.org", + "discovery_base_url": "http://backend.example.org:8080", + "expect": true + }, + { + "kind": "login", + "stored": "http://ai.example.org", + "typed": "https://ai.example.org", + "discovery_base_url": "http://ai.example.org", + "expect": true + }, + { + "kind": "login", + "stored": "http://ai.example.org", + "typed": "https://ai.example.org", + "expect": false + }, + { + "kind": "login", + "stored": "http://ai.example.org", + "typed": "https://ai.example.org", + "discovery_base_url": "https://ai.example.org", + "expect": false + }, + { + "kind": "login", + "stored": "http://backend.example.org:8080", + "typed": "ai.example.org", + "expect": false + }, + { + "kind": "login", + "stored": "http://backend.example.org:8080", + "typed": "ai.example.org", + "discovery_base_url": "http://other.example.org:8080", + "expect": false + }, + { + "kind": "login", + "stored": "https://other.example.org", + "typed": "ai.example.org", + "discovery_base_url": "https://ai.example.org", + "expect": false + }, + { + "kind": "login", + "stored": "https://other.example.org", + "typed": "ai.example.org", + "discovery_base_url": "", + "expect": false + }, + { + "kind": "login", + "stored": "https://other.example.org", + "typed": "ai.example.org", + "discovery_base_url": "not an address", + "expect": false + }, + { + "kind": "login", + "stored": "", + "typed": "ai.example.org", + "discovery_base_url": "", + "expect": false + }, + { + "kind": "login", + "stored": "https://ai.example.org", + "typed": "http://ai.example.org", + "discovery_base_url": "https://ai.example.org", + "expect": true + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "https://ai.example.org/api/device/code", + "expect": true + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "https://AI.example.org:443/api/device/code", + "expect": true + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "http://ai.example.org/api/device/code", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "https://ai.example.org:8443/api/device/code", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "https://login.example.org/api/device/code", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "https://ai.example.org.example.net/x", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "/api/device/code", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "ai.example.org/api/device/code", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": null, + "expect": false + }, + { + "kind": "origin", + "base": "http://localhost:3000", + "url": "http://localhost:3000/v1", + "expect": true + }, + { + "kind": "origin", + "base": "http://localhost:3000", + "url": "http://127.0.0.1:3000/v1", + "expect": false + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "https://person@ai.example.org/api/device/code", + "expect": true + }, + { + "kind": "origin", + "base": "https://ai.example.org", + "url": "javascript:alert(1)", + "expect": false } ] } diff --git a/harness/conformance/errors.json b/harness/conformance/errors.json index 10dc332..b1bbcdd 100644 --- a/harness/conformance/errors.json +++ b/harness/conformance/errors.json @@ -1,5 +1,5 @@ { - "about": "LLeMbas connection 1 (connection.md §11; the words: connection.json `codes` and `steps`). A condition → its machine code and the English sentence a person reads, or null when nothing is wrong. `condition.kind`: `network` (`error`: `dns`, `refused`, `reset`, `timeout`, `tls`); `discovery` (the answer to GET /.well-known/lembas.json: `status`, `json` false when the body is not JSON, `service` what it says); `http` (any other request's `status`, `retry_after` the header as sent); `close` (the link's close `code`); `versions` (`mine`, `theirs`, as conformance/version.json); `state` (`code` itself: a condition the client knows without asking). `vars`: `host` (default: \"the server\"), `product` (default `cli`), `version`, `needed`, `status`, `stdio` (true: the sentence of a client of lembas serve --stdio, where the code has one). The sentence is the code's text with the variables filled in, then the product's own step where it has one. A host's name is never changed; the stand-in for a host nobody named takes a capital where it begins the sentence. A 429 also answers `retry_s`, from `Retry-After`: whole seconds as sent, at least 1 and at most connection.json `retry_after.ceiling_s`; null for a header that is absent, a date or anything else (the client's own schedule decides).", + "about": "LLeMbas connection 1 (connection.md §11; the words: connection.json `codes` and `steps`). A condition → its machine code and the English sentence a person reads, or null when nothing is wrong. `condition.kind`: `network` (`error`: `dns`, `refused`, `reset`, `timeout`, `tls`); `discovery` (the answer to GET /.well-known/lembas.json: `status`, `json` false when the body is not JSON, `service` what it says); `http` (any other request's `status`, `retry_after` and `challenge` the `Retry-After` and `WWW-Authenticate` headers as sent); `close` (the link's close `code`); `versions` (`mine`, `theirs`, as conformance/version.json); `state` (`code` itself: a condition the client knows without asking). `vars`: `host` (default: \"the server\"), `product` (default `cli`), `version`, `needed`, `mine`, `other`, `status`, `stdio`, `minimum` (true: the sentence for a client below the server's `min_clients`) (true: the sentence of a client of lembas serve --stdio, where the code has one). The sentence is the code's text with the variables filled in, then the product's own step where it has one. A host's name is never changed; the stand-in for a host nobody named takes a capital where it begins the sentence. A 429 also answers `retry_s`, from `Retry-After`: whole seconds as sent, at least 1 and at most connection.json `retry_after.ceiling_s`; null for a header that is absent, a date or anything else (the client's own schedule decides). A 401 is `signed_out` only with the server's own challenge, `Bearer realm=\"lembas\"` (connection.json `challenge`; the scheme in any case of letters, the realm quoted or not): the server's /v1 passes a model provider's status through, so a 401 without it is `failed` — the server's own sentence is shown, and nobody is signed out.", "cases": [ { "condition": { @@ -336,8 +336,8 @@ "host": "ai.example.org" }, "expect": { - "code": "signed_out", - "text": "ai.example.org no longer accepts this sign-in — sign in again. Run lembas login." + "code": "failed", + "text": "That did not work." } }, { @@ -405,7 +405,7 @@ "expect": { "code": "busy", "text": "ai.example.org is busy just now.", - "retry_s": 60 + "retry_s": 300 } }, { @@ -542,8 +542,8 @@ "product": "desktop" }, "expect": { - "code": "signed_out", - "text": "ai.example.org no longer accepts this sign-in — sign in again." + "code": "failed", + "text": "That did not work." } }, { @@ -555,8 +555,8 @@ "product": "android" }, "expect": { - "code": "signed_out", - "text": "The server no longer accepts this sign-in — sign in again." + "code": "failed", + "text": "That did not work." } }, { @@ -1145,6 +1145,335 @@ "code": "unreachable", "text": "Cannot reach the server." } + }, + { + "condition": { + "kind": "state", + "code": "client_too_old" + }, + "vars": { + "host": "ai.example.org", + "minimum": true, + "needed": "2.0.0", + "mine": "2.0.0-beta.17" + }, + "expect": { + "code": "client_too_old", + "text": "ai.example.org needs LLeMbas CLI 2.0.0 or later, and this is 2.0.0-beta.17. Update LLeMbas CLI. Run lembas update." + } + }, + { + "condition": { + "kind": "state", + "code": "client_too_old" + }, + "vars": { + "host": "ai.example.org", + "minimum": true, + "needed": "1.0.0", + "mine": "1.0.0-beta.5", + "product": "vscode" + }, + "expect": { + "code": "client_too_old", + "text": "ai.example.org needs LLeMbas for VS Code 1.0.0 or later, and this is 1.0.0-beta.5. Update LLeMbas for VS Code." + } + }, + { + "condition": { + "kind": "state", + "code": "client_too_old" + }, + "vars": { + "host": "ai.example.org", + "minimum": true, + "needed": "1.0.0", + "mine": "1.0.0-beta.16", + "product": "android" + }, + "expect": { + "code": "client_too_old", + "text": "ai.example.org needs LLeMbas for Android 1.0.0 or later, and this is 1.0.0-beta.16. Update LLeMbas for Android." + } + }, + { + "condition": { + "kind": "state", + "code": "client_too_old" + }, + "vars": { + "minimum": true + }, + "expect": { + "code": "client_too_old", + "text": "The server needs LLeMbas CLI (a newer version) or later, and this is (an unknown version). Update LLeMbas CLI. Run lembas update." + } + }, + { + "condition": { + "kind": "state", + "code": "other_origin" + }, + "vars": { + "host": "ai.example.org", + "other": "https://login.example.net/api/device/code" + }, + "expect": { + "code": "other_origin", + "text": "ai.example.org names an address on another server (https://login.example.net/api/device/code) for this, and this LLeMbas CLI does not follow it. The server's own address is set wrong: whatever stands in front of it must pass on the host and scheme it was asked for." + } + }, + { + "condition": { + "kind": "state", + "code": "other_origin" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "other_origin", + "text": "ai.example.org names an address on another server (another address) for this, and this LLeMbas Desktop does not follow it. The server's own address is set wrong: whatever stands in front of it must pass on the host and scheme it was asked for." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer realm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "signed_out", + "text": "ai.example.org no longer accepts this sign-in — sign in again." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "bearer realm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "signed_out", + "text": "ai.example.org no longer accepts this sign-in — sign in again." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer realm=lembas" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "signed_out", + "text": "ai.example.org no longer accepts this sign-in — sign in again." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer error=\"invalid_token\", realm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "signed_out", + "text": "ai.example.org no longer accepts this sign-in — sign in again." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer realm=\"lembas\", error=\"invalid_token\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "signed_out", + "text": "ai.example.org no longer accepts this sign-in — sign in again." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer realm=\"other\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Basic realm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer realm=\"lembas-proxy\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "realm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401 + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 401, + "challenge": "Bearer xrealm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org", + "product": "desktop" + }, + "expect": { + "code": "failed", + "text": "That did not work." + } + }, + { + "condition": { + "kind": "http", + "status": 403, + "challenge": "Bearer realm=\"lembas\"" + }, + "vars": { + "host": "ai.example.org" + }, + "expect": { + "code": "not_allowed", + "text": "ai.example.org did not allow this." + } + }, + { + "condition": { + "kind": "http", + "status": 429, + "retry_after": "300" + }, + "vars": { + "host": "ai.example.org" + }, + "expect": { + "code": "busy", + "text": "ai.example.org is busy just now.", + "retry_s": 300 + } + }, + { + "condition": { + "kind": "http", + "status": 429, + "retry_after": "301" + }, + "vars": { + "host": "ai.example.org" + }, + "expect": { + "code": "busy", + "text": "ai.example.org is busy just now.", + "retry_s": 300 + } } ] } diff --git a/harness/conformance/version.json b/harness/conformance/version.json index eed5ff0..34f1d33 100644 --- a/harness/conformance/version.json +++ b/harness/conformance/version.json @@ -1,5 +1,5 @@ { - "about": "LLeMbas connection 1 (connection.md §5). One surface's version integers, judged both ways. `mine`: what this client speaks; `theirs`: what the other side lists (a list, or one number where it says one) → `{ use, verdict }`: `use` the highest in common, or null; `verdict` `ok`, `server_too_old` (update the other side) or `client_too_old` (update this product). With nothing in common the side whose highest is lower is the old one; a side that lists nothing is the one to update. Anything that is not a whole number is not listed. `kind: stdio` — `lembas serve --stdio`: `agent` the agent's `_lembas` protocol, `client` what the client said in `clientCapabilities._meta.lembas.protocol` (absent or not a whole number from 1: 1) → `{ use, told }`: both use the lower, and `told` is true when the client said a higher one than the agent has, which the agent then says in words.", + "about": "LLeMbas connection 1 (connection.md §5). One surface's version integers, judged both ways. `mine`: what this client speaks; `theirs`: what the other side lists (a list, or one number where it says one) → `{ use, verdict }`: `use` the highest in common, or null; `verdict` `ok`, `server_too_old` (update the other side) or `client_too_old` (update this product). With nothing in common the side whose highest is lower is the old one; a side that lists nothing is the one to update. Anything that is not a whole number is not listed. `kind: stdio` — `lembas serve --stdio`: `agent` the agent's `_lembas` protocol, `client` what the client said in `clientCapabilities._meta.lembas.protocol` (absent or not a whole number from 1: 1) → `{ use, told }`: both use the lower, and `told` is true when the client said a higher one than the agent has, which the agent then says in words. `kind: min` — `min_clients` (connection.md §5): `mine` this product's version, `minimum` what the server's discovery names for the product (absent: none) → `{ verdict }`, `client_too_old` when mine is below it, else `ok`. Versions are `X.Y.Z` or `X.Y.Z-.N`, a leading `v` allowed; numbers compare as numbers, a pre-release is older than its release, two pre-releases of one release compare by word and then by number. A version on either side that is not of that form is no minimum: `ok`. `kind: compare` — `a`, `b` → negative, 0 or positive as a is older, the same or newer (only the sign is specified: −1, 0, 1 here), or null when either is not a version.", "cases": [ { "mine": [ @@ -338,6 +338,259 @@ "use": 3, "told": true } + }, + { + "kind": "min", + "mine": "2.0.0-beta.9", + "minimum": "2.0.0-beta.10", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "2.0.0-beta.10", + "minimum": "2.0.0-beta.9", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0-beta.10", + "minimum": "2.0.0-beta.10", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0-beta.99", + "minimum": "2.0.0", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "minimum": "2.0.0-beta.99", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "minimum": "2.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "1.9.9", + "minimum": "2.0.0", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "2.0.10", + "minimum": "2.0.9", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.9", + "minimum": "2.0.10", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "2.10.0", + "minimum": "2.9.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "10.0.0", + "minimum": "9.9.9", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "v2.0.0", + "minimum": "2.0.1", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "minimum": "v1.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "minimum": "", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "minimum": "latest", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0", + "minimum": 2, + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "dev", + "minimum": "2.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0+g1234abc", + "minimum": "3.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": null, + "minimum": "2.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0-alpha.3", + "minimum": "2.0.0-beta.1", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "2.0.0-rc.1", + "minimum": "2.0.0-beta.7", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0-beta.1", + "minimum": "2.0.0-rc.1", + "expect": { + "verdict": "client_too_old" + } + }, + { + "kind": "min", + "mine": "1.0", + "minimum": "1.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "min", + "mine": "2.0.0-beta", + "minimum": "2.0.0", + "expect": { + "verdict": "ok" + } + }, + { + "kind": "compare", + "a": "2.0.0-beta.10", + "b": "2.0.0-beta.9", + "expect": 1 + }, + { + "kind": "compare", + "a": "2.0.0", + "b": "2.0.0-beta.99", + "expect": 1 + }, + { + "kind": "compare", + "a": "2.0.0-beta.2", + "b": "2.0.0-beta.2", + "expect": 0 + }, + { + "kind": "compare", + "a": "1.2.3", + "b": "1.2.4", + "expect": -1 + }, + { + "kind": "compare", + "a": "1.10.0", + "b": "1.9.0", + "expect": 1 + }, + { + "kind": "compare", + "a": "v1.0.0", + "b": "1.0.0", + "expect": 0 + }, + { + "kind": "compare", + "a": "1.0.0", + "b": "one", + "expect": null + }, + { + "kind": "compare", + "a": "2.0.0-beta.1", + "b": "2.0.0-rc.1", + "expect": -1 + }, + { + "kind": "compare", + "a": "3.0.0-beta.1", + "b": "2.9.9", + "expect": 1 } ] } diff --git a/harness/connection.json b/harness/connection.json index b7a58a2..82e9eb3 100644 --- a/harness/connection.json +++ b/harness/connection.json @@ -1,5 +1,5 @@ { - "about": "LLeMbas connection 1 (connection.md): the numbers, the names and the words every LLeMbas product uses when it connects to another. `products`: the id each product identifies itself with and the name a sentence calls it. `codes`: one machine code per condition and its English sentence — `{host}` the server's host (and port), `{product}` this product's name, `{version}` the other side's version, `{needed}` the version a client needs, `{status}` an HTTP status; `stdio` is the sentence a client of `lembas serve --stdio` says instead, where the other side is LLeMbas CLI and not a server. `steps`: what one product adds after a code's sentence, the thing a person can do there. `heals`: true where the client tries again by itself.", + "about": "LLeMbas connection 1 (connection.md): the numbers, the names and the words every LLeMbas product uses when it connects to another. `products`: the id each product identifies itself with and the name a sentence calls it. `codes`: one machine code per condition and its English sentence — `{host}` the server's host (and port), `{product}` this product's name, `{version}` the other side's version, `{needed}` the version a client needs, `{mine}` this product's own version, `{other}` an address the server named, `{status}` an HTTP status; `stdio` is the sentence a client of `lembas serve --stdio` says instead, where the other side is LLeMbas CLI and not a server; `minimum` the sentence for a client below the server's `min_clients` (connection.md §5). `steps`: what one product adds after a code's sentence, the thing a person can do there. `heals`: true where the client tries again by itself.", "contract": 1, "identity": "llembas-{product}/{version}", "products": { @@ -21,7 +21,8 @@ }, "streams": { "keepalive_s": 15, "silence_s": 45 }, "reconnect": { "first_s": 1, "ceiling_s": 60, "jitter": 0.2, "healthy_s": 30 }, - "retry_after": { "ceiling_s": 60 }, + "retry_after": { "ceiling_s": 300 }, + "challenge": { "scheme": "Bearer", "realm": "lembas" }, "stdio": { "protocol": 3, "initialize_s": 10, "line_bytes": 67108864, "stderr_lines": 40, "kill_after_s": 5, "quiet_restart_s": 60 }, "codes": { "linked": { "text": "Linked to {host}.", "heals": true }, @@ -40,12 +41,14 @@ "client_too_old": { "text": "{host} runs LLeMbas {version}, which is newer than this {product} can use. Update {product}.", "stdio": "LLeMbas CLI {version} is newer than this {product} can use. Update {product}.", + "minimum": "{host} needs {product} {needed} or later, and this is {mine}. Update {product}.", "heals": false }, "signed_out": { "text": "{host} no longer accepts this sign-in — sign in again.", "heals": false }, "replaced": { "text": "A newer link of this device took its place on {host}, so this one stopped.", "heals": false }, "not_logged_in": { "text": "This computer is not logged in to a LLeMbas server.", "heals": false }, "not_allowed": { "text": "{host} did not allow this.", "heals": false }, + "other_origin": { "text": "{host} names an address on another server ({other}) for this, and this {product} does not follow it. The server's own address is set wrong: whatever stands in front of it must pass on the host and scheme it was asked for.", "heals": false }, "disabled": { "text": "The link to a LLeMbas server is turned off here.", "heals": false }, "invalid_address": { "text": "That is not a server address. Give a host name, or an http or https address.", "heals": false }, "expired": { "text": "The code expired before it was approved. Start the sign-in again.", "heals": false }, diff --git a/harness/connection.md b/harness/connection.md index 3e4dea2..7de23b5 100644 --- a/harness/connection.md +++ b/harness/connection.md @@ -34,12 +34,26 @@ and not the person's word (`kind: same`). Every comparison of addresses anywhere "am I already signed in there", "is this computer linked to my server" — is this comparison, with **both sides normalised first**. No product compares raw strings. -> **Open — not a rule yet: which address is stored.** Whether a client stores the normalised -> typed address or the `base_url` the server's discovery names is not decided. Products differ -> today, and changing it moves account ids and existing logins. Until it is decided, a product -> keeps what it stores now, and the rule above carries the weight: both sides of every comparison -> go through the one address rule, so two products that stored different spellings of one server -> still agree that it is one. +**What is stored is the normalised typed address.** The `base_url` in the server's discovery is +advisory: a product may show it and write it to a log, and **never stores it and never compares +with it**. It is built from the headers of whatever stands in front of the server, so two +products that stored it could disagree about the name of one server, and a product that followed +it would be talking to an address nobody typed. + +**Sign-ins kept from before this rule** are not lost and not doubled: + +- an existing sign-in keeps working untouched; its stored address is read through the address + rule above from now on, and compared like any other; +- only a **new** sign-in stores the typed address; +- a sign-in whose stored address is the one the server's discovery names — it was stored when + that was what a product kept — **is the same sign-in** as one now made by typing the server's + real address: it is replaced, never given a twin (`kind: login`). The server's word is taken + only for this, and only about an address already stored: discovery naming an address nobody + stored claims nothing. **And it is not proof.** A token is sent only to the server it belongs + to: a sign-in recognised as the same on the server's word alone has its old token signed out + at the address that token was stored with, and the new token is never named there — so a + server that claims another's address in its discovery gets neither the other's token nor a + twin of it. ## 2. Discover @@ -54,7 +68,15 @@ updated since. The outcomes, each with its own code and words (§11): | the certificate is not trusted | `tls_untrusted` — the sentence names what that product's person can do about the CA | | 404, or a body that is not JSON, or `service` is not `lembas` | `not_lembas` | | any other status that is not 2xx | `server_error`, saying the status — **never** `not_lembas` | -| no version in common | `server_too_old` or `client_too_old` (§5) | +| no version in common, or this product below the server's minimum | `server_too_old` or `client_too_old` (§5) | +| an endpoint it names is on another origin | `other_origin` | + +**Endpoints from discovery are used only on the stored base's origin** — the same scheme, host +and port (`conformance/address.json`, `kind: origin`). Where discovery names an address anywhere +else for something the client is about to call — where to sign in, where its API is — the client +does not call it and says `other_origin`, naming the address; what the client reaches by a path +of its own on the stored base needs no word from discovery and is not affected. This is also a safety rule: the token +goes only to the server whose address a person typed. ## 3. Identify @@ -99,22 +121,39 @@ answer, one sentence. Within a protocol a feature is used only if its capability `agentInfo.version` with its stated minimum once, at connect, and says `server_too_old` in its stdio wording, with both versions. -> **Open — not a rule yet: `min_clients`.** A server saying in discovery the lowest version of -> each product it still serves (`min_clients: { : }`) is not decided. No -> client may rely on the field, and no server need send it. +**`min_clients`.** Discovery may carry `"min_clients": { "": "" }`, 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 +`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 +that is not a version is no minimum (`conformance/version.json`, `kind: min`). + +A client of `lembas serve --stdio` does not ask the server itself, so the agent tells it: in +`initialize`'s answer, **`_meta.lembas.min_client`** is the minimum the logged-in server names +for the product the client said it is in `clientInfo.name` (`llembas-nvim` → `min_clients.nvim`) +— a version string, or absent when the CLI is not logged in, has not heard the server's +discovery, the client named no LLeMbas product, or there is no minimum for it. The client +compares its own version and says the same sentence. ## 6. A refused token One event, one behaviour, in every product. -- **401** on HTTP, or the link closed with a `link.close.refused` code: `signed_out`. The client - marks **the account that token belongs to** — not whichever account is in front — as signed out - by the server, stops that account's streams and its link, keeps everything else, and offers the - sign-in in one step. +- **Signed out** is a **401 that carries the server's own challenge**, + `WWW-Authenticate: Bearer realm="lembas"` (`connection.json` `challenge`), or the link closed + as refused (the server sends **4403**; `link.close.refused`): `signed_out`. It concerns **the token that was sent** — + the client marks the account that token belongs to, not whichever account is in front, as + signed out by the server, stops that account's streams and its link, keeps everything else, and + offers the sign-in in one step. A refusal that arrives late, for a token since replaced, signs + out nothing: the newer token was not the one refused. +- **A 401 without that challenge is not a sign-out.** The server's `/v1` routes pass a model + provider's status through, so a provider's 401 reaches the client: it is shown as the server's + own sentence (`failed`), and nobody is signed out. - **403**: `not_allowed`, with the server's own sentence where it gave one. Nobody is signed out. - **429**: `busy`. The client waits what `Retry-After` says — whole seconds, at least 1 and at - most `retry_after.ceiling_s` — before the request is made again, and its own schedule (§9) - where the header is absent or is not a number of seconds. + most `retry_after.ceiling_s` (five minutes) — before the request is made again, and its own + schedule (§9) where the header is absent or is not a number of seconds. ## 7. The link @@ -190,15 +229,16 @@ only its own step from `steps`, the one thing a person can do there. | `busy` | 429 | yes, after `Retry-After` | | `server_too_old` | no version in common; the other side is the old one | no | | `client_too_old` | no version in common; this product is the old one | no | -| `signed_out` | 401; the link closed as refused | no — until signed in again | +| `signed_out` | a 401 with the server's challenge; the link closed as refused | no — until signed in again | | `replaced` | the link closed with 4409 | no — until signed in again | | `not_logged_in` | there is no sign-in on this computer | no — until signed in | | `not_allowed` | 403 | no | +| `other_origin` | discovery names an endpoint on another origin (§2) | no | | `disabled` | the link is turned off on this device | no | | `invalid_address` | §1 | no | | `expired` | a device code ran out before it was approved | no | | `stopped` | stopped on purpose | no | -| `failed` | anything else; the sentence is the product's own | no | +| `failed` | anything else — a 401 without the server's challenge among it; the sentence is the server's or the product's own | no | **A failed turn is reported in the prompt's answer** — `_meta.lembas.error = { code, message }` (`acp.md`, `session/prompt`) — as well as by the `error` event, so a client that draws only what diff --git a/src/acp/agent.ts b/src/acp/agent.ts index ed8bf37..3ec6ba4 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -40,6 +40,8 @@ import { isLevel, readLevel, type Level } from "../provider/effort.ts" import { HARNESS_VERSION } from "../harness.ts" import { findProject, trustedRoots, trustedWithin, trustOf } from "../project/root.ts" import { VERSION } from "../version.ts" +import { minimumFor, productOf, stdioProtocol } from "../lembas/connection.ts" +import { instances as loggedIn } from "../lembas/login.ts" import { CWD_META, REMOTE_META, SCHEDULED_META, Store } from "../session/store.ts" import { lastModels } from "../session/lastmodel.ts" import type { Message } from "../provider/types.ts" @@ -381,6 +383,37 @@ export const CAPABILITIES = [ ] as const export const STOP: Record = { stop: "end_turn", steps: "max_turn_requests", budget: "max_tokens", cancelled: "cancelled", error: "end_turn" } +/** `_meta.lembas.min_client`: the minimum the logged-in server's discovery named for the product + * a client says it is (`llembas-nvim` → `min_clients.nvim`), as this machine last heard it — at + * login, at a refresh, at the service's dial. Undefined when not logged in, when the client is not + * a LLeMbas product, or when the server names no minimum for it. */ +export function minClientFor(clientInfoName: unknown): string | undefined { + const product = productOf(clientInfoName) + if (!product) return undefined + try { + const all = Object.values(loggedIn()) + return all.length === 1 ? minimumFor(all[0]!.min_clients, product) : undefined + } catch { + return undefined + } +} + +/** `clientInfo` as one loggable word, `name/version` — or undefined when the client gave none. */ +export function clientName(info: unknown): string | undefined { + const word = (v: unknown) => (typeof v === "string" ? v.replace(/[^\x21-\x7e]+/g, " ").trim().slice(0, 80) : "") + const o = info && typeof info === "object" ? (info as { name?: unknown; version?: unknown }) : {} + const name = word(o.name) + if (!name) return undefined + const version = word(o.version) + return version ? `${name}/${version}` : name +} + +/** A turn's `error` event as the prompt's answer carries it: a code and one line. */ +export function turnError(e: { message: string; code?: string }): { code: string; message: string } { + const line = e.message.split("\n").find((l) => l.trim()) ?? "the turn failed" + return { code: e.code ?? "failed", message: line.trim().slice(0, 600) } +} + type AskRequest = Parameters[0] /** `session/request_permission`'s params for an approval — the same card whichever process asks @@ -547,6 +580,10 @@ export class AcpAgent { /** The `_lembas` protocol the client says it speaks (`clientCapabilities._meta.lembas.protocol`): * question and plan cards only for 2 or later — a client may say `lembas` and have neither. */ private clientProtocol = 1 + /** Called once `initialize` has been answered: for the link, the moment it is linked. */ + onInitialized?: () => void + /** The client as it named itself in `initialize` (`llembas-nvim/1.0.0`), for the log. */ + client?: string private get cards() { return this.lembas && this.clientProtocol >= 2 } @@ -667,7 +704,22 @@ export class AcpAgent { private initialize(p: any) { const said = p?.clientCapabilities?._meta?.lembas this.lembas = Boolean(said) - this.clientProtocol = typeof said?.protocol === "number" ? said.protocol : 1 + // Both use the lower of the two protocols (harness connection.md §5): a client that says a + // higher one than this build has is answered this build's, and told so in words. + const agreed = stdioProtocol(this.protocol, said?.protocol) + this.clientProtocol = agreed.use + const notice = agreed.told + ? `this LLeMbas CLI ${VERSION} speaks protocol ${this.protocol}, and the client said ${said.protocol}: both use ${agreed.use}. Update LLeMbas CLI for what the client's newer protocol adds.` + : undefined + // Who the client is (ACP's `clientInfo`; a LLeMbas client says `llembas-`): for the + // log, where a person or a bug report can find which client and version this was. Nothing is + // decided by it. Model-free text from outside: one line, no control characters, capped. + this.client = clientName(p?.clientInfo) + // The lowest version of the client's own product the server it works through still serves + // (harness connection.md §5), where this machine's login knows it: the client compares and + // says so itself. Not on the link — there the client is the server. + const minClient = this.isLink ? undefined : minClientFor(p?.clientInfo?.name) + if (!this.isLink) console.error(`client: ${this.client ?? "unnamed"}, protocol ${said ? agreed.use : "none (plain ACP)"}${notice ? ` — ${notice}` : ""}`) this.shows = said?.show === true this.editorClient = said?.editor === true this.media = said?.media === true @@ -680,6 +732,7 @@ export class AcpAgent { // knows the agent — after this answer, not before it. setTimeout(() => { this.ready = true + this.onInitialized?.() for (const s of this.sessions.values()) if (s.agent === this) this.sendCommands(s, true) for (const t of this.hub?.shared.values() ?? []) if (t.commands) this.commandsShared(t.sessionId, t.commands) this.flushDeleted() @@ -699,6 +752,8 @@ export class AcpAgent { _meta: { lembas: { protocol: this.protocol, + ...(notice ? { notice } : {}), + ...(minClient ? { min_client: minClient } : {}), harness_spec: HARNESS_VERSION, limits: this.limits ? { roots: this.limits.roots, max_mode: this.limits.maxMode, scheduled: this.limits.scheduled === true, files_that_run_code: this.limits.filesThatRunCode === true } : null, // The login's connection: a `model` event's ref `/` is the @@ -1617,6 +1672,13 @@ export class AcpAgent { } for (const a of prepared.atPaths) this.indexFor(app.engine.o.toolCtx.cwd).used(a.replace(/\/$/, "")) const prev = { model: app.engine.model.ref, mode: app.engine.mode, effort: app.engine.effort } + // Why the turn failed, when it does: said in the answer too (acp.md `session/prompt`, + // `_meta.lembas.error`), since a client that reads only the answer would otherwise show a turn + // that ended with nothing and no reason. + let failure: { code: string; message: string } | undefined + const off = app.bus.on((e) => { + if (e.type === "error") failure = turnError(e) + }) try { if (prepared.model) app.switchModel(prepared.model, "borrowed") if (prepared.mode) app.engine.mode = this.limits ? clampMode(prepared.mode, this.limits.maxMode) : prepared.mode @@ -1624,8 +1686,10 @@ export class AcpAgent { // Messages sent mid-task (`_lembas/steer`) that the task ended before taking in: handed back, // so the web UI sends them as the next turn rather than losing them. const unsent = this.leftover(s) - return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(unsent.length ? { unsent } : {}), ...(prepared.command ? { command: prepared.command } : {}) } } } + const error = reason === "error" ? (failure ?? { code: "failed", message: "the turn failed" }) : undefined + return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(unsent.length ? { unsent } : {}), ...(prepared.command ? { command: prepared.command } : {}), ...(error ? { error } : {}) } } } } finally { + off() // A command's model and mode hold for its prompt only — unless the turn itself changed the // mode (a plan approved), which then stays. // The model back, and the effort the person had on it — not the model's default. diff --git a/src/acp/editor.ts b/src/acp/editor.ts index 93fddda..70ffae6 100644 --- a/src/acp/editor.ts +++ b/src/acp/editor.ts @@ -124,7 +124,7 @@ export function completeBody(p: any): CompleteParams { /** One autocomplete request to the server (`POST /v1/lembas/complete`, acp.md *The HTTP API*). * `signal` closes it — the server stops the model's request when the client goes. */ export async function completeOnServer(login: Login, body: CompleteParams, signal: AbortSignal): Promise<{ text: string; model: string | null; finish: "stop" | "length" }> { - let r: { status: number; json: any } + let r: { status: number; json: any; signedOut: boolean } try { r = await apiCall(login.instance.base_url, login.token, tlsOf(login), "POST", "/v1/lembas/complete", { ...body, stream: false }, 60_000, signal) } catch (e) { @@ -132,7 +132,7 @@ export async function completeOnServer(login: Login, body: CompleteParams, signa throw new RpcError(INTERNAL_ERROR, (e as Error).message) } const said = detailOf(r.json) - if (r.status === 401) throw new RpcError(INVALID_PARAMS, said ?? "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) + if (r.signedOut) throw new RpcError(INVALID_PARAMS, said ?? "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) if (r.status === 409) throw new RpcError(INVALID_PARAMS, said ?? "no autocomplete model is chosen yet — choose one in your settings on the server", { reason: "no_model" }) if (r.status === 403) throw new RpcError(INVALID_PARAMS, said ?? "that model is not allowed for autocomplete", { reason: "not_allowed" }) if (r.status === 413) throw new RpcError(INVALID_PARAMS, said ?? "the text around the cursor is too long for autocomplete", { reason: "too_large" }) @@ -178,9 +178,9 @@ export async function editorSettings(login: Login, set?: { autocomplete_model?: throw new RpcError(INTERNAL_ERROR, (e as Error).message) } } - const judge = (r: { status: number; json: any }, writing: boolean): EditorSettings | undefined => { + const judge = (r: { status: number; json: any; signedOut: boolean }, writing: boolean): EditorSettings | undefined => { const said = detailOf(r.json) - if (r.status === 401) throw new RpcError(INVALID_PARAMS, said ?? "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) + if (r.signedOut) throw new RpcError(INVALID_PARAMS, said ?? "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) if (r.status === 404 && said) throw new RpcError(INVALID_PARAMS, said, { reason: "unknown_model" }) if (r.status === 404 || r.status === 405) { if (writing) throw new RpcError(INVALID_PARAMS, OLDER("editor settings"), { reason: "unsupported" }) @@ -213,13 +213,13 @@ export function settingsToSet(p: any): { autocomplete_model?: string | null; mai /** `_lembas/models`: the login's chat models, each with what it may be picked for. */ export async function modelsForPicker(login: Login) { - let r: { status: number; json: any } + let r: { status: number; json: any; signedOut: boolean } try { r = await apiCall(login.instance.base_url, login.token, tlsOf(login), "GET", "/v1/models", undefined, 15_000) } catch (e) { throw new RpcError(INTERNAL_ERROR, (e as Error).message) } - if (r.status === 401) throw new RpcError(INVALID_PARAMS, "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) + if (r.signedOut) throw new RpcError(INVALID_PARAMS, "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) if (r.status >= 400) throw new RpcError(INTERNAL_ERROR, detailOf(r.json) ?? `listing the models failed (${r.status})`) const served: ServedModel[] = Array.isArray(r.json?.data) ? r.json.data : [] const settings = await editorSettings(login) diff --git a/src/acp/link.ts b/src/acp/link.ts index 2438a7d..fe44ef8 100644 --- a/src/acp/link.ts +++ b/src/acp/link.ts @@ -5,7 +5,11 @@ // // One WebSocket message is one JSON-RPC message. The token goes in the Authorization header and // never in the address. A token the instance refuses (revoked from its Settings → Security, or the -// account lost the permission) ends the link for good: retrying it would only knock on a closed door. +// account lost the permission) ends the link for that token: retrying it would only knock on a +// closed door — until the sign-in kept here changes, which is read again at every dial. +// +// How it is made, kept and lost is the harness's connection.md (LLeMbas connection 1); its numbers +// are connection.json `link` and `reconnect`. import { existsSync, readFileSync } from "node:fs" import { hostname } from "node:os" import { resolve as resolvePath } from "node:path" @@ -15,13 +19,22 @@ import { refusedLocally } from "../project/local.ts" import type { Mode } from "../config/schema.ts" import { HARNESS_VERSION } from "../harness.ts" import { instances, keyFile, rememberProtocols, type Instance } from "../lembas/login.ts" -import { discover, linkProtocol, ProtocolError, spoken } from "../lembas/client.ts" +import { discover, LembasError, linkProtocol, ProtocolError, spoken } from "../lembas/client.ts" +import { codeFor, CONNECTION, reconnectWait, sentence, USER_AGENT, type Code } from "../lembas/connection.ts" import { VERSION } from "../version.ts" import { AcpAgent, type Limits } from "./agent.ts" import type { Hub } from "./hub.ts" import { Peer, type Transport } from "./rpc.ts" -export class LinkError extends Error {} +/** The link cannot run, and why as a machine code (harness connection.json `codes`). */ +export class LinkError extends Error { + constructor( + message: string, + readonly code: Code = "failed", + ) { + super(message) + } +} /** The device's limits, read from the global `remote:` block each time one is looked at — so a * running service follows `lembas remote …` (or an edit of config.yaml) without a restart. Every @@ -78,19 +91,42 @@ export function pickInstance(name?: string): Instance { const all = instances() if (name) { const one = all[name] - if (!one) throw new LinkError(`not logged in to ${name}${Object.keys(all).length ? ` — logged in: ${Object.keys(all).join(", ")}` : ""}`) + if (!one) throw new LinkError(`not logged in to ${name}${Object.keys(all).length ? ` — logged in: ${Object.keys(all).join(", ")}` : ""}`, "not_logged_in") return one } const list = Object.values(all) - if (!list.length) throw new LinkError("not logged in to any LLeMbas instance — lembas login
") - if (list.length > 1) throw new LinkError(`logged in to several instances; name one: ${Object.keys(all).join(", ")}`) + if (!list.length) throw new LinkError("not logged in to any LLeMbas instance — lembas login
", "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]! } +/** The sign-in as it is on disk now: the instance and its token. Read at every dial, never kept — + * a `lembas login` made again by another process is then what the next dial uses. A login whose + * key file is gone is no login: said, not thrown as a crash. */ +export function heldLogin(name?: string): { instance: Instance; token: string } { + const instance = pickInstance(name) + let token = "" + try { + token = readFileSync(keyFile(instance.connection), "utf8").trim() + } catch {} + if (!token) throw new LinkError(`not logged in: the sign-in kept here for ${instance.base_url} has no key any more — lembas login ${instance.base_url}`, "not_logged_in") + return { instance, token } +} + +/** What identifies the sign-in a dial used: when it differs, somebody signed in again. */ +function loginMark(name?: string): string { + try { + const { instance, token } = heldLogin(name) + return `${instance.connection}\n${instance.base_url}\n${token}` + } catch { + return "" + } +} + export function linkUrl(instance: Instance): string { const u = new URL(instance.base_url) u.protocol = u.protocol === "https:" ? "wss:" : "ws:" - u.pathname = "/api/devices/link" + u.pathname = CONNECTION.link.path return u.toString() } @@ -104,6 +140,8 @@ function wsTransport(ws: WebSocket): Transport { export interface LinkStatus { state: "connecting" | "linked" | "waiting" | "stopped" + /** Why, for a program (harness connection.json `codes`): `detail` is the same for a person. */ + code: Code instance: string since: string detail?: string @@ -125,8 +163,24 @@ export interface LinkOptions { sharedOnly?: boolean /** Only for tests: how often the config is looked at while linked (default 2 s). */ pollMs?: number + /** The service: a stop that a sign-in would heal — not logged in, the token refused, replaced + * by a newer link — does not end it. It stays, says `stopped` with the code, watches the + * sign-in kept here and dials again when that changes, so `lembas login` on a machine nobody + * sits at brings its link back without anybody restarting anything. Without it (a terminal's + * /remote) such a stop is returned. */ + stay?: boolean + /** Only for tests: the timers of connection.json `link` and `reconnect`, in milliseconds, and + * the jitter's random number. */ + timers?: { handshake?: number; ping?: number; silence?: number; healthy?: number; login?: number; random?: () => number } } +type Outcome = + | { kind: "changed" } + | { kind: "refused"; reason: string } + | { kind: "replaced"; reason: string } + | { kind: "protocol"; reason: string } + | { kind: "dropped"; code: Code; detail: string; healthy: boolean } + /** Dial, serve, and dial again, until stopped or refused. Resolves when it stops for good. * * It links whether remote work is on or not, and with no roots at all: the instance then hears @@ -134,72 +188,151 @@ export interface LinkOptions { * `lembas remote add` or `enable` makes it serve, without a restart. */ export async function runLink(o: LinkOptions = {}): Promise { const local = refusedLocally("the link to a LLeMbas instance (lembas service, /remote)") - if (local) throw new LinkError(local) + if (local) throw new LinkError(local, "disabled") const limits = limitsFromConfig({ sharedOnly: o.sharedOnly }) const poll = o.pollMs ?? 2000 - const instance = pickInstance(o.instance) - const token = readFileSync(keyFile(instance.connection), "utf8").trim() + const T = { + handshake: o.timers?.handshake ?? CONNECTION.link.handshake_s * 1000, + ping: o.timers?.ping ?? CONNECTION.link.ping_s * 1000, + silence: o.timers?.silence ?? CONNECTION.link.silence_s * 1000, + healthy: o.timers?.healthy ?? CONNECTION.reconnect.healthy_s * 1000, + login: o.timers?.login ?? 2000, + random: o.timers?.random ?? Math.random, + } + // Without `stay`, a machine that is not logged in is the caller's to say at once. + if (!o.stay) heldLogin(o.instance) // A service runs for weeks: the webui connections' models are read again every ten minutes, so a // session the web UI opens here starts with the instance's models as they are then. const freshen = setInterval(() => void import("../lembas/webui.ts").then((w) => w.refreshWebui()), 10 * 60_000) freshen.unref?.() - const [first, ceiling] = o.backoffMs ?? [1000, 60_000] - let wait = first + const [first, ceiling] = o.backoffMs ?? [CONNECTION.reconnect.first_s * 1000, CONNECTION.reconnect.ceiling_s * 1000] + /** Dials in a row that did not end in a connection that stayed healthy: what the wait grows by. */ + let failures = 0 let attempts = 0 - const status = (state: LinkStatus["state"], detail?: string): LinkStatus => { - const s = { state, instance: instance.base_url, since: new Date().toISOString(), detail, attempts } + let base = "" + const status = (state: LinkStatus["state"], code: Code, detail?: string): LinkStatus => { + const s = { state, code, instance: base, since: new Date().toISOString(), detail, attempts } o.onStatus?.(s) return s } - // The CA the login was given, as a full path (an older login kept what was typed: relative, or - // with ~, which a service started elsewhere does not find). One that is gone is said, not skipped. - const caPath = instance.ca ? resolvePath(expandHome(instance.ca)) : undefined - const caGone = caPath && !existsSync(caPath) ? caPath : undefined - const loginCa = caPath && !caGone ? readFileSync(caPath, "utf8") : undefined + const finish = (s: LinkStatus) => (clearInterval(freshen), s) + /** A stop a sign-in heals: returned — or, for the service, waited out until the sign-in kept + * here is another one than `mark`. True when there is something new to dial with. */ + const healed = async (mark: string): Promise => { + if (!o.stay) return false + while (!o.signal?.aborted && loginMark(o.instance) === mark) await sleep(T.login, o.signal) + failures = 0 + return !o.signal?.aborted + } while (!o.signal?.aborted) { + // The sign-in as it is now: the token is read at every dial, so one made again since — by + // `lembas login` in another process — is the one used. + const mark = loginMark(o.instance) + let held: ReturnType + try { + held = heldLogin(o.instance) + } catch (e) { + if (!(e instanceof LinkError)) throw e + base = "" + const stopped = status("stopped", e.code, e.message) + if (await healed(mark)) continue + return finish(o.signal?.aborted ? status("stopped", "stopped", "stopped") : stopped) + } + const { instance, token } = held + base = instance.base_url + const host = new URL(base).host + // The CA the login was given, as a full path (an older login kept what was typed: relative, or + // with ~, which a service started elsewhere does not find). One that is gone is said, not skipped. + const caPath = instance.ca ? resolvePath(expandHome(instance.ca)) : undefined + const caGone = caPath && !existsSync(caPath) ? caPath : undefined + const loginCa = caPath && !caGone ? readFileSync(caPath, "utf8") : undefined + attempts++ - status("connecting") + status("connecting", "connecting") // What the instance speaks now: asked at every dial, since it may have been updated // since the login; what was said last when it cannot be asked. let protocols = instances()[instance.connection]?.protocols ?? instance.protocols // What the socket trusts is what discovery just got through with: the login's CA, or the // system's bundle when the instance's certificate needs it (Bun's own roots do not hold a - // private CA). Why discovery failed is why the dial will, said in the status. + // private CA). Why discovery failed is why a dial would, so none is made. let ca = loginCa - let why: string | undefined - let older: string | undefined + let outcome: Outcome | undefined try { const found = await discover(instance.base_url, loginCa ? { ca: caPath! } : undefined) protocols = spoken(found.discovery) - rememberProtocols(instance.connection, protocols) + rememberProtocols(instance.connection, protocols, found.discovery.min_clients) if (found.tls?.ca && found.tls.ca !== caPath) ca = readFileSync(found.tls.ca, "utf8") } catch (e) { - why = (e as Error).message + const why = (e as Error).message // A server that answers and speaks another protocol: no dial would get further. - if (e instanceof ProtocolError) older = why + if (e instanceof ProtocolError) { + const stopped = status("stopped", e.code, why) + if (await healed(mark)) continue + return finish(o.signal?.aborted ? status("stopped", "stopped", "stopped") : stopped) + } + const detail = [caGone && `the CA file given at login, ${caGone}, is not there`, why].filter(Boolean).join("; ") + outcome = { kind: "dropped", code: e instanceof LembasError ? e.code : "unreachable", detail, healthy: false } } - if (older) { - clearInterval(freshen) - return status("stopped", older) - } - const unreachable = [caGone && `the CA file given at login, ${caGone}, is not there`, why ?? "could not reach the instance"].filter(Boolean).join("; ") + if (o.signal?.aborted) break const protocol = linkProtocol(protocols) - const outcome = await new Promise<{ refused?: string; dropped?: string; final?: boolean; changed?: boolean }>((resolve) => { + outcome ??= await new Promise((resolve) => { let opened = false let changed = false + let done = false + /** When `initialize` was answered: only then is this a link. */ + let linkedAt = 0 + /** Why this end closed it, when it did: the handshake ran out, or nothing was heard. */ + let gaveUp: { code: Code; detail: string } | undefined + let heard = Date.now() let watch: ReturnType | undefined + let alive: ReturnType | undefined const ws = new WebSocket(linkUrl(instance), { - headers: { authorization: `Bearer ${token}`, "user-agent": `lembas-cli/${VERSION}` }, + headers: { authorization: `Bearer ${token}`, "user-agent": USER_AGENT }, ...(ca ? { tls: { ca } } : {}), } as unknown as string[]) const stop = () => ws.close() + const end = (out: Outcome) => { + if (done) return + done = true + o.signal?.removeEventListener("abort", stop) + clearInterval(watch) + clearInterval(alive) + clearTimeout(deadline) + resolve(out) + } + /** Close a socket the other end may never answer on again: a close handshake with a peer + * that is gone would wait for ever, so the outcome is said now. */ + const giveUp = (code: Code, detail: string) => { + gaveUp = { code, detail } + const hard = (ws as unknown as { terminate?: () => void }).terminate + try { + if (hard) hard.call(ws) + else ws.close() + } catch {} + end({ kind: "dropped", code, detail, healthy: false }) + } o.signal?.addEventListener("abort", stop, { once: true }) + // Connect and handshake together (connection.md §7): the upgrade, the hello, and the + // instance's `initialize` answered here. A socket that hangs half-way is not waited on. + const deadline = setTimeout(() => giveUp("timeout", `${host} did not finish linking in ${Math.round(T.handshake / 1000)} s`), T.handshake) + const life = () => (heard = Date.now()) + ws.addEventListener("message", life) + ws.addEventListener("pong" as "message", life) + ws.addEventListener("ping" as "message", life) ws.addEventListener("open", () => { opened = true - wait = first + life() const peer = new Peer(wsTransport(ws)) - new AcpAgent(peer, limits, instance.connection, o.hub, protocol) + const agent = new AcpAgent(peer, limits, instance.connection, o.hub, protocol) + // Linked once the instance's `initialize` was answered — not at the open socket, which the + // instance accepts before it has judged the token. + agent.onInitialized = () => { + if (done || linkedAt) return + linkedAt = Date.now() + clearTimeout(deadline) + status("linked", "linked") + } peer.notify("_lembas/hello", { protocol, version: VERSION, @@ -207,7 +340,6 @@ export async function runLink(o: LinkOptions = {}): Promise { device: { host: hostname(), platform: `${process.platform}-${process.arch}` }, limits: { roots: limits.roots, max_mode: limits.maxMode, require_trust: limits.requireTrust, scheduled: limits.scheduled === true, files_that_run_code: limits.filesThatRunCode === true }, }) - status("linked") // The limits apply at once, each time they are looked at. What the instance was told at // 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. @@ -218,35 +350,71 @@ export async function runLink(o: LinkOptions = {}): Promise { ws.close() }, poll) watch.unref?.() + // Liveness (connection.md §7): a ping every so often, and anything heard is life. A link + // that died without a close — a cable, a sleeping laptop, a proxy that forgot it — would + // otherwise say `linked` for ever. + alive = setInterval(() => { + if (Date.now() - heard >= T.silence) return giveUp("timeout", `nothing was heard from ${host} for ${Math.round(T.silence / 1000)} s`) + try { + ;(ws as unknown as { ping?: () => void }).ping?.() + } catch {} + }, T.ping) + alive.unref?.() }) ws.addEventListener("close", (e) => { - o.signal?.removeEventListener("abort", stop) - clearInterval(watch) - if (changed) return resolve({ changed: true }) + if (changed) return end({ kind: "changed" }) + if (gaveUp) return end({ kind: "dropped", ...gaveUp, healthy: false }) + const close = CONNECTION.link.close + // 4409: a newer link of this same device took this one's place. Dialling again would take + // it back, and the two would close each other for ever. + if (e.code === close.replaced) return end({ kind: "replaced", reason: e.reason }) // 4401/4403: the instance's word that this token is done; 1008 policy, likewise. - if ([4401, 4403, 1008].includes(e.code)) return resolve({ refused: e.reason || "the instance refused this device's token" }) + if (close.refused.includes(e.code)) return end({ kind: "refused", reason: e.reason || "the instance refused this device's token" }) // 4400: the hello's protocol is not one it speaks. Dialling again would say the same. - if (e.code === 4400) return resolve({ refused: `the instance does not speak link protocol ${protocol}, which this LLeMbas CLI ${VERSION} speaks: it needs a LLeMbas 2.0 server — update the server, or use LLeMbas CLI 1.x with it${e.reason ? ` (${e.reason})` : ""}`, final: true }) - resolve({ dropped: opened ? `the link dropped (${e.code}${e.reason ? `: ${e.reason}` : ""})` : unreachable }) + if (e.code === close.protocol) return end({ kind: "protocol", reason: e.reason }) + const healthy = linkedAt > 0 && Date.now() - linkedAt >= T.healthy + end({ kind: "dropped", code: codeFor({ kind: "close", code: e.code }) ?? "unreachable", detail: opened ? `the link dropped (${e.code}${e.reason ? `: ${e.reason}` : ""})` : `${sentence("unreachable", { host })} (the link could not be opened)`, healthy }) }) ws.addEventListener("error", () => {}) }) if (o.signal?.aborted) break - if (outcome.changed) { - status("waiting", "the remote settings changed; linking again") - wait = first + if (outcome.kind === "changed") { + status("waiting", "connecting", "the remote settings changed; linking again") continue } - if (outcome.refused) { - clearInterval(freshen) - return status("stopped", outcome.final ? outcome.refused : `${outcome.refused} — sign in again: lembas login`) + if (outcome.kind === "refused") { + // Refused — but with which token? Signed in again since this dial began (`lembas login` + // replaces the token and signs the old one out, which is what closed this link): the new + // one has not been tried, so it is, at once. + if (loginMark(o.instance) !== mark && loginMark(o.instance)) { + status("waiting", "connecting", "the sign-in kept here changed; linking again with it") + failures = 0 + continue + } + const stopped = status("stopped", "signed_out", `${sentence("signed_out", { host })} (${outcome.reason})`) + if (await healed(mark)) continue + return finish(o.signal?.aborted ? status("stopped", "stopped", "stopped") : stopped) } - status("waiting", `${outcome.dropped}; trying again in ${Math.round(wait / 1000)}s`) + if (outcome.kind === "replaced") { + const stopped = status("stopped", "replaced", `${sentence("replaced", { host })}${outcome.reason ? ` (${outcome.reason})` : ""}`) + if (await healed(mark)) continue + return finish(o.signal?.aborted ? status("stopped", "stopped", "stopped") : stopped) + } + if (outcome.kind === "protocol") { + const said = `the instance does not speak link protocol ${protocol}, which this LLeMbas CLI ${VERSION} speaks: it needs a LLeMbas 2.0 server — update the server, or use LLeMbas CLI 1.x with it${outcome.reason ? ` (${outcome.reason})` : ""}` + const stopped = status("stopped", "server_too_old", said) + if (await healed(mark)) continue + return finish(o.signal?.aborted ? status("stopped", "stopped", "stopped") : stopped) + } + // Dropped, or never made. The wait starts over only after a link that stayed healthy + // (connection.md §9): one that opens and is closed a moment later — a handshake the instance + // gives up on, a message it will not take — grows the wait like any other failure. + failures = outcome.healthy ? 1 : failures + 1 + const wait = reconnectWait(failures, T.random(), first, ceiling) + status("waiting", outcome.code, `${outcome.detail}; trying again in ${wait < 1000 ? `${wait} ms` : `${Math.round(wait / 1000)} s`}`) await sleep(wait, o.signal) - wait = Math.min(ceiling, wait * 2) } - clearInterval(freshen) - return status("stopped", "stopped") + return finish(status("stopped", "stopped", "stopped")) } /** Wait, or stop waiting when `signal` aborts. */ diff --git a/src/acp/rpc.ts b/src/acp/rpc.ts index d85643d..66c028a 100644 --- a/src/acp/rpc.ts +++ b/src/acp/rpc.ts @@ -3,6 +3,8 @@ // answer with the same id. Written here rather than taken from the ACP SDK so the same few rules // are what LLeMbas implements in Python, and nothing about them is hidden in a dependency. +import { CONNECTION } from "../lembas/connection.ts" + export interface Transport { send(text: string): void onMessage(fn: (text: string) => void): void @@ -139,13 +141,20 @@ export class Peer { } } +/** The longest line read from a client (harness connection.json `stdio.line_bytes`). Counted in + * characters of the decoded text, which are never more than its bytes: a line within the limit + * is never refused. */ +const MAX_LINE = CONNECTION.stdio.line_bytes + /** Newline-delimited JSON on a pair of streams: ACP over stdio. */ -export function stdioTransport(input: NodeJS.ReadableStream = process.stdin, output: NodeJS.WritableStream = process.stdout): Transport { +export function stdioTransport(input: NodeJS.ReadableStream = process.stdin, output: NodeJS.WritableStream = process.stdout, maxLine = MAX_LINE): Transport { let onMsg: (t: string) => void = () => {} let onEnd: () => void = () => {} let buf = "" + let over = false input.setEncoding?.("utf8") input.on("data", (chunk: string | Buffer) => { + if (over) return buf += chunk.toString() let nl: number while ((nl = buf.indexOf("\n")) >= 0) { @@ -153,8 +162,16 @@ export function stdioTransport(input: NodeJS.ReadableStream = process.stdin, out buf = buf.slice(nl + 1) if (line) onMsg(line) } + // A line with no end in sight is not a message: a client that never sends the newline would + // otherwise be read into memory until there is none. The connection is given up, and said. + if (buf.length > maxLine) { + over = true + buf = "" + console.error(`lembas: the client sent a line longer than ${Math.round(maxLine / (1024 * 1024))} MB without ending it; closing`) + onEnd() + } }) - input.on("end", () => onEnd()) + input.on("end", () => !over && onEnd()) return { send: (text) => void output.write(text + "\n"), onMessage: (fn) => (onMsg = fn), diff --git a/src/app.ts b/src/app.ts index 5c87c25..4589a22 100644 --- a/src/app.ts +++ b/src/app.ts @@ -41,6 +41,7 @@ import { VERSION } from "./version.ts" import { Settings } from "./settings.ts" import { Library, type Embedder } from "./library/store.ts" import { instances as lembasInstances, keyFile as lembasKeyFile } from "./lembas/login.ts" +import { USER_AGENT } from "./lembas/connection.ts" import { PERSONAL_KEYS, personalConfig, pushPersonalization } from "./lembas/personal.ts" import type { Plan } from "./plan/plan.ts" import { LIBRARY_SERVER, mcpInstructions } from "./mcp/index.ts" @@ -213,7 +214,7 @@ function lembasLibraryServer(warnings: string[]): (McpServer & { source: "global return { url: `${one.base_url}/mcp`, // The token itself, read now: the config's {file:} substitution has already run by here. - headers: { authorization: `Bearer ${readFileSync(lembasKeyFile(one.connection), "utf8").trim()}` }, + headers: { authorization: `Bearer ${readFileSync(lembasKeyFile(one.connection), "utf8").trim()}`, "user-agent": USER_AGENT }, transport: "http", oauth: false, // The memory tool alone; the resource is read for the prompt, not offered to the model. diff --git a/src/bus/index.ts b/src/bus/index.ts index 30f2b09..ecd9738 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -89,7 +89,9 @@ export type Event = | { type: "flash"; text: string } /** A setting changed (/settings, the settings tool, a command): front ends redraw what shows it. */ | { type: "setting"; key: string; value: unknown } - | { type: "error"; message: string } + /** The turn failed. `code`: why, as one of the harness's connection codes (`unreachable`, + * `signed_out`, `server_error`, … or `failed`). */ + | { type: "error"; message: string; code?: string } | { type: "done"; reason: "stop" | "steps" | "budget" | "cancelled" | "error" } /** What went with a prompt, as a client shows it: a chip, not the content. */ diff --git a/src/cli.ts b/src/cli.ts index a97ffa9..7500c5b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -124,7 +124,9 @@ async function loginCommand(cmd: "login" | "logout", args: string[]) { const known = instances() const json = cmd === "login" && values.json const emit = (o: object) => console.log(JSON.stringify(o)) - const sameBase = (a: string, b: string) => a.replace(/^https?:\/\//, "").replace(/\/+$/, "") === b.replace(/^https?:\/\//, "").replace(/\/+$/, "") + // "Is this the server I am already logged in to": the one address rule, both sides normalised + // (harness connection.md §1) — never a comparison of what happened to be typed and stored. + const { sameServer: sameBase } = await import("./lembas/connection.ts") if (cmd === "login" && (values["token-stdin"] || values.server !== undefined)) { const usage = "usage: … | lembas login --token-stdin --server [--json] [--ca file]" if (!values["token-stdin"]) fail(`--server goes with --token-stdin (${usage}); a sign-in by code is lembas login
`, 2) @@ -189,7 +191,8 @@ async function loginCommand(cmd: "login" | "logout", args: string[]) { else console.log(loginSummary(r, true).join("\n")) } catch (e) { if (e instanceof LembasError) { - if (json) emit({ event: "error", message: e.message }) + // `code`: what a program driving the login reads (harness connection.md §10) — never the sentence. + if (json) emit({ event: "error", code: e.code, message: e.message }) fail(e.message) } throw e @@ -282,6 +285,9 @@ async function main() { // stdout is the protocol: anything else printed would corrupt it, so it goes to stderr. console.log = (...a: unknown[]) => console.error(...a) const peer = new Peer(stdioTransport()) + // What the server says of itself now (its minimum for each client), kept with the login for + // `initialize` to pass on; not waited for. + void import("./lembas/login.ts").then((m) => m.refreshDiscovery()) new AcpAgent(peer) await new Promise((resolve) => peer.onClose(resolve)) process.exit(0) diff --git a/src/lembas/client.ts b/src/lembas/client.ts index 872986d..049f6f4 100644 --- a/src/lembas/client.ts +++ b/src/lembas/client.ts @@ -8,6 +8,7 @@ import { existsSync, readFileSync } from "node:fs" import { hostname } from "node:os" import { VERSION } from "../version.ts" +import { belowMinimum, CONNECTION, judgeVersions, minimumFor, normalise as oneRule, onOrigin, retryAfter, sentence, tokenRefused, USER_AGENT, type Code } from "./connection.ts" /** The device protocol this build speaks (LLeMbas `services/device_link.py:PROTOCOL`): 3, the * same number as the link's `_lembas/*` extension (acp/agent.ts LEMBAS_PROTOCOL). */ @@ -17,21 +18,47 @@ export const PROTOCOL = 3 * on what to update (harness/acp.md *Versions*). */ export const PROTOCOLS = [3] -/** What this CLI says to a server that does not speak its protocol — at login, and at a dial: a - * 1.x server (1 and 2) needs updating, a newer one needs a newer CLI. */ -export function protocolMismatch(base: string, d: Pick): string { - const theirs = Array.isArray(d.protocols) && d.protocols.length ? d.protocols : [d.protocol] - const said = `${base} runs LLeMbas ${d.version ?? "(an unknown version)"}, which speaks link protocol ${theirs.join(" and ")}` - if (theirs.every((p) => p > PROTOCOL)) return `${said}; this LLeMbas CLI ${VERSION} speaks ${PROTOCOL}. Update LLeMbas CLI (lembas update).` - return `${said}; this LLeMbas CLI ${VERSION} needs a LLeMbas 2.0 server (protocol ${PROTOCOL}). Update the server, or use LLeMbas CLI 1.x with it.` +/** What the server lists as its link protocols: `protocols` where it says, else `protocol`. */ +const listed = (d: Pick): number[] => (Array.isArray(d.protocols) && d.protocols.length ? d.protocols : [d.protocol]) + +/** What this CLI says to a server that does not speak its protocol — at login, and at a dial — + * and which side is the old one (harness connection.md §5): a 1.x server (1 and 2) needs + * updating, a newer one needs a newer CLI. The numbers follow the sentence, for whoever reads a log. */ +export function protocolMismatch(base: string, d: Pick): { code: "server_too_old" | "client_too_old"; message: string } { + const theirs = listed(d) + const code = judgeVersions(PROTOCOLS, theirs).verdict === "client_too_old" ? "client_too_old" : "server_too_old" + return { code, message: `${sentence(code, { host: hostOf(base), version: d.version })} (it speaks link protocol ${theirs.join(" and ")}; LLeMbas CLI ${VERSION} speaks ${PROTOCOLS.join(" and ")})` } } -export class LembasError extends Error {} +/** A failure talking to the server, with its machine code (harness connection.json `codes`): + * what `lembas login --json` and the service's status file say beside the sentence. */ +export class LembasError extends Error { + constructor( + message: string, + readonly code: Code = "failed", + /** A 429's `Retry-After`, in seconds. */ + readonly retryAfter?: number, + ) { + super(message) + } +} /** The instance answered 401: the token this machine holds is revoked or unknown there. `login` signs in afresh. */ -export class SignInRejected extends LembasError {} +export class SignInRejected extends LembasError { + constructor(message: string) { + super(message, "signed_out") + } +} /** The server and this CLI speak no link protocol in common: no login, and no dial gets further. */ export class ProtocolError extends LembasError {} +const hostOf = (url: string): string => { + try { + return new URL(url).host + } catch { + return url + } +} + export interface Discovery { service: "lembas" version: string @@ -44,7 +71,12 @@ export interface Discovery { * lowest, so a client that compares it for equality still logs in). */ protocols?: number[] harness_spec: string + /** The server's own idea of its address. Advisory: shown and logged, never stored and never + * compared — what is stored is the address the person typed (harness connection.md §1). */ base_url: string + /** The lowest version of each product the server still serves (connection.md §5): + * `{ cli: "2.0.0" }`. Absent, or without this product: no minimum. */ + min_clients?: Record api: { openai: string; instance?: string } login: { device: { code: string; token: string; verify: string } } } @@ -101,42 +133,65 @@ function untrusted(e: unknown): boolean { return /CERT|SIGNATURE|SELF_SIGNED|UNABLE_TO_GET_ISSUER/.test(code) } -async function call(url: string, init: RequestInit, tls: Tls | undefined, timeoutMs = 15_000, signal?: AbortSignal): Promise { +/** One request to the instance. Every one says who is asking (`User-Agent: llembas-cli/`, + * harness connection.md §3), and a failure to get an answer is one of three codes with the + * spec's own sentence. */ +async function call(url: string, init: RequestInit, tls: Tls | undefined, timeoutMs = DISCOVERY_MS, signal?: AbortSignal): Promise { + const headers = { "user-agent": USER_AGENT, ...(init.headers as Record | undefined) } try { - return await fetch(url, { ...init, ...tlsInit(tls), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) } as RequestInit) + return await fetch(url, { ...init, headers, ...tlsInit(tls), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) } as RequestInit) } catch (e) { // Stopped by whoever asked (a newer autocomplete request): theirs to handle, not a failure to reach. if (signal?.aborted) throw e - if (untrusted(e)) throw new LembasError(`the TLS certificate of ${new URL(url).host} is not trusted. Pass --ca with the CA that signed it.`) - if ((e as Error).name === "TimeoutError") throw new LembasError(`${new URL(url).host} did not answer in time`) - throw new LembasError(`cannot reach ${new URL(url).host}: ${(e as Error).message}`) + const host = hostOf(url) + if (untrusted(e)) throw new LembasError(sentence("tls_untrusted", { host }), "tls_untrusted") + if ((e as Error).name === "TimeoutError") throw new LembasError(sentence("timeout", { host }), "timeout") + throw new LembasError(`${sentence("unreachable", { host })} (${(e as Error).message})`, "unreachable") } } +const DISCOVERY_MS = CONNECTION.discovery.timeout_s * 1000 + +/** Whether an answer is the instance refusing the token that was sent: a 401 with its own + * challenge (harness connection.md §6). A 401 without it came from further along — a model's + * provider, whose status the instance's /v1 passes through — and signs nobody out. */ +export const signedOut = (res: Response): boolean => res.status === 401 && tokenRefused(res.headers.get("www-authenticate")) + +/** A 401, thrown as what it is: the sign-in refused (`SignInRejected`), or — without the + * instance's challenge — a failure in the instance's own words, with nobody signed out. */ +async function unauthorised(res: Response, what: string): Promise { + if (signedOut(res)) throw new SignInRejected("the instance no longer accepts this sign-in — run login again") + const said = await res + .json() + .then((b: any) => (typeof b?.error?.message === "string" ? b.error.message : typeof b?.detail === "string" ? b.detail : "")) + .catch(() => "") + throw new LembasError(`${what}: ${said.trim().slice(0, 300) || "401, and not from the instance itself (it did not refuse this sign-in)"}`, "failed") +} + +/** A 429 as the error every caller here throws for one: `busy`, with what `Retry-After` said. */ +export function busy(url: string, res: Response): LembasError { + return new LembasError(sentence("busy", { host: hostOf(url) }), "busy", retryAfter(res.headers.get("retry-after"))) +} + /** One request to the instance with the device's token, its JSON answer and status (spec 3.5.0: * the schedule routes of /api/v2). A body that is not JSON is null. */ -export async function apiCall(base: string, token: string, tls: Tls | undefined, method: string, path: string, body?: unknown, timeoutMs = 30_000, signal?: AbortSignal): Promise<{ status: number; json: any }> { +export async function apiCall(base: string, token: string, tls: Tls | undefined, method: string, path: string, body?: unknown, timeoutMs = 30_000, signal?: AbortSignal): Promise<{ status: number; json: any; signedOut: boolean; retryAfter?: number }> { const headers: Record = { authorization: `Bearer ${token}`, accept: "application/json" } if (body !== undefined) headers["content-type"] = "application/json" const res = await call(`${base}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }, tls, timeoutMs, signal) const json = res.status === 204 ? null : await res.json().catch(() => null) - return { status: res.status, json } + // `signedOut`: the 401 is the instance's own refusal of this token, not one passed through. + return { status: res.status, json, signedOut: signedOut(res), ...(res.status === 429 ? { retryAfter: retryAfter(res.headers.get("retry-after")) } : {}) } } -/** What a person typed, as a base address: a scheme added (https unless they said http), the path - * and a trailing slash dropped. */ +/** What a person typed, as a base address — the one rule (connection.ts `address`) — as this + * module's own error, naming what was typed. */ export function normalise(address: string): string { - let a = address.trim() - if (!a) throw new LembasError("an instance address is needed, e.g. ai.example.org") - if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(a)) a = `https://${a}` - let u: URL try { - u = new URL(a) + return oneRule(address) } catch { - throw new LembasError(`${address} is not an address`) + throw new LembasError(`${address.trim() ? `${address.trim()}: ` : ""}${sentence("invalid_address")}`, "invalid_address") } - if (u.protocol !== "https:" && u.protocol !== "http:") throw new LembasError(`${address}: only http and https`) - return `${u.protocol}//${u.host}` } /** Find the instance. With no CA given and an untrusted certificate, the system's own bundle is @@ -144,7 +199,7 @@ export function normalise(address: string): string { * connection written afterwards uses it too. */ /** The protocols both this CLI and the instance speak: `protocols` where it says, else `protocol`. */ export function spoken(d: Pick): number[] { - const theirs = Array.isArray(d.protocols) && d.protocols.length ? d.protocols : [d.protocol] + const theirs = listed(d) return PROTOCOLS.filter((p) => theirs.includes(p)) } @@ -154,31 +209,44 @@ export function linkProtocol(_protocols?: number[]): number { return PROTOCOL } -export async function discover(address: string, tls?: Tls): Promise<{ discovery: Discovery; tls?: Tls }> { +export async function discover(address: string, tls?: Tls): Promise<{ discovery: Discovery; tls?: Tls; base: string }> { const base = normalise(address) - const url = `${base}/.well-known/lembas.json` + const host = hostOf(base) + const url = `${base}${CONNECTION.discovery.path}` let res: Response let used = tls try { res = await call(url, { headers: { accept: "application/json" } }, tls) } catch (e) { const bundle = SYSTEM_BUNDLES.find((f) => existsSync(f)) - if (tls?.ca || !bundle || !(e instanceof LembasError) || !/not trusted/.test(e.message)) throw e + if (tls?.ca || !bundle || !(e instanceof LembasError) || e.code !== "tls_untrusted") throw e used = { ca: bundle } res = await call(url, { headers: { accept: "application/json" } }, used) } - if (res.status === 404) throw new LembasError(`${base} answers, but is not a LLeMbas instance (no /.well-known/lembas.json)`) - if (!res.ok) throw new LembasError(`${base}: ${res.status} ${res.statusText}`) + // Three different things, never one sentence: it is not LLeMbas (404, or an answer that is not + // its discovery), it is LLeMbas and failing (any other status), or it is fine. + const notLembas = (why: string) => new LembasError(`${sentence("not_lembas", { host })} (${why})`, "not_lembas") + if (res.status === 404) throw notLembas(`no ${CONNECTION.discovery.path}`) + if (res.status === 429) throw busy(url, res) + if (!res.ok) throw new LembasError(sentence("server_error", { host, status: res.status }), "server_error") let body: Discovery try { body = (await res.json()) as Discovery } catch { - throw new LembasError(`${base} answered /.well-known/lembas.json with something that is not JSON`) + throw notLembas(`${CONNECTION.discovery.path} is not JSON`) } - if (body?.service !== "lembas") throw new LembasError(`${base} is not a LLeMbas instance`) - if (!spoken(body).length) throw new ProtocolError(protocolMismatch(base, body)) + if (body?.service !== "lembas") throw notLembas(`${CONNECTION.discovery.path} does not say it is`) + if (!spoken(body).length) { + const m = protocolMismatch(base, body) + throw new ProtocolError(m.message, m.code) + } + // Below the lowest version of this product the server still serves: said here, with both + // versions and what to do, and nothing goes on. + const minimum = minimumFor(body.min_clients, "cli") + if (belowMinimum(VERSION, minimum).verdict === "client_too_old") + throw new ProtocolError(sentence("client_too_old", { host, minimum: true, needed: minimum, mine: VERSION }), "client_too_old") if (!body.login?.device?.code) throw new LembasError(`${base} offers no device login`) - return { discovery: body, tls: used } + return { discovery: body, tls: used, base } } export interface DeviceStart { @@ -190,14 +258,24 @@ export interface DeviceStart { interval: number } -export async function startDevice(d: Discovery, tls: Tls | undefined, scopes = ["models", "memory", "link"]): Promise { +/** An endpoint discovery names, to call: only on the server that was asked (harness + * connection.md §2). Where to sign in is the server's to say — on itself, and nowhere else: an + * address on another origin would take the sign-in, and then the token, somewhere nobody typed. */ +export function endpoint(base: string, url: unknown): string { + if (onOrigin(base, url)) return url as string + throw new LembasError(sentence("other_origin", { host: hostOf(base), other: typeof url === "string" && url ? url.slice(0, 200) : "none" }), "other_origin") +} + +export async function startDevice(d: Discovery, tls: Tls | undefined, base: string, scopes = ["models", "memory", "link"]): Promise { + // Both are checked before anything is sent: a code is not started that could not be finished. + endpoint(base, d.login.device.token) const res = await call( - d.login.device.code, + endpoint(base, d.login.device.code), { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify({ - client_id: `lembas-cli ${VERSION}`, + client_id: USER_AGENT, // The machine's name alone: the program is said by client_id, and the web UI shows this // where room is short. device_name: hostname(), @@ -209,7 +287,8 @@ export async function startDevice(d: Discovery, tls: Tls | undefined, scopes = [ tls, ) const body = (await res.json().catch(() => ({}))) as DeviceStart & { error?: string; error_description?: string } - if (!res.ok) throw new LembasError(body.error_description ?? body.error ?? `${res.status} ${res.statusText}`) + if (res.status === 429) throw busy(base, res) + if (!res.ok) throw new LembasError(body.error_description ?? body.error ?? `${res.status} ${res.statusText}`, res.status >= 500 ? "server_error" : "failed") return body } @@ -221,7 +300,8 @@ export interface Granted { } /** Poll until the person decides, the code runs out, or `signal` stops it. */ -export async function awaitToken(d: Discovery, start: DeviceStart, tls: Tls | undefined, opts: { signal?: AbortSignal; sleep?: (ms: number) => Promise } = {}): Promise { +export async function awaitToken(d: Discovery, start: DeviceStart, tls: Tls | undefined, base: string, opts: { signal?: AbortSignal; sleep?: (ms: number) => Promise } = {}): Promise { + const tokenUrl = endpoint(base, d.login.device.token) const sleep = opts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))) let interval = Math.max(1, start.interval || 5) const deadline = Date.now() + Math.max(1, start.expires_in) * 1000 @@ -229,7 +309,7 @@ export async function awaitToken(d: Discovery, start: DeviceStart, tls: Tls | un await sleep(interval * 1000) if (opts.signal?.aborted) throw new LembasError("cancelled") const res = await call( - d.login.device.token, + tokenUrl, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, @@ -246,14 +326,22 @@ export async function awaitToken(d: Discovery, start: DeviceStart, tls: Tls | un interval += 5 continue case "access_denied": - throw new LembasError("the sign-in was denied on the instance") + throw new LembasError("the sign-in was denied on the instance", "not_allowed") case "expired_token": - throw new LembasError("the code expired before it was approved — run login again") + throw new LembasError("the code expired before it was approved — run login again", "expired") default: - throw new LembasError(`the instance refused the sign-in: ${body.error ?? `${res.status} ${res.statusText}`}`) + // Too many polls, or a server that fails for a moment: not the end of the sign-in. The + // code is still good until it runs out, so wait — what Retry-After says, else one more + // interval — and ask again. + if (res.status === 429 || res.status >= 500) { + const more = retryAfter(res.headers.get("retry-after")) + if (more) await sleep(more * 1000) + continue + } + throw new LembasError(`the instance refused the sign-in: ${body.error ?? `${res.status} ${res.statusText}`}`, res.status === 403 ? "not_allowed" : "failed") } } - throw new LembasError("the code expired before it was approved — run login again") + throw new LembasError("the code expired before it was approved — run login again", "expired") } /** The scopes a token carries, as the instance granted them (`models memory link`). */ @@ -266,29 +354,31 @@ export function scopesOf(scope: string | undefined): string[] { * return it as a device login's poll would have. A token that cannot link is refused: it would * give this machine models but no agent chats, and the program handing it over is after the * agent. Nothing is written by this. */ -export async function checkToken(d: Discovery, token: string, tls: Tls | undefined): Promise { - const base = d.base_url +export async function checkToken(d: Discovery, token: string, tls: Tls | undefined, base: string): Promise { const host = new URL(base).host const res = await call(`${base}/api/v1/instance`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls) const older = `${base} runs LLeMbas ${d.version}, which cannot say what a token may do: lembas login --token-stdin needs a newer LLeMbas 2.0 server. Update the server, or sign in with lembas login ${base}` - if (res.status === 401) throw new LembasError(`${host} does not accept this token: it is revoked, expired, or not one of this instance's`) - if (res.status === 403) throw new LembasError(`${host} refused this token for its models: it needs the models scope, and the account the “Use the API” permission`) - if (res.status === 404) throw new LembasError(older) - if (!res.ok) throw new LembasError(`checking the token: ${res.status} ${res.statusText}`) + if (signedOut(res)) throw new LembasError(`${host} does not accept this token: it is revoked, expired, or not one of this instance's`, "signed_out") + if (res.status === 401) await unauthorised(res, "checking the token") + if (res.status === 403) throw new LembasError(`${host} refused this token for its models: it needs the models scope, and the account the “Use the API” permission`, "not_allowed") + if (res.status === 404) throw new LembasError(older, "server_too_old") + if (res.status === 429) throw busy(base, res) + if (!res.ok) throw new LembasError(`checking the token: ${res.status} ${res.statusText}`, res.status >= 500 ? "server_error" : "failed") const body = (await res.json().catch(() => undefined)) as (InstanceInfo & { scope?: unknown; account?: { email?: string; name?: string } }) | undefined - if (!body || typeof body !== "object" || typeof body.scope !== "string") throw new LembasError(older) + if (!body || typeof body !== "object" || typeof body.scope !== "string") throw new LembasError(older, "server_too_old") const scopes = scopesOf(body.scope) if (!scopes.includes("link")) - throw new LembasError(`this token cannot link this machine to ${host}: it carries ${scopes.length ? scopes.join(" ") : "no scope"}, and LLeMbas CLI's needs link (models memory link). Sign in with lembas login ${base} instead`) + throw new LembasError(`this token cannot link this machine to ${host}: it carries ${scopes.length ? scopes.join(" ") : "no scope"}, and LLeMbas CLI's needs link (models memory link). Sign in with lembas login ${base} instead`, "not_allowed") const account = body.account && typeof body.account === "object" ? { email: body.account.email, name: body.account.name } : {} return { access_token: token, scope: scopes.join(" "), account, base_url: base } } export async function models(d: { api: { openai: string } }, token: string, tls: Tls | undefined, timeoutMs?: number): Promise { const res = await call(`${d.api.openai}/models`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs) - if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again") - if (res.status === 403) throw new LembasError("this account may not use the instance's models through the API (the “Use the API” permission)") - if (!res.ok) throw new LembasError(`listing the models: ${res.status} ${res.statusText}`) + if (res.status === 401) await unauthorised(res, "listing the models") + if (res.status === 403) throw new LembasError("this account may not use the instance's models through the API (the “Use the API” permission)", "not_allowed") + if (res.status === 429) throw busy(d.api.openai, res) + if (!res.ok) throw new LembasError(`listing the models: ${res.status} ${res.statusText}`, res.status >= 500 ? "server_error" : "failed") const body = (await res.json()) as { data?: ServedModel[] } return Array.isArray(body.data) ? body.data : [] } @@ -311,7 +401,7 @@ export interface InstanceInfo { export async function instanceInfo(base: string, token: string, tls: Tls | undefined, timeoutMs?: number): Promise { const res = await call(`${base}/api/v1/instance`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs) if (res.status === 404) return undefined - if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again") + if (res.status === 401) await unauthorised(res, "reading the instance") if (!res.ok) throw new LembasError(`reading the instance: ${res.status} ${res.statusText}`) const body = (await res.json().catch(() => undefined)) as InstanceInfo | undefined return body && typeof body === "object" ? body : undefined @@ -359,7 +449,7 @@ export interface Usage { export async function usage(base: string, token: string, tls: Tls | undefined, timeoutMs = 5000): Promise { const res = await call(`${base}/v1/usage`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs) if (res.status === 404) return undefined - if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again") + if (res.status === 401) await unauthorised(res, "reading the usage") if (!res.ok) throw new LembasError(`reading the usage: ${res.status} ${res.statusText}`) const body = (await res.json().catch(() => undefined)) as Usage | undefined return body && typeof body === "object" ? body : undefined @@ -387,7 +477,7 @@ function asPersonalization(b: unknown): Personalization | undefined { export async function personalization(base: string, token: string, tls: Tls | undefined, timeoutMs = 5000): Promise { const res = await call(`${base}/v1/me/personalization`, { headers: { authorization: `Bearer ${token}`, accept: "application/json" } }, tls, timeoutMs) if (res.status === 404) return undefined - if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again") + if (res.status === 401) await unauthorised(res, "reading the personalization") if (!res.ok) throw new LembasError(`reading the personalization: ${res.status} ${res.statusText}`) return asPersonalization(await res.json().catch(() => undefined)) } @@ -411,7 +501,7 @@ export async function savePersonalization(base: string, token: string, tls: Tls if (res.status === 422) throw new LembasError(`the instance would not take that personalization${detail ? `: ${detail}` : ""}`) throw new LembasError(detail ? `the instance did not allow it: ${detail}` : "not allowed: the instance refused to save the personalization") } - if (res.status === 401) throw new SignInRejected("the instance no longer accepts this sign-in — run login again") + if (res.status === 401) await unauthorised(res, "saving the personalization") if (!res.ok) throw new LembasError(`saving the personalization: ${res.status} ${res.statusText}`) return asPersonalization(await res.json().catch(() => undefined)) } diff --git a/src/lembas/connection.ts b/src/lembas/connection.ts index 72803d3..d330ca2 100644 --- a/src/lembas/connection.ts +++ b/src/lembas/connection.ts @@ -80,6 +80,33 @@ export function sameServer(a: string, b: string): boolean { return x.base.replace(/^https?:/, "") === y.base.replace(/^https?:/, "") } +/** Whether a login kept here is for the server now being signed in to (connection.md §1). The + * stored address and the typed one are one server — or the stored one is from before the typed + * address was what is stored, when it was the `base_url` the server's discovery named: then the + * server still names it, and discovery of the typed address says so. Never the other way round: + * a server cannot claim a login by naming an address in its discovery that nobody stored. */ +export function sameLogin(stored: string, typed: string, discoveryBaseUrl?: unknown): boolean { + if (sameServer(stored, typed)) return true + if (typeof discoveryBaseUrl !== "string" || !discoveryBaseUrl.trim()) return false + try { + return address(stored).base === address(discoveryBaseUrl).base + } catch { + return false + } +} + +/** Whether `url` is on the server a base address names: same scheme, host and port. An endpoint + * discovery names anywhere else is not used (connection.md §2). */ +export function onOrigin(base: string, url: unknown): boolean { + if (typeof url !== "string") return false + try { + const u = address(url) + return u.scheme_given && u.base === address(base).base + } catch { + return false + } +} + // ---- versions ----------------------------------------------------------------------------- export interface Verdict { @@ -110,6 +137,49 @@ export function stdioProtocol(agent: number, client: unknown): { use: number; to return { use: Math.min(agent, said), told: said > agent } } +const RELEASE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z]+)\.(\d+))?$/ + +/** A product version as numbers: X.Y.Z, or X.Y.Z-.N (a pre-release, older than its X.Y.Z). + * Undefined for anything else. */ +function release(v: unknown): [number, number, number, string, number] | undefined { + const m = typeof v === "string" ? RELEASE.exec(v.trim()) : null + if (!m) return undefined + return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ?? "", m[5] === undefined ? 0 : Number(m[5])] +} + +/** Negative when version `a` is older than `b`; undefined when either is not a version. Numbers + * are compared as numbers, never as text; a pre-release is older than its release, and two + * pre-releases of one release compare by their word, then by their number. */ +export function compareReleases(a: unknown, b: unknown): number | undefined { + const x = release(a) + const y = release(b) + if (!x || !y) return undefined + for (const i of [0, 1, 2] as const) if (x[i] !== y[i]) return x[i] - y[i] + if (x[3] !== y[3]) return x[3] === "" ? 1 : y[3] === "" ? -1 : x[3] < y[3] ? -1 : 1 + return x[4] - y[4] +} + +/** `min_clients` (connection.md §5): whether this product's version is below the lowest the + * server still serves. No minimum, or a version on either side that cannot be read: not below — + * a server never locks out a client by a typing mistake in its own table. */ +export function belowMinimum(mine: unknown, minimum: unknown): { verdict: "ok" | "client_too_old" } { + const c = compareReleases(mine, minimum) + return { verdict: c !== undefined && c < 0 ? "client_too_old" : "ok" } +} + +/** The minimum a server's discovery names for one product, or undefined. */ +export function minimumFor(minClients: unknown, product: string | undefined): string | undefined { + if (!product || !minClients || typeof minClients !== "object" || Array.isArray(minClients)) return undefined + const v = (minClients as Record)[product] + return typeof v === "string" && release(v) ? v.trim() : undefined +} + +/** The product a client named itself as (`llembas-nvim`, `llembas-nvim/1.0.0`): `nvim`. */ +export function productOf(name: unknown): Product | undefined { + const m = typeof name === "string" ? /^llembas-([a-z]+)(?:\/.*)?$/.exec(name.trim()) : null + return m && m[1]! in SPEC.products ? (m[1] as Product) : undefined +} + // ---- codes and sentences ------------------------------------------------------------------ export interface Vars { @@ -117,6 +187,11 @@ export interface Vars { product?: Product version?: string needed?: string + /** This product's own version, and an address the server named: for the sentences that say them. */ + mine?: string + other?: string + /** The sentence for a client below the server's `min_clients`. */ + minimum?: boolean status?: number /** The sentence of a client of `lembas serve --stdio`, where a code has one. */ stdio?: boolean @@ -125,16 +200,18 @@ export interface Vars { /** A code's sentence for this product, with the product's own step after it. A variable nobody * gave reads as the plainest true thing ("the server"), never as a brace. */ export function sentence(code: Code, v: Vars = {}): string { - const entry = SPEC.codes[code] as { text: string; stdio?: string } + const entry = SPEC.codes[code] as { text: string; stdio?: string; minimum?: string } const product = v.product ?? "cli" const fill: Record = { host: v.host || "the server", product: SPEC.products[product], version: v.version || "(an unknown version)", needed: v.needed || "(a newer version)", + mine: v.mine || "(an unknown version)", + other: v.other || "another address", status: String(v.status ?? "an error"), } - let text = (v.stdio && entry.stdio ? entry.stdio : entry.text).replace(/\{(\w+)\}/g, (_, k: string) => fill[k] ?? "") + let text = (v.minimum && entry.minimum ? entry.minimum : v.stdio && entry.stdio ? entry.stdio : entry.text).replace(/\{(\w+)\}/g, (_, k: string) => fill[k] ?? "") // A sentence that begins with the stand-in for a host nobody named begins with a capital; a // host's own name is never changed. if (!v.host) text = text.charAt(0).toUpperCase() + text.slice(1) @@ -145,7 +222,7 @@ export function sentence(code: Code, v: Vars = {}): string { export type Condition = | { kind: "network"; error: "dns" | "refused" | "reset" | "timeout" | "tls" } | { kind: "discovery"; status: number; json?: boolean; service?: unknown } - | { kind: "http"; status: number; retry_after?: unknown } + | { kind: "http"; status: number; retry_after?: unknown; challenge?: unknown } | { kind: "close"; code: number } | { kind: "versions"; mine: unknown; theirs: unknown } | { kind: "state"; code: Code } @@ -160,7 +237,10 @@ export function codeFor(c: Condition): Code | null { if (c.status < 200 || c.status > 299) return "server_error" return c.json === false || c.service !== "lembas" ? "not_lembas" : null case "http": - if (c.status === 401) return "signed_out" + // A 401 is the server refusing the token only when it carries the server's own challenge: + // its /v1 routes pass a model provider's status through, and a provider's 401 is not a + // sign-out (connection.md §6). + if (c.status === 401) return tokenRefused(c.challenge) ? "signed_out" : "failed" if (c.status === 403) return "not_allowed" if (c.status === 429) return "busy" return c.status >= 500 ? "server_error" : null @@ -188,6 +268,17 @@ export function explain(c: Condition, v: Vars = {}): { code: Code; text: string; return c.kind === "http" && code === "busy" ? { code, text, retry_s: retryAfter(c.retry_after) ?? null } : { code, text } } +/** Whether a 401's `WWW-Authenticate` header is the LLeMbas server's own challenge — + * `Bearer realm="lembas"` — and so its word that the token sent is not accepted. The scheme in any + * case of letters, the realm quoted or not; any other 401 came from further along. */ +export function tokenRefused(challenge: unknown): boolean { + if (typeof challenge !== "string") return false + const m = /^\s*([A-Za-z]+)\s+(.*)$/s.exec(challenge) + if (!m || m[1]!.toLowerCase() !== SPEC.challenge.scheme.toLowerCase()) return false + const realm = /(?:^|[\s,])realm\s*=\s*(?:"([^"]*)"|([^\s,]+))/i.exec(m[2]!) + return (realm?.[1] ?? realm?.[2]) === SPEC.challenge.realm +} + /** `Retry-After` as whole seconds to wait: a number of seconds as the header gives it, at least 1 * and at most the ceiling. Undefined for a header that is absent or says anything else (a date * needs a clock both sides agree on: the client's own schedule is used instead). */ diff --git a/src/lembas/login.ts b/src/lembas/login.ts index c00f4f1..9bdc5cd 100644 --- a/src/lembas/login.ts +++ b/src/lembas/login.ts @@ -14,6 +14,7 @@ import { join, resolve } from "node:path" import { parseDocument } from "yaml" import { expandHome, globalPaths, isLocal, paths } from "../config/paths.ts" import { awaitToken, checkToken, discover, LembasError, SignInRejected, signOut, spoken, startDevice, type DeviceStart, type Discovery, type Granted, type InstanceInfo, type ServedModel, type Tls } from "./client.ts" +import { normalise as oneRule, sameLogin, sameServer } from "./connection.ts" import { dropCache, fetchWebui, isChatModel, readCache, specFor } from "./webui.ts" export interface Instance { @@ -31,6 +32,9 @@ export interface Instance { /** The link protocols the instance listed when last asked: at login, and again at every * dial of the link, so an instance updated later is picked up. */ protocols?: number[] + /** The lowest version of each product the instance still serves, as its discovery last said + * (harness connection.md §5): what `serve --stdio` tells an editor about its own product. */ + min_clients?: Record logged_in_at: string } @@ -53,17 +57,41 @@ export const keyFile = (connection: string) => { /** What a later look at the instance said it speaks, kept with the login (not for a login local * mode only reads). */ -export function rememberProtocols(connection: string, protocols: number[]) { +export function rememberProtocols(connection: string, protocols: number[], minClients?: unknown) { const all = ownInstances() const one = all[connection] - if (!one || JSON.stringify(one.protocols) === JSON.stringify(protocols)) return - saveIndex({ ...all, [connection]: { ...one, protocols } }) + if (!one) return + const min_clients = minimums(minClients) + if (JSON.stringify(one.protocols) === JSON.stringify(protocols) && JSON.stringify(one.min_clients ?? {}) === JSON.stringify(min_clients ?? {})) return + const { min_clients: _, ...rest } = one + saveIndex({ ...all, [connection]: { ...rest, protocols, ...(min_clients ? { min_clients } : {}) } }) +} + +/** Discovery's `min_clients` as what is kept: product → version, strings only, a handful. */ +function minimums(said: unknown): Record | undefined { + if (!said || typeof said !== "object" || Array.isArray(said)) return undefined + const out: Record = {} + for (const [k, v] of Object.entries(said as Record).slice(0, 32)) if (typeof v === "string" && /^[a-z]{1,20}$/.test(k) && v.length <= 40) out[k] = v + return Object.keys(out).length ? out : undefined +} + +/** A stored address, read through the one address rule (harness connection.md §1): a login made + * before that rule keeps working untouched, and is compared like any other. One that is not an + * address at all is left as it is, for whoever reads it to say so. */ +function readBase(stored: unknown): string { + try { + return oneRule(String(stored ?? "")) + } catch { + return String(stored ?? "") + } } function readIndex(dir: string): Record { try { const parsed = JSON.parse(readFileSync(indexFile(dir), "utf8")) as Index - return parsed.instances ?? {} + const all = parsed.instances ?? {} + for (const one of Object.values(all)) if (one && typeof one === "object") one.base_url = readBase(one.base_url) + return all } catch { return {} } @@ -104,30 +132,30 @@ function writeYamlDoc(file: string, doc: Doc, mode?: number) { /** What to call the instance's connection: the name it gives itself (`example`), or — from an * instance that gives none — its host's first label. Never one the user wrote by hand: * that gets `-lembas` after it. */ -export function connectionNameFor(baseUrl: string, preferred?: string): string { +export function connectionNameFor(baseUrl: string, preferred?: string, discoveryBase?: string): string { let name = (preferred ?? "").toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "") if (!name) { const host = new URL(baseUrl).hostname const first = (/^\d+(\.\d+){3}$/.test(host) ? host.replace(/\./g, "-") : host.split(".")[0]!).toLowerCase() name = first.replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "") || "lembas" } - const ours = Object.values(instances()).some((i) => i.connection === name && i.base_url === baseUrl) + const ours = Object.values(instances()).some((i) => i.connection === name && sameLogin(i.base_url, baseUrl, discoveryBase)) if (ours) return name return readYamlDoc(connectionsFile()).hasIn(["connections", name]) ? `${name}-lembas` : name } -export function writeConnection(connection: string, d: Discovery, tls: Tls | undefined) { +export function writeConnection(connection: string, d: Discovery, tls: Tls | undefined, base: string) { const doc = readYamlDoc(connectionsFile()) const entry: Record = { type: "webui", - url: d.base_url, + url: base, api_key: `{file:${ownKeyFile(connection)}}`, ...(tls?.ca ? { tls: { ca: tls.ca } } : {}), } 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 ${d.base_url}, 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 instance at every start; \`lembas logout ${connection}\` removes it.` writeYamlDoc(connectionsFile(), doc, 0o600) } @@ -393,11 +421,11 @@ function webuiCount(): number { export async function login(address: string, o: LoginOptions): Promise { // Kept as a full path: `lembas service` and Desktop read it from another directory. const ca = o.ca ? resolve(expandHome(o.ca)) : undefined - const { discovery, tls } = await discover(address, ca ? { ca } : undefined) - const start = await startDevice(discovery, tls) + const { discovery, tls, base } = await discover(address, ca ? { ca } : undefined) + const start = await startDevice(discovery, tls, base) o.onCode(start, discovery) - const granted = await awaitToken(discovery, start, tls, { signal: o.signal, sleep: o.sleep }) - return store(discovery, tls, granted, o) + const granted = await awaitToken(discovery, start, tls, base, { signal: o.signal, sleep: o.sleep }) + return store(discovery, tls, granted, o, base) } /** `lembas login --token-stdin`: what a program that already holds an agent's token — LLeMbas @@ -408,9 +436,9 @@ export async function loginWithToken(address: string, token: string, o: Omit): Promise { - const connection = connectionNameFor(discovery.base_url, discovery.connection) +/** `base`: the address the person typed, normalised — what is stored, used and compared from + * here on (harness connection.md §1). The instance's own `base_url` is only ever a hint that a + * login kept from before this rule is this same instance (`sameLogin`): such a login is replaced, + * never given a twin. */ +async function store(discovery: Discovery, tls: Tls | undefined, granted: Granted, o: Pick, base: string): Promise { + const same = (stored: string) => sameLogin(stored, base, discovery.base_url) + const connection = connectionNameFor(base, discovery.connection, discovery.base_url) // Logging in again under the same name: the token being replaced, read before its file is. const before = ownInstances()[connection] - const replaced = before?.base_url === discovery.base_url && existsSync(ownKeyFile(connection)) ? readFileSync(ownKeyFile(connection), "utf8").trim() : "" + const replaced = before && same(before.base_url) && existsSync(ownKeyFile(connection)) ? { token: readFileSync(ownKeyFile(connection), "utf8").trim(), at: before.base_url } : undefined mkdirSync(keyDir(), { recursive: true, mode: 0o700 }) writeFileSync(ownKeyFile(connection), granted.access_token + "\n", { mode: 0o600 }) chmodSync(ownKeyFile(connection), 0o600) - const fetched = await fetchWebui(connection, discovery.base_url, granted.access_token, tls) + const fetched = await fetchWebui(connection, base, granted.access_token, tls) const instanceDefault = fetched.instance?.default_model ?? fetched.models.find((m) => m.default)?.id ?? undefined const changes: string[] = [] // The old token is signed out too: this machine holds one, the new one. Over the TLS that has // just worked (the old login's CA may be what was wrong), naming the new token, so the instance // moves the old device's agent chats to it instead of keeping an offline twin. - const handOver = async (old: string) => { - if (old && old !== granted.access_token && !(await signOut(discovery.base_url, old, tls, granted.access_token))) - changes.push("the previous login could not be signed out: revoke it under User → Security → Devices on the instance") + // + // A token goes only to the server it belongs to. Where the earlier login is at the address + // typed now, that is this server, and it hears both tokens. Where it is the same login only on + // the server's word (its discovery names the address the earlier login stored), nothing proves + // the two are one server: the old token is then signed out at its own address, without the new + // token's name — so neither token can reach a server that merely claimed the other's address. + const handOver = async (old: { token: string; at: string } | undefined) => { + 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") } await handOver(replaced) // One server at a time (2.0: the CLI is LLeMbas-server-specific): a login to another one signs // this machine out of the one it was logged in to. for (const [name, old] of Object.entries(ownInstances())) - if (name !== connection && old.base_url !== discovery.base_url) { + if (name !== connection && !same(old.base_url)) { const out = await logout(name).catch(() => undefined) if (!out) continue changes.push(`signed out of ${old.instance_name ?? old.base_url} (${name}): LLeMbas CLI uses one server at a time`) @@ -452,15 +493,16 @@ async function store(discovery: Discovery, tls: Tls | undefined, granted: Grante // signed out or replaced — it is not this project's. const known = ownInstances() for (const [name, old] of Object.entries(known)) - if (name !== connection && old.base_url === discovery.base_url) { - if (existsSync(ownKeyFile(name))) await handOver(readFileSync(ownKeyFile(name), "utf8").trim()) + if (name !== connection && same(old.base_url)) { + if (existsSync(ownKeyFile(name))) await handOver({ token: readFileSync(ownKeyFile(name), "utf8").trim(), at: old.base_url }) changes.push(...replaceOld(name, connection, instanceDefault)) delete known[name] } - writeConnection(connection, discovery, tls) + writeConnection(connection, discovery, tls, base) + const min_clients = minimums(discovery.min_clients) const instance: Instance = { - base_url: discovery.base_url, + base_url: base, connection, email: granted.account?.email, name: granted.account?.name, @@ -468,6 +510,7 @@ async function store(discovery: Discovery, tls: Tls | undefined, granted: Grante ...(tls?.ca ? { ca: tls.ca } : {}), ...(granted.scope ? { scope: granted.scope } : {}), protocols: spoken(discovery), + ...(min_clients ? { min_clients } : {}), logged_in_at: new Date().toISOString(), } saveIndex({ ...known, [connection]: instance }) @@ -498,7 +541,8 @@ export async function sync(connection: string, o: { setDefault?: boolean } = {}) const instance = instances()[connection] if (!instance) throw new LembasError(`${connection} was not made by lembas login`) const { discovery, tls } = await discover(instance.base_url, instance.ca ? { ca: instance.ca } : undefined) - const fetched = await fetchWebui(connection, discovery.base_url, tokenOf(connection), tls) + rememberProtocols(connection, spoken(discovery), discovery.min_clients) + const fetched = await fetchWebui(connection, instance.base_url, tokenOf(connection), tls) const instanceDefault = fetched.instance?.default_model ?? fetched.models.find((m) => m.default)?.id ?? undefined // Logging in again reads the models again: an embedding model the instance has added since is // taken up the same way, still only where none is set. @@ -514,6 +558,20 @@ export async function sync(connection: string, o: { setDefault?: boolean } = {}) return { connection, instance, models: fetched.models.filter(isChatModel), instanceDefault, defaultSet, changes, version: discovery.version, refs } } +/** Ask the instance's discovery again and keep what it says of itself (its protocols, its + * `min_clients`) with the login: what `serve --stdio` does as it starts, without waiting for it, + * so the next editor to connect is told the minimum for its product as the server has it now. + * Never throws. */ +export async function refreshDiscovery(): Promise { + try { + const all = Object.values(ownInstances()) + if (all.length !== 1) return + const one = all[0]! + const { discovery } = await discover(one.base_url, one.ca ? { ca: one.ca } : undefined) + rememberProtocols(one.connection, spoken(discovery), discovery.min_clients) + } catch {} +} + export interface LogoutResult { connection: string revoked: boolean diff --git a/src/provider/common.ts b/src/provider/common.ts index a0a1bf5..108f6ce 100644 --- a/src/provider/common.ts +++ b/src/provider/common.ts @@ -36,8 +36,9 @@ export type RetryHandler = (e: ProviderError) => { retry: boolean; notice?: stri /** Run attempts until one succeeds. A retry is only ever considered while nothing of the reply has * been passed on (`beforeOutput`); a server error gets two retries on top of whatever `handle` allows. */ -export async function* retrying(attempt: () => AsyncGenerator, handle?: RetryHandler): AsyncGenerator { +export async function* retrying(attempt: () => AsyncGenerator, handle?: RetryHandler, signal?: AbortSignal): AsyncGenerator { let retried5xx = 0 + let retried429 = 0 for (let n = 0; ; n++) { try { yield* attempt() @@ -49,6 +50,17 @@ export async function* retrying(attempt: () => AsyncGenerator, hand if (h.notice) yield { type: "notice", message: h.notice } continue } + // Too many requests, and the server said when to come back (harness connection.md §6): wait + // that long — it is capped at five minutes, and given up when the turn is stopped — and ask again, twice at most. Without a + // Retry-After nothing says a second go would fare better, so the refusal stands. + if (e.status === 429 && e.retryAfter && retried429 < 2 && !signal?.aborted) { + retried429++ + const reason = e.message.split("\n")[0]!.slice(0, 160) + yield { type: "notice", message: `the server is busy, trying again in ${e.retryAfter} s (${retried429} of 2) — ${reason}`, retry: { reason, in: e.retryAfter, attempt: retried429 } } + await pause(e.retryAfter * 1000, signal) + if (signal?.aborted) throw new ProviderError("cancelled") + continue + } // Often the model's own output failing the server's parser (llama.cpp + gpt-oss), or the // model swapped out under us (llama-swap): sampling differs on a second go. // Twice: the first at once, the second after a pause (a model still loading, a busy server). @@ -64,6 +76,15 @@ export async function* retrying(attempt: () => AsyncGenerator, hand } } +/** Wait, or stop waiting when `signal` aborts. */ +function pause(ms: number, signal?: AbortSignal): Promise { + return new Promise((r) => { + const done = () => (clearTimeout(t), signal?.removeEventListener("abort", done), r()) + const t = setTimeout(done, ms) + signal?.addEventListener("abort", done, { once: true }) + }) +} + /** Status for an error object inside a stream: a numeric code is HTTP; llama-swap's * `type: "server_error"` / `code: "internal_error"` is a 500 too. */ export function statusOf(err: any): number | undefined { diff --git a/src/provider/http.ts b/src/provider/http.ts index fef60eb..b9ac028 100644 --- a/src/provider/http.ts +++ b/src/provider/http.ts @@ -3,6 +3,7 @@ import { expandHome } from "../config/paths.ts" import type { Connection } from "../config/schema.ts" import { ProviderError } from "./types.ts" import { duration } from "../duration.ts" +import { codeFor, retryAfter, tokenRefused, USER_AGENT, type Code } from "../lembas/connection.ts" const caCache = new Map() @@ -71,6 +72,16 @@ async function cappedText(res: Response, max: number): Promise { return new TextDecoder().decode(Buffer.concat(chunks).subarray(0, max)) } +const coded = (code: Code, e: ProviderError): ProviderError => ((e.code = code), e) + +/** The code of a failed request (harness connection.json `codes`), for a turn's `error`: why no + * answer came, else what its status means, else `failed`. */ +export function failureCode(e: unknown): Code { + if (!(e instanceof ProviderError)) return "failed" + if (e.code) return e.code as Code + return (e.status ? codeFor({ kind: "http", status: e.status }) : null) ?? "failed" +} + export async function request( url: string, init: RequestInit & { timeoutMs?: number; tls?: { ca?: string; rejectUnauthorized?: boolean } }, @@ -84,24 +95,33 @@ export async function request( let silent = false let timer = setTimeout(() => ((silent = true), ctl.abort()), ms) const signal = init.signal ? AbortSignal.any([init.signal, ctl.signal]) : ctl.signal + // Who is asking (harness connection.md §3), unless the caller has its own name for a site that + // is not a LLeMbas server (the web tools). + const headers = new Headers(init.headers) + if (!headers.has("user-agent")) headers.set("user-agent", USER_AGENT) let res: Response try { - res = await fetch(url, { ...init, signal }) + res = await fetch(url, { ...init, headers, signal }) } catch (e) { clearTimeout(timer) const err = e as Error if (init.signal?.aborted) throw new ProviderError("cancelled") - if (silent || err.name === "TimeoutError") throw new ProviderError(`${what}: timed out — no response in ${duration(ms, true)}`, undefined, undefined, true, true) + if (silent || err.name === "TimeoutError") throw coded("timeout", new ProviderError(`${what}: timed out — no response in ${duration(ms, true)}`, undefined, undefined, true, true)) const code = (err as { code?: string }).code ?? "" if (/CERT|SIGNATURE|SELF_SIGNED/.test(code)) - throw new ProviderError(`${what}: TLS certificate of ${new URL(url).host} is not trusted (${code}). Install its CA system-wide, or set tls.ca on the connection.`) - throw new ProviderError(`${what}: cannot reach ${new URL(url).host} — ${err.message}`, undefined, undefined, true, true) + throw coded("tls_untrusted", new ProviderError(`${what}: TLS certificate of ${new URL(url).host} is not trusted (${code}). Install its CA system-wide, or set tls.ca on the connection.`)) + throw coded("unreachable", new ProviderError(`${what}: cannot reach ${new URL(url).host} — ${err.message}`, undefined, undefined, true, true)) } clearTimeout(timer) // A redirect asked to be handled by hand is a response, not an error. if (!res.ok && !(init.redirect === "manual" && res.status >= 300 && res.status < 400)) { const body = await cappedText(res, 64 * 1024).catch(() => "") - throw new ProviderError(`${what}: ${describeError(res.status, body)}`, res.status, body) + const err = new ProviderError(`${what}: ${describeError(res.status, body)}`, res.status, body) + if (res.status === 429) err.retryAfter = retryAfter(res.headers.get("retry-after")) + // The server's own refusal of the token — its challenge is on it — and not a 401 of the + // model's provider, which the server's /v1 passes through and which signs nobody out. + if (res.status === 401 && tokenRefused(res.headers.get("www-authenticate"))) err.code = "signed_out" + throw err } if (!res.body) return res const reader = res.body.getReader() @@ -114,7 +134,7 @@ export async function request( else c.enqueue(r.value) } catch (e) { if (init.signal?.aborted) throw new ProviderError("cancelled") - if (silent) throw new ProviderError(`${what}: timed out — the server sent nothing for ${duration(ms, true)}`, undefined, undefined, false) + if (silent) throw coded("timeout", new ProviderError(`${what}: timed out — the server sent nothing for ${duration(ms, true)}`, undefined, undefined, false)) throw e } finally { clearTimeout(timer) diff --git a/src/provider/openai-chat.ts b/src/provider/openai-chat.ts index 5a0e30e..e80563a 100644 --- a/src/provider/openai-chat.ts +++ b/src/provider/openai-chat.ts @@ -179,6 +179,7 @@ export class OpenAIChatClient implements Client { } return { retry: false } }, + req.signal, ) if (droppedProgress) learnNoProgress(base) } diff --git a/src/provider/types.ts b/src/provider/types.ts index 7992e8a..8610e60 100644 --- a/src/provider/types.ts +++ b/src/provider/types.ts @@ -97,4 +97,9 @@ export class ProviderError extends Error { ) { super(message) } + /** A 429's `Retry-After` in whole seconds (harness connection.md §6), where the server said. */ + retryAfter?: number + /** Why no answer came, where that is known without a status: `timeout`, `tls_untrusted`, + * `unreachable` (harness connection.json `codes`). */ + code?: string } diff --git a/src/service.ts b/src/service.ts index b4dbeef..763ba9c 100644 --- a/src/service.ts +++ b/src/service.ts @@ -10,7 +10,7 @@ // It runs as the user, never as root, and listens on nothing. To keep it running while nobody is // logged in, the user needs lingering (`loginctl enable-linger`), which `install` says rather than // does: on most systems that is a decision for whoever administers the machine. -import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +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" @@ -114,7 +114,7 @@ export function status(): string[] { process.kill(s.pid, 0) alive = true } catch {} - lines.push(alive ? `${s.state} — ${s.instance} since ${s.since}${s.detail ? ` (${s.detail})` : ""}` : `not running (last: ${s.state}${s.detail ? `, ${s.detail}` : ""})`) + lines.push(alive ? `${s.state}${s.instance ? ` — ${s.instance}` : ""} since ${s.since}${s.detail ? ` (${s.detail})` : ""}` : `not running (last: ${s.state}${s.detail ? `, ${s.detail}` : ""})`) } catch { lines.push("not running") } @@ -128,22 +128,67 @@ export function logs(follow: boolean): number { return r.exitCode ?? 1 } -/** One copy at a time: a second `service run` refuses while the first holds the lock. */ -function takeLock(): () => void { - mkdirSync(paths.state, { recursive: true }) +/** Whether `pid` is a `lembas service run` that is running. A pid alone is not proof: after a + * crash or a reboot the number in a stale lock may be anybody's. Where the system says what a + * process is (Linux's /proc), one that is not running `service` does not hold the lock. */ +export function holdsLock(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return false try { - const held = Number(readFileSync(lockFile(), "utf8")) - if (held) { - process.kill(held, 0) - throw new LinkError(`already running (pid ${held})`) - } + process.kill(pid, 0) } catch (e) { - if (e instanceof LinkError) throw e + // EPERM: it is there, and somebody else's — not ours to judge, so it is taken to hold it. + if ((e as { code?: string }).code !== "EPERM") return false + } + try { + const args = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0") + return args.includes("service") + } catch { + return true + } +} + +/** One copy at a time: a second `service run` refuses while the first holds the lock. The file is + * 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 }) + const release = () => { + // Only this process's own: a lock taken over meanwhile is the other's. + try { + if (Number(readFileSync(file, "utf8")) === process.pid) rmSync(file, { force: true }) + } catch {} + } + for (let tries = 0; tries < 3; tries++) { + try { + const fd = openSync(file, "wx", 0o600) + writeFileSync(fd, String(process.pid)) + closeSync(fd) + return release + } catch (e) { + if ((e as { code?: string }).code !== "EEXIST") throw e + } + let held = 0 + try { + held = Number(readFileSync(file, "utf8")) + } catch {} + if (holdsLock(held)) throw new LinkError(`already running (pid ${held})`) + // Stale: its holder is gone. Removed, and the exclusive create is tried again — if another + // start got there first, that one holds it and this one is refused on the next round. + rmSync(file, { force: true }) + } + throw new LinkError("could not take the service's lock (another copy is starting)") +} + +/** The status file, replaced in one step: a program reading it (LLeMbas Desktop) never sees half + * of one. `code` is what it reads; `detail` is for a person. */ +function writeStatus(s: LinkStatus) { + const tmp = `${statusFile()}.${process.pid}.tmp` + try { + writeFileSync(tmp, JSON.stringify({ ...s, pid: process.pid }, null, 2)) + renameSync(tmp, statusFile()) + } catch { + rmSync(tmp, { force: true }) } - const fd = openSync(lockFile(), "w") - writeFileSync(fd, String(process.pid)) - closeSync(fd) - return () => rmSync(lockFile(), { force: true }) } /** An installed unit from an older release is brought up to this one's text, so a change to @@ -163,7 +208,16 @@ function refreshUnit() { export const RESTART_FOR_UPDATE = 75 export async function run(instance?: string): Promise { - const release = takeLock() + let release: () => void + try { + release = takeLock() + } catch (e) { + if (!(e instanceof LinkError)) throw e + // Another copy holds it (one started by hand, say). Non-zero, so the unit tries again and + // takes over when that one has gone — said in a line, not as a crash. + console.error(`lembas service: ${e.message}`) + return 1 + } const stop = new AbortController() for (const sig of ["SIGTERM", "SIGINT"] as const) process.once(sig, () => stop.abort()) refreshUnit() @@ -201,22 +255,30 @@ export async function run(instance?: string): Promise { try { // Remote work off or no roots: linked all the same, telling the instance `roots: []` and // refusing every session; `lembas remote add ` or `enable` makes it serve, no restart. - const end = await runLink({ + // It stays (`stay`): not logged in, a token the instance refuses, or a newer link of this + // device having taken its place, is a state — `stopped`, with its code — not an exit. The + // unit is Restart=on-failure, so an exit 0 would leave the machine without a service until + // somebody restarted it by hand, and an exit 1 would restart it every ten seconds for ever; + // staying, it watches the sign-in kept here and links again when `lembas login` has run. + let last = "" + await runLink({ instance, hub, + stay: true, signal: stop.signal, onStatus: (s) => { - writeFileSync(statusFile(), JSON.stringify({ ...s, pid: process.pid }, null, 2)) - console.log(`${s.state}${s.detail ? `: ${s.detail}` : ""}`) + writeStatus(s) + const line = `${s.state}${s.detail ? `: ${s.detail}` : ""}` + if (line !== last) console.log(line) + last = line }, }) - // Refused (token revoked): exit cleanly so systemd does not knock on a closed door for ever. - void end return updated ? RESTART_FOR_UPDATE : 0 } catch (e) { console.error(`lembas service: ${(e as Error).message}`) - // A configuration that cannot work (not logged in) is not fixed by restarting: exit 0 so - // Restart=on-failure leaves it, and the journal says why. + // A configuration that cannot work (local mode) is not fixed by restarting: exit 0 so + // Restart=on-failure leaves it, and the status file and the journal say why. + if (e instanceof LinkError) writeStatus({ state: "stopped", code: e.code, instance: "", since: new Date().toISOString(), detail: e.message, attempts: 0 }) return e instanceof LinkError ? 0 : 1 } finally { clearInterval(watch) diff --git a/src/session/engine.ts b/src/session/engine.ts index d28fc7e..18d4f74 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -17,6 +17,7 @@ import { splitPurpose, toSpec, ToolError, type Tool, type ToolContext, type Tool import { promptText } from "../prompt/assemble.ts" import { resolveCall } from "../tool/names.ts" import { contextWindow } from "../provider/index.ts" +import { failureCode } from "../provider/http.ts" import { summaryTurns, type Store } from "./store.ts" import { estimateTokens, estimateValue } from "../provider/tokens.ts" import { duration } from "../duration.ts" @@ -1058,12 +1059,12 @@ export class Engine { step-- continue } - bus.emit({ type: "error", message: (e as Error).message }) + bus.emit({ type: "error", message: (e as Error).message, code: failureCode(e) }) bus.emit({ type: "done", reason: "error" }) return "error" } if (!assistant) { - bus.emit({ type: "error", message: "the stream ended without a reply" }) + bus.emit({ type: "error", message: "the stream ended without a reply", code: "failed" }) bus.emit({ type: "done", reason: "error" }) return "error" } diff --git a/tests/acp.test.ts b/tests/acp.test.ts index 7771d48..ad186f3 100644 --- a/tests/acp.test.ts +++ b/tests/acp.test.ts @@ -475,20 +475,23 @@ test("link protocol 3: a 1.x server is refused before any dial; a 4400 stops the const old = await runLink({ backoffMs: [10, 20] }) expect(dials).toBe(0) expect(old.state).toBe("stopped") - expect(old.detail).toContain("runs LLeMbas 1.7.3, which speaks link protocol 1 and 2") - expect(old.detail).toContain("needs a LLeMbas 2.0 server (protocol 3). Update the server, or use LLeMbas CLI 1.x with it.") + expect(old.code).toBe("server_too_old") + expect(old.detail).toContain("runs LLeMbas 1.7.3, which is too old for this LLeMbas CLI. Update the server. Or use LLeMbas CLI 1.x with it.") + expect(old.detail).toContain("it speaks link protocol 1 and 2") // Discovery lists 3, but the link refuses the hello anyway: one dial, stopped, said plainly. discovery = { version: "2.0.0", protocol: 3, protocols: [3] } const refused = await runLink({ backoffMs: [10, 20] }) expect(hellos).toEqual([3]) expect(dials).toBe(1) + expect(refused.code).toBe("server_too_old") expect(refused.detail).toContain("the instance does not speak link protocol 3") expect(refused.detail).toContain("update the server, or use LLeMbas CLI 1.x with it") // A newer server than this CLI: the CLI is what needs updating. discovery = { version: "3.0.0", protocol: 4, protocols: [4] } const newer = await runLink({ backoffMs: [10, 20] }) expect(dials).toBe(1) - expect(newer.detail).toContain("Update LLeMbas CLI (lembas update).") + expect(newer.code).toBe("client_too_old") + expect(newer.detail).toContain("Update LLeMbas CLI. Run lembas update.") }) test("a link that cannot dial says why: a CA file gone since the login, and what discovery met", async () => { diff --git a/tests/conformance.ts b/tests/conformance.ts index 2673353..ba3cb75 100644 --- a/tests/conformance.ts +++ b/tests/conformance.ts @@ -47,7 +47,7 @@ import { diffContent, editorBlock, rewriteMessage, rewriteModel, RewriteOutput, import { baseCheck, judgePath, runsCode, sameAgain, type FsOp } from "../src/acp/files.ts" import { textFrom, writeTo } from "../src/tool/buffers.ts" import { showPlan } from "../src/tool/show.ts" -import { address, CodedError, explain, judgeVersions, sameServer, stdioProtocol, type Condition, type Vars } from "../src/lembas/connection.ts" +import { address, belowMinimum, CodedError, compareReleases, explain, judgeVersions, onOrigin, sameLogin, sameServer, stdioProtocol, type Condition, type Vars } from "../src/lembas/connection.ts" type Case = Record @@ -76,6 +76,8 @@ export const AREAS: Record unknown> = { // LLeMbas connection 1 (harness/connection.md; src/lembas/connection.ts). address: (c) => { if (c.kind === "same") return sameServer(c.a as string, c.b as string) + if (c.kind === "login") return sameLogin(c.stored as string, c.typed as string, c.discovery_base_url) + if (c.kind === "origin") return onOrigin(c.base as string, c.url) try { return address(c.typed as string) } catch (e) { @@ -83,7 +85,15 @@ export const AREAS: Record unknown> = { throw e } }, - version: (c) => (c.kind === "stdio" ? stdioProtocol(c.agent as number, c.client) : judgeVersions(c.mine, c.theirs)), + version: (c) => { + if (c.kind === "stdio") return stdioProtocol(c.agent as number, c.client) + if (c.kind === "min") return belowMinimum(c.mine, c.minimum) + if (c.kind === "compare") { + const r = compareReleases(c.a, c.b) + return r === undefined ? null : Math.sign(r) + } + return judgeVersions(c.mine, c.theirs) + }, errors: (c) => explain(c.condition as Condition, (c.vars ?? {}) as Vars), // Spec 3.11.0: an editor as the client (src/acp/editor.ts). diff --git a/tests/connection.test.ts b/tests/connection.test.ts new file mode 100644 index 0000000..d224132 --- /dev/null +++ b/tests/connection.test.ts @@ -0,0 +1,892 @@ +// LLeMbas connection 1 (harness/connection.md) as the CLI does it: the link against a stand-in +// server — replaced by a newer link (4409), a token refused and then signed in again, a handshake +// that never finishes, a server that accepts and drops, a link that goes silent — and the smaller +// rules: who the CLI says it is, a failed turn in the prompt's answer, the stdio client's name and +// protocol, the lock, a line with no end, Retry-After. +import { afterAll, afterEach, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { PassThrough } from "node:stream" +import { AcpAgent, clientName, minClientFor, turnError } from "../src/acp/agent.ts" +import { heldLogin, LinkError, runLink, type LinkOptions, type LinkStatus } from "../src/acp/link.ts" +import { Peer, stdioTransport, type Transport } from "../src/acp/rpc.ts" +import { paths } from "../src/config/paths.ts" +import { apiCall, discover, LembasError, models, SignInRejected } from "../src/lembas/client.ts" +import { CONNECTION, reconnectWait, USER_AGENT } from "../src/lembas/connection.ts" +import { instances, login, loginWithToken, refreshDiscovery, sync } from "../src/lembas/login.ts" +import { setTrust } from "../src/project/root.ts" +import { retrying } from "../src/provider/common.ts" +import { failureCode, request } from "../src/provider/http.ts" +import { ProviderError, type StreamEvent } from "../src/provider/types.ts" +import { holdsLock, takeLock } from "../src/service.ts" +import { VERSION } from "../src/version.ts" +import { delta, type Fake } from "./fake-provider.ts" + +afterAll(() => { + rmSync(join(paths.config, "lembas.json"), { force: true }) + rmSync(join(paths.config, "lembas"), { recursive: true, force: true }) +}) + +let fake: Fake | undefined +const stops: (() => void)[] = [] +afterEach(() => { + fake?.stop() + fake = undefined + for (const s of stops.splice(0)) s() + rmSync(join(paths.config, "lembas.json"), { force: true }) + rmSync(join(paths.config, "lembas"), { recursive: true, force: true }) +}) + +const keyPath = () => join(paths.config, "lembas", "fake.key") + +/** A login as `lembas login` leaves it: the index, and the key in its own file. */ +function kept(base: string, token: string | null = "lmb_first") { + mkdirSync(join(paths.config, "lembas"), { recursive: true }) + writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { fake: { base_url: base, connection: "fake", logged_in_at: "" } } })) + if (token === null) rmSync(keyPath(), { force: true }) + else writeFileSync(keyPath(), `${token}\n`, { mode: 0o600 }) +} + +interface Dial { + n: number + token: string + agent: string + ws: any + /** What the device sent on this socket, as JSON-RPC messages. */ + got: any[] + /** Ask the device something, as the server does after the hello. */ + ask: (method: string, params?: unknown) => Promise +} + +/** A stand-in LLeMbas server: discovery, and the link's socket handed to `onDial` each time the + * device dials. It does nothing by itself — not even `initialize` — so each test says exactly + * what the server does. */ +function standIn(onDial: (d: Dial) => void | Promise, o: { discovery?: () => Response | undefined } = {}) { + const dials: Dial[] = [] + const agents: string[] = [] + const server = Bun.serve({ + port: 0, + fetch(req, srv) { + const u = new URL(req.url) + const base = `http://${u.host}` + if (u.pathname === "/.well-known/lembas.json") { + agents.push(req.headers.get("user-agent") ?? "") + return ( + o.discovery?.() ?? + Response.json({ service: "lembas", version: "2.0.0", protocol: 3, protocols: [3], harness_spec: "3.0.0", base_url: base, api: { openai: `${base}/v1` }, login: { device: { code: `${base}/c`, token: `${base}/t`, verify: `${base}/d` } } }) + ) + } + if (u.pathname === "/api/devices/link" && srv.upgrade(req, { data: { token: (req.headers.get("authorization") ?? "").replace(/^Bearer /, ""), agent: req.headers.get("user-agent") ?? "" } } as never)) return + return new Response("no", { status: 404 }) + }, + websocket: { + open(ws) { + const data = ws.data as unknown as { token: string; agent: string; dial?: Dial; waiting?: Map void> } + const waiting = (data.waiting = new Map()) + let id = 1000 + const d: Dial = { + n: dials.length + 1, + token: data.token, + agent: data.agent, + ws, + got: [], + ask: (method, params) => + new Promise((resolve) => { + const mine = id++ + waiting.set(mine, resolve) + ws.send(JSON.stringify({ jsonrpc: "2.0", id: mine, method, params })) + }), + } + data.dial = d + dials.push(d) + void onDial(d) + }, + message(ws, msg) { + const data = ws.data as unknown as { dial?: Dial; waiting?: Map void> } + const m = JSON.parse(String(msg)) + data.dial?.got.push(m) + if (m.method === undefined && data.waiting?.has(m.id)) data.waiting.get(m.id)!(m) + }, + }, + }) + stops.push(() => server.stop(true)) + return { base: `http://127.0.0.1:${server.port}`, dials, agents } +} + +const initialize = (d: Dial) => d.ask("initialize", { protocolVersion: 1, clientInfo: { name: "llembas-server", version: "2.0.0" }, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }) + +/** Run the link with test-sized timers, collecting what it says. */ +function link(o: LinkOptions = {}) { + const stop = new AbortController() + stops.push(() => stop.abort()) + const said: LinkStatus[] = [] + const done = runLink({ backoffMs: [10, 80], signal: stop.signal, ...o, timers: { random: () => 0.5, login: 10, ...o.timers }, onStatus: (s) => void said.push(s) }) + const until = async (ok: () => boolean, what: string) => { + for (let i = 0; i < 400 && !ok(); i++) await Bun.sleep(10) + if (!ok()) throw new Error(`timed out waiting for ${what}: ${JSON.stringify(said.map((s) => [s.state, s.code, s.detail]))}`) + } + return { stop, said, done, until, codes: () => said.map((s) => `${s.state}:${s.code}`) } +} + +test("who the CLI says it is: llembas-cli/, on discovery and on the link's upgrade request", async () => { + expect(USER_AGENT).toBe(`llembas-cli/${VERSION}`) + const srv = standIn(async (d) => { + await initialize(d) + d.ws.close(4403, "revoked") + }) + kept(srv.base) + const l = link() + expect((await l.done).code).toBe("signed_out") + expect(srv.agents).toEqual([USER_AGENT]) + expect(srv.dials[0]!.agent).toBe(USER_AGENT) +}) + +test("linked is said only after initialize was answered, never at the open socket", async () => { + let let_in!: () => void + const gate = new Promise((r) => (let_in = r)) + const srv = standIn(async (d) => { + await gate + await initialize(d) + }) + kept(srv.base) + const l = link() + // The socket is open and the hello was sent: still connecting. + await l.until(() => srv.dials[0]?.got.some((m) => m.method === "_lembas/hello") === true, "the hello") + await Bun.sleep(50) + expect(l.codes()).toEqual(["connecting:connecting"]) + let_in() + await l.until(() => l.said.some((s) => s.state === "linked"), "linked") + expect(l.said.at(-1)).toMatchObject({ state: "linked", code: "linked", instance: srv.base }) + l.stop.abort() + expect(await l.done).toMatchObject({ state: "stopped", code: "stopped", detail: "stopped" }) +}) + +test("a token refused before initialize never says linked (the server accepts the socket first)", async () => { + const srv = standIn((d) => d.ws.close(4403, "not allowed to link")) + kept(srv.base) + const l = link() + const end = await l.done + expect(end).toMatchObject({ state: "stopped", code: "signed_out" }) + expect(end.detail).toContain("no longer accepts this sign-in — sign in again. Run lembas login. (not allowed to link)") + expect(l.codes()).toEqual(["connecting:connecting", "stopped:signed_out"]) + expect(srv.dials.length).toBe(1) +}) + +test("4409, replaced by a newer link of the same device: stopped with its own code, and no dial again", async () => { + const srv = standIn(async (d) => { + await initialize(d) + d.ws.close(4409, "replaced by a newer link") + }) + kept(srv.base) + const l = link() + const end = await l.done + expect(end).toMatchObject({ state: "stopped", code: "replaced" }) + expect(end.detail).toContain("A newer link of this device took its place") + await Bun.sleep(150) + expect(srv.dials.length).toBe(1) +}) + +test("a plain 1000 is a link that dropped, and is dialled again — only 4409 means replaced", async () => { + const srv = standIn(async (d) => { + await initialize(d) + d.ws.close(d.n === 1 ? 1000 : 4409, "bye") + }) + kept(srv.base) + const l = link() + expect((await l.done).code).toBe("replaced") + expect(srv.dials.length).toBe(2) + expect(l.said.find((s) => s.state === "waiting")).toMatchObject({ code: "unreachable" }) +}) + +test("4403 after the key changed: the sign-in was made again, so the link dials at once with the new key", async () => { + const srv = standIn(async (d) => { + await initialize(d) + if (d.token !== "lmb_first") return + // `lembas login` again: the new key is written, then the old token is signed out — which is + // what closes this link. + writeFileSync(keyPath(), "lmb_second\n", { mode: 0o600 }) + d.ws.close(4403, "revoked") + }) + kept(srv.base) + const l = link() + await l.until(() => srv.dials.length === 2 && l.said.at(-1)?.state === "linked", "the second link") + expect(srv.dials.map((d) => d.token)).toEqual(["lmb_first", "lmb_second"]) + expect(l.said.some((s) => s.state === "stopped")).toBe(false) + expect(l.said.some((s) => s.detail === "the sign-in kept here changed; linking again with it")).toBe(true) + l.stop.abort() + await l.done +}) + +test("the service stays when its token is refused, and links again by itself once lembas login has run", async () => { + const srv = standIn(async (d) => { + await initialize(d) + if (d.token === "lmb_first") d.ws.close(4403, "revoked") + }) + kept(srv.base) + const l = link({ stay: true }) + await l.until(() => l.said.at(-1)?.code === "signed_out", "the refusal") + // It does not come back by itself: nothing dials while the same key is there. + await Bun.sleep(120) + expect(srv.dials.length).toBe(1) + expect(l.said.at(-1)).toMatchObject({ state: "stopped", code: "signed_out" }) + writeFileSync(keyPath(), "lmb_second\n", { mode: 0o600 }) + await l.until(() => l.said.at(-1)?.state === "linked", "the link with the new key") + expect(srv.dials.map((d) => d.token)).toEqual(["lmb_first", "lmb_second"]) + l.stop.abort() + expect((await l.done).code).toBe("stopped") +}) + +test("no key file: not a crash and not a restart loop — stopped as not_logged_in, and healed by a login", async () => { + const srv = standIn((d) => void initialize(d)) + kept(srv.base, null) + // A terminal's /remote is told at once, with the code. + expect(() => heldLogin()).toThrow(LinkError) + const refused = await runLink({ backoffMs: [10, 20] }).catch((e) => e) + expect(refused).toBeInstanceOf(LinkError) + expect(refused.code).toBe("not_logged_in") + expect(refused.message).toContain("not logged in") + // The service says so and waits. + const l = link({ stay: true }) + await l.until(() => l.said.length > 0, "a status") + await Bun.sleep(80) + expect(l.codes()).toEqual(["stopped:not_logged_in"]) + expect(srv.dials.length).toBe(0) + writeFileSync(keyPath(), "lmb_new\n", { mode: 0o600 }) + await l.until(() => l.said.at(-1)?.state === "linked", "the link after the login") + expect(srv.dials[0]!.token).toBe("lmb_new") + l.stop.abort() + await l.done +}) + +test("not logged in at all: the service waits in not_logged_in until there is a login", async () => { + const srv = standIn((d) => void initialize(d)) + const l = link({ stay: true }) + await l.until(() => l.said.length > 0, "a status") + expect(l.said[0]).toMatchObject({ state: "stopped", code: "not_logged_in", instance: "" }) + kept(srv.base, "lmb_new") + await l.until(() => l.said.at(-1)?.state === "linked", "the link after the login") + l.stop.abort() + await l.done +}) + +test("a handshake that never finishes is given up on, and counts as a failure", async () => { + // The server accepts the socket, reads the hello, and never sends initialize. + const srv = standIn(() => {}) + kept(srv.base) + const l = link({ timers: { handshake: 60 } }) + await l.until(() => srv.dials.length >= 3, "three dials") + l.stop.abort() + await l.done + expect(l.said.some((s) => s.state === "linked")).toBe(false) + const waits = l.said.filter((s) => s.state === "waiting") + expect(waits[0]).toMatchObject({ code: "timeout" }) + expect(waits[0]!.detail).toContain("did not finish linking") + // The wait grows: 10 ms, then 20 ms — an open socket did not set it back. + expect(waits.slice(0, 2).map((s) => s.detail!.match(/trying again in (\d+) ms/)?.[1])).toEqual(["10", "20"]) +}) + +test("flapping: a server that accepts and drops at once is dialled ever more slowly, up to the ceiling", async () => { + const srv = standIn(async (d) => { + await initialize(d) + await Bun.sleep(5) + d.ws.close(1011, "internal error") + }) + kept(srv.base) + const l = link() + await l.until(() => l.said.filter((s) => s.state === "waiting").length >= 5, "five waits") + l.stop.abort() + await l.done + const waits = l.said.filter((s) => s.state === "waiting").map((s) => Number(s.detail!.match(/trying again in (\d+) ms/)?.[1])) + // It was linked each time — for a moment, which is not health: the wait is not set back. + expect(waits.slice(0, 5)).toEqual([10, 20, 40, 80, 80]) + expect(l.said.filter((s) => s.state === "linked").length).toBeGreaterThanOrEqual(5) +}) + +test("the wait starts over only after a link that stayed healthy", async () => { + const srv = standIn(async (d) => { + await initialize(d) + // The third link lives long enough to count as healthy; the others drop at once. + if (d.n === 3) await Bun.sleep(120) + d.ws.close(1011, "internal error") + }) + kept(srv.base) + const l = link({ timers: { healthy: 60 } }) + await l.until(() => l.said.filter((s) => s.state === "waiting").length >= 4, "four waits") + l.stop.abort() + await l.done + const waits = l.said.filter((s) => s.state === "waiting").map((s) => Number(s.detail!.match(/trying again in (\d+) ms/)?.[1])) + expect(waits.slice(0, 4)).toEqual([10, 20, 10, 20]) +}) + +test("the reconnect schedule: 1 s doubling to 60 s, within ±20 %", () => { + expect([1, 2, 3, 4, 5, 6, 7, 8, 20].map((n) => reconnectWait(n, 0.5))).toEqual([1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000]) + expect(reconnectWait(0, 0.5)).toBe(1000) + expect(reconnectWait(1, 0)).toBe(800) + expect(reconnectWait(1, 0.999999)).toBe(1200) + expect(reconnectWait(7, 0)).toBe(48000) + for (let i = 0; i < 200; i++) { + const w = reconnectWait(3) + expect(w).toBeGreaterThanOrEqual(3200) + expect(w).toBeLessThanOrEqual(4800) + } + expect(CONNECTION.reconnect).toEqual({ first_s: 1, ceiling_s: 60, jitter: 0.2, healthy_s: 30 }) + expect(CONNECTION.link.close.replaced).toBe(4409) +}) + +test("liveness: pings keep a quiet link, and a link nothing is heard on is closed and dialled again", async () => { + // A healthy server says nothing for a while, but answers pings: the link stays. + const quiet = standIn((d) => void initialize(d)) + kept(quiet.base) + const a = link({ timers: { ping: 20, silence: 70 } }) + await a.until(() => a.said.at(-1)?.state === "linked", "linked") + await Bun.sleep(250) + expect(a.said.at(-1)?.state).toBe("linked") + expect(quiet.dials.length).toBe(1) + a.stop.abort() + await a.done + + // A server that finishes the upgrade, answers initialize by hand, and then goes silent — no + // pong, no close: what a dead connection looks like from here. + let sockets = 0 + const dead = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + data(sock, chunk) { + const text = chunk.toString("latin1") + const head = text.split("\r\n\r\n")[0] ?? "" + if (/^GET \/\.well-known\/lembas\.json/.test(head)) { + const base = `http://127.0.0.1:${dead.port}` + const body = JSON.stringify({ service: "lembas", version: "2.0.0", protocol: 3, protocols: [3], harness_spec: "3.0.0", base_url: base, api: { openai: `${base}/v1` }, login: { device: { code: `${base}/c`, token: `${base}/t`, verify: `${base}/d` } } }) + sock.write(`HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: ${body.length}\r\nconnection: close\r\n\r\n${body}`) + sock.end() + return + } + const key = /sec-websocket-key: *(\S+)/i.exec(head)?.[1] + if (!key) return + sockets++ + const accept = createHash("sha1").update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64") + sock.write(`HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: ${accept}\r\n\r\n`) + // initialize, as one unmasked text frame; whatever comes back is never read. + const msg = Buffer.from(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } } })) + sock.write(Buffer.concat([Buffer.from([0x81, 126, msg.length >> 8, msg.length & 0xff]), msg])) + }, + }, + }) + stops.push(() => dead.stop(true)) + kept(`http://127.0.0.1:${dead.port}`) + const b = link({ timers: { ping: 20, silence: 70 } }) + await b.until(() => b.said.some((s) => s.state === "waiting"), "the silence being noticed") + expect(b.said.some((s) => s.state === "linked")).toBe(true) + const gone = b.said.find((s) => s.state === "waiting")! + expect(gone.code).toBe("timeout") + expect(gone.detail).toContain("nothing was heard from") + await b.until(() => sockets >= 2, "a second dial") + b.stop.abort() + await b.done +}) + +test("why a dial failed is a code: not LLeMbas, a server that fails, one that is too old, one that is not there", async () => { + let answer: () => Response = () => new Response("no", { status: 404 }) + const srv = standIn(() => {}, { discovery: () => answer() }) + const code = async (address: string) => { + const e = await discover(address).catch((x) => x) + expect(e).toBeInstanceOf(LembasError) + return [e.code, e.message] + } + expect((await code(srv.base))[0]).toBe("not_lembas") + answer = () => new Response("bad gateway", { status: 502 }) + const failing = await code(srv.base) + expect(failing[0]).toBe("server_error") + expect(failing[1]).toContain("answered 502") + expect(failing[1]).not.toContain("not a LLeMbas") + answer = () => Response.json({ service: "something-else" }) + expect((await code(srv.base))[0]).toBe("not_lembas") + answer = () => new Response("not json") + expect((await code(srv.base))[0]).toBe("not_lembas") + answer = () => Response.json({ service: "lembas", version: "1.7.3", protocol: 1, protocols: [1, 2] }) + expect((await code(srv.base))[0]).toBe("server_too_old") + answer = () => Response.json({ service: "lembas", version: "3.0.0", protocol: 4, protocols: [4] }) + expect((await code(srv.base))[0]).toBe("client_too_old") + answer = () => new Response("slow down", { status: 429, headers: { "retry-after": "7" } }) + const busy = await discover(srv.base).catch((x) => x) + expect([busy.code, busy.retryAfter]).toEqual(["busy", 7]) + expect((await code("ftp://example.org"))[0]).toBe("invalid_address") + const closed = Bun.serve({ port: 0, fetch: () => new Response("no") }) + const port = closed.port + closed.stop(true) + expect((await code(`http://127.0.0.1:${port}`))[0]).toBe("unreachable") + // The link says the same code while it waits to try again, and does not open a socket for it. + answer = () => new Response("bad gateway", { status: 502 }) + kept(srv.base) + const l = link() + await l.until(() => l.said.some((s) => s.state === "waiting"), "a wait") + l.stop.abort() + await l.done + expect(l.said.find((s) => s.state === "waiting")).toMatchObject({ code: "server_error" }) + expect(srv.dials.length).toBe(0) +}) + +// ---- the prompt's answer, and the stdio client -------------------------------------------- + +function pair(): [Transport, Transport] { + const make = () => ({ msg: (_: string) => {}, end: () => {} }) + const a = make() + const b = make() + const side = (me: typeof a, other: typeof a): Transport => ({ + send: (t) => queueMicrotask(() => other.msg(t)), + onMessage: (fn) => (me.msg = fn), + onClose: (fn) => (me.end = fn), + close: () => (me.end(), other.end()), + }) + return [side(a, b), side(b, a)] +} + +function config(url: string) { + mkdirSync(paths.config, { recursive: true }) + writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${url}\n models: { f/m: {} }\n`, { mode: 0o600 }) + writeFileSync(join(paths.config, "config.yaml"), "model: f/m\n") +} + +function project(): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-conn-"))) + setTrust(dir, "trusted") + return dir +} + +function stdioClient(init: Record) { + const [ta, tb] = pair() + const agent = new AcpAgent(new Peer(ta)) + const c = new Peer(tb) + const events: any[] = [] + c.on("_lembas/event", (p) => void events.push(p.event)) + return { c, agent, events, init: c.request("initialize", { protocolVersion: 1, ...init }) } +} + +/** A model endpoint that answers each chat request with the next of `answers`, then with a reply. */ +function chat(answers: Response[]) { + const srv = Bun.serve({ + port: 0, + fetch(req) { + if (req.method !== "POST") return new Response("not found", { status: 404 }) + return answers.shift() ?? new Response(`data: ${JSON.stringify(delta({ content: "fine now" }))}\n\ndata: ${JSON.stringify(delta({}, "stop"))}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } }) + }, + }) + stops.push(() => srv.stop(true)) + return `http://127.0.0.1:${srv.port}` +} + +test("a turn that fails says so in the prompt's answer: _meta.lembas.error, a code and one line", async () => { + // The server's own refusal of the token: a 401 with its challenge. + config(chat([new Response(JSON.stringify({ error: { message: "That token is not valid, has expired or was revoked." } }), { status: 401, headers: { "www-authenticate": 'Bearer realm="lembas"' } })])) + const { c, events, init } = stdioClient({ clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }) + await init + const s: any = await c.request("session/new", { cwd: project(), mcpServers: [] }) + const failed: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] }) + // The stop reason is as before: ACP has none for a failure. + expect(failed.stopReason).toBe("end_turn") + expect(failed._meta.lembas.error.code).toBe("signed_out") + expect(failed._meta.lembas.error.message).toContain("That token is not valid") + expect(failed._meta.lembas.error.message).not.toContain("\n") + // The event is still there, for a client that reads events, and carries the same code. + expect(events.find((e) => e.type === "error")).toMatchObject({ code: "signed_out" }) + // A turn that works has no error. + const fine: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "again" }] }) + expect(fine._meta.lembas.error).toBeUndefined() +}) + +test("a 401 without the server's challenge is a model provider's, passed through: failed, in its words, and no sign-out", async () => { + config(chat([new Response(JSON.stringify({ error: { message: "Incorrect API key provided to the provider." } }), { status: 401 })])) + const { c, init } = stdioClient({ clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }) + await init + const s: any = await c.request("session/new", { cwd: project(), mcpServers: [] }) + const r: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] }) + expect(r._meta.lembas.error.code).toBe("failed") + expect(r._meta.lembas.error.message).toContain("Incorrect API key provided to the provider.") + // The same holds for every request with the device's token. + const bare = Bun.serve({ port: 0, fetch: () => Response.json({ detail: "upstream said no" }, { status: 401 }) }) + const own = Bun.serve({ port: 0, fetch: () => Response.json({ detail: "That token is not valid, has expired or was revoked." }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="lembas"' } }) }) + stops.push(() => (bare.stop(true), own.stop(true))) + const passed = await models({ api: { openai: `http://127.0.0.1:${bare.port}/v1` } }, "lmb_x", undefined).catch((e) => e) + expect(passed).toBeInstanceOf(LembasError) + expect(passed).not.toBeInstanceOf(SignInRejected) + expect([passed.code, passed.message]).toEqual(["failed", "listing the models: upstream said no"]) + const refused = await models({ api: { openai: `http://127.0.0.1:${own.port}/v1` } }, "lmb_x", undefined).catch((e) => e) + expect(refused).toBeInstanceOf(SignInRejected) + expect(refused.code).toBe("signed_out") + expect((await apiCall(`http://127.0.0.1:${bare.port}`, "lmb_x", undefined, "GET", "/v1/x")).signedOut).toBe(false) + expect((await apiCall(`http://127.0.0.1:${own.port}`, "lmb_x", undefined, "GET", "/v1/x")).signedOut).toBe(true) +}) + +test("a server that cannot be reached is `unreachable` in the answer, and plain ACP clients get it too", async () => { + const closed = Bun.serve({ port: 0, fetch: () => new Response("no") }) + const port = closed.port + closed.stop(true) + config(`http://127.0.0.1:${port}`) + // No `_meta.lembas` at all: this client gets no events — only the answer can tell it. + const { c, init } = stdioClient({ clientCapabilities: {} }) + await init + const s: any = await c.request("session/new", { cwd: project(), mcpServers: [] }) + const r: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] }) + expect(r._meta.lembas.error.code).toBe("unreachable") + expect(r._meta.lembas.error.message).toContain("cannot reach") +}) + +test("a failure's code: from why no answer came, else from its status, else failed", () => { + // A bare 401 is not the server's refusal of the token: only one with its challenge is. + expect(failureCode(new ProviderError("x", 401))).toBe("failed") + expect(failureCode(Object.assign(new ProviderError("x", 401), { code: "signed_out" }))).toBe("signed_out") + expect(failureCode(new ProviderError("x", 403))).toBe("not_allowed") + expect(failureCode(new ProviderError("x", 429))).toBe("busy") + expect(failureCode(new ProviderError("x", 503))).toBe("server_error") + expect(failureCode(new ProviderError("x", 400))).toBe("failed") + expect(failureCode(new ProviderError("x"))).toBe("failed") + expect(failureCode(new Error("x"))).toBe("failed") + expect(turnError({ message: "\n first line \nsecond" })).toEqual({ code: "failed", message: "first line" }) +}) + +test("the stdio agent reads and logs clientInfo, and answers its own protocol to a client that says a higher one", async () => { + const logged: string[] = [] + const error = console.error + console.error = (...a: unknown[]) => void logged.push(a.join(" ")) + stops.push(() => (console.error = error)) + // An editor that says protocol 2: both use 2, nothing to tell. + const two = stdioClient({ clientInfo: { name: "llembas-nvim", version: "1.0.0" }, clientCapabilities: { _meta: { lembas: { protocol: 2, editor: true } } } }) + const a = await two.init + expect(a._meta.lembas.protocol).toBe(3) + expect(a._meta.lembas.notice).toBeUndefined() + expect(two.agent.client).toBe("llembas-nvim/1.0.0") + expect(logged.at(-1)).toBe("client: llembas-nvim/1.0.0, protocol 2") + // A client from the future: answered 3, in the field and in words. + const four = stdioClient({ clientInfo: { name: "llembas-tty", version: "9.0.0" }, clientCapabilities: { _meta: { lembas: { protocol: 4 } } } }) + const b = await four.init + expect(b._meta.lembas.protocol).toBe(3) + expect(b._meta.lembas.notice).toContain("speaks protocol 3, and the client said 4: both use 3") + expect(logged.at(-1)).toContain("client: llembas-tty/9.0.0, protocol 3 — ") + // No name, and plain ACP: said as such; a name with control characters is cleaned for the log. + const plain = stdioClient({ clientCapabilities: {} }) + await plain.init + expect(logged.at(-1)).toBe("client: unnamed, protocol none (plain ACP)") + expect(clientName({ name: "ed\u001b[31mitor\n", version: "1" })).toBe("ed [31mitor/1") + expect(clientName({ name: "x".repeat(500) })!.length).toBe(80) + expect(clientName(undefined)).toBeUndefined() + expect(clientName({ version: "1" })).toBeUndefined() +}) + +// ---- the smaller rules -------------------------------------------------------------------- + +test("a line from the client with no end is given up on, not read into memory", async () => { + const input = new PassThrough() + const output = new PassThrough() + const said: string[] = [] + const error = console.error + console.error = (...a: unknown[]) => void said.push(a.join(" ")) + stops.push(() => (console.error = error)) + const t = stdioTransport(input, output, 1024) + const got: string[] = [] + let closed = 0 + t.onMessage((m) => void got.push(m)) + t.onClose(() => void closed++) + // Lines within the limit pass, however many arrive in one chunk. + input.write(`{"a":1}\n{"b":"${"x".repeat(900)}"}\n`) + await Bun.sleep(10) + expect(got.length).toBe(2) + expect(closed).toBe(0) + input.write("y".repeat(2000)) + await Bun.sleep(10) + expect(closed).toBe(1) + expect(said.at(-1)).toContain("a line longer than") + // Nothing after it is read, and the end is not said twice. + input.write('\n{"c":1}\n') + input.end() + await Bun.sleep(10) + expect(got.length).toBe(2) + expect(closed).toBe(1) + expect(CONNECTION.stdio.line_bytes).toBe(64 * 1024 * 1024) +}) + +test("the service's lock: made exclusively, refused while its holder runs, taken over from one that is gone", () => { + const dir = mkdtempSync(join(tmpdir(), "ph-lock-")) + const file = join(dir, "service.lock") + const release = takeLock(file) + // This process is not "another copy": a lock naming itself is stale (a restart reusing a pid). + expect(holdsLock(process.pid)).toBe(false) + release() + // A pid nobody has: stale, taken over. + writeFileSync(file, "2147483646") + expect(holdsLock(2147483646)).toBe(false) + takeLock(file)() + // A pid that is alive but is not a `lembas service` (pid 1, where /proc says what it is): a + // number recycled since a crash does not hold the lock. + if (process.platform === "linux") { + expect(holdsLock(1)).toBe(false) + writeFileSync(file, "1") + takeLock(file)() + } + // Garbage in the file: stale. + writeFileSync(file, "not a pid") + const again = takeLock(file) + // Releasing gives up only this process's own lock, never one somebody else has taken since. + writeFileSync(file, "2147483646") + again() + expect(Bun.file(file).size).toBeGreaterThan(0) +}) + +test("Retry-After on a 429 is honoured: the request is made again after it, and the header is read as seconds", async () => { + let hits = 0 + let agent = "" + const srv = Bun.serve({ + port: 0, + fetch(req) { + agent = req.headers.get("user-agent") ?? "" + return ++hits === 1 ? new Response("slow down", { status: 429, headers: { "retry-after": "1" } }) : new Response("ok") + }, + }) + stops.push(() => srv.stop(true)) + const url = `http://127.0.0.1:${srv.port}/v1/chat/completions` + const e = await request(url, { method: "POST", body: "{}" }, "m").catch((x) => x) + expect(e).toBeInstanceOf(ProviderError) + expect([e.status, e.retryAfter]).toEqual([429, 1]) + // Every request to the server says who is asking. + expect(agent).toBe(USER_AGENT) + // The retry rule waits what it said, says so, and asks again. + hits = 0 + const events: StreamEvent[] = [] + const started = Date.now() + for await (const ev of retrying(async function* () { + await request(url, { method: "POST", body: "{}" }, "m") + yield { type: "text", text: "done" } as StreamEvent + })) + events.push(ev) + expect(Date.now() - started).toBeGreaterThanOrEqual(950) + expect(events.map((x) => x.type)).toEqual(["notice", "text"]) + expect((events[0] as { retry?: { in: number } }).retry?.in).toBe(1) + // Without a Retry-After the refusal stands, as before. + const bare = await (async () => { + for await (const _ of retrying(async function* (): AsyncGenerator { + throw new ProviderError("m: HTTP 429: slow down", 429) + })) void _ + })().catch((x) => x) + expect(bare).toBeInstanceOf(ProviderError) + // A wait is given up when the turn is cancelled. + const stop = new AbortController() + setTimeout(() => stop.abort(), 30) + const t0 = Date.now() + const cancelled = await (async () => { + for await (const _ of retrying( + async function* (): AsyncGenerator { + const err = new ProviderError("m: HTTP 429: slow down", 429) + err.retryAfter = 30 + throw err + }, + undefined, + stop.signal, + )) void _ + })().catch((x) => x) + expect(Date.now() - t0).toBeLessThan(2000) + expect((cancelled as Error).message).toBe("cancelled") +}) + +// ---- which address is stored, and the server's minimum ------------------------------------ + +/** A stand-in server for signing in with a token: discovery saying what the test tells it to say + * of itself, the instance and its models for one token, and what was signed out. */ +function instance(o: { reported?: (asked: string) => string; endpoints?: (asked: string) => string; min_clients?: unknown } = {}) { + const state = { token: "lmb_new", signedOut: [] as { token: string; replacedBy?: string }[], heard: [] as string[] } + const srv = Bun.serve({ + port: 0, + async fetch(req) { + const u = new URL(req.url) + const asked = `http://${u.host}` + state.heard.push(`${req.method} ${u.host}${u.pathname}`) + const at = o.endpoints?.(asked) ?? asked + if (u.pathname === "/.well-known/lembas.json") + return Response.json({ + service: "lembas", + version: "2.0.0", + name: "Example", + connection: "example", + protocol: 3, + protocols: [3], + harness_spec: "3.11.0", + base_url: o.reported?.(asked) ?? asked, + ...(o.min_clients === undefined ? {} : { min_clients: o.min_clients }), + api: { openai: `${at}/v1` }, + login: { device: { code: `${at}/api/device/code`, token: `${at}/api/device/token`, verify: `${at}/device` } }, + }) + const auth = (req.headers.get("authorization") ?? "").replace(/^Bearer /, "") + if (u.pathname === "/api/v1/token" && req.method === "DELETE") { + const text = await req.text() + state.signedOut.push({ token: auth, replacedBy: text ? JSON.parse(text).replaced_by : undefined }) + return new Response(null, { status: 204 }) + } + if (auth !== state.token) return Response.json({ detail: "no" }, { status: 401, headers: { "www-authenticate": 'Bearer realm="lembas"' } }) + if (u.pathname === "/v1/models") return Response.json({ object: "list", data: [{ id: "qwen", default: true }] }) + if (u.pathname === "/api/v1/instance") return Response.json({ name: "Example", connection: "example", scope: "models memory link", account: { email: "sam@example.org" }, default_model: "qwen" }) + return new Response("not found", { status: 404 }) + }, + }) + stops.push(() => srv.stop(true)) + // Two spellings of one server: what a person types, and what a proxy in front of it might make + // the server call itself. + return { state, port: srv.port, typed: `http://127.0.0.1:${srv.port}`, other: `http://localhost:${srv.port}` } +} + +const index = () => JSON.parse(readFileSync(join(paths.config, "lembas.json"), "utf8")).instances as Record }> +const cleanConfig = () => { + rmSync(paths.config, { recursive: true, force: true }) + mkdirSync(paths.config, { recursive: true }) +} + +test("a new login stores the typed address, normalised — never the base_url the server names", async () => { + cleanConfig() + const i = instance({ reported: () => "http://backend.example.org:8080" }) + const r = await loginWithToken(`${i.typed}/chat/?tab=1`, i.state.token) + expect(r.instance.base_url).toBe(i.typed) + expect(index().example!.base_url).toBe(i.typed) + expect(readFileSync(join(paths.config, "connections.yaml"), "utf8")).toContain(`url: ${i.typed}\n`) + expect(readFileSync(join(paths.config, "connections.yaml"), "utf8")).not.toContain("backend.example.org") + // Nothing was asked of the address the server named. + expect(i.state.heard.every((h) => h.includes(`127.0.0.1:${i.port}`))).toBe(true) + // The link dials the stored address too. + expect(heldLogin().instance.base_url).toBe(i.typed) +}) + +test("a login kept from before: it works untouched, read through the one address rule", async () => { + cleanConfig() + const i = instance() + // As an older CLI left it: what the server said of itself, with a path and a slash. + mkdirSync(join(paths.config, "lembas"), { recursive: true }) + writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { base_url: `HTTP://LOCALHOST:${i.port}/`, connection: "example", logged_in_at: "2026-01-01T00:00:00.000Z" } } })) + writeFileSync(join(paths.config, "lembas", "example.key"), `${i.state.token}\n`, { mode: 0o600 }) + writeFileSync(join(paths.config, "connections.yaml"), `connections:\n example:\n type: webui\n url: http://localhost:${i.port}/\n api_key: "{file:${join(paths.config, "lembas", "example.key")}}"\n`, { mode: 0o600 }) + expect(instances().example!.base_url).toBe(i.other) + expect(heldLogin().instance.base_url).toBe(i.other) + // It still refreshes its models, at the address it has. + const r = await sync("example") + expect(r.models.map((m) => m.id)).toEqual(["qwen"]) + expect(i.state.signedOut).toEqual([]) + // Still one login, still at its own address: nothing is migrated without a new sign-in. + expect(Object.keys(instances())).toEqual(["example"]) + expect(instances().example!.base_url).toBe(i.other) +}) + +test("a kept login whose address is the one the server names is the same login as the typed one: replaced, no twin", async () => { + cleanConfig() + // The server calls itself by another address than the one typed — what the old login stored. + const i = instance({ reported: (asked) => asked.replace("127.0.0.1", "localhost") }) + mkdirSync(join(paths.config, "lembas"), { recursive: true }) + writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { base_url: i.other, connection: "example", logged_in_at: "2026-01-01T00:00:00.000Z" } } })) + writeFileSync(join(paths.config, "lembas", "example.key"), "lmb_old\n", { mode: 0o600 }) + writeFileSync(join(paths.config, "connections.yaml"), `connections:\n example:\n type: webui\n url: ${i.other}\n api_key: "{file:${join(paths.config, "lembas", "example.key")}}"\n`, { mode: 0o600 }) + const r = await loginWithToken(i.typed, i.state.token) + // One login, under the same name, now at the typed address — and no `example-lembas` beside it. + expect(Object.keys(index())).toEqual(["example"]) + expect(r.connection).toBe("example") + expect(index().example!.base_url).toBe(i.typed) + const yaml = readFileSync(join(paths.config, "connections.yaml"), "utf8") + expect(yaml).not.toContain("example-lembas") + expect(yaml).toContain(`url: ${i.typed}\n`) + // The older token was signed out — at the address it was stored with, and without naming the + // new one: that the two addresses are one server is only the server's word. + expect(i.state.signedOut).toEqual([{ token: "lmb_old", replacedBy: undefined }]) + expect(i.state.heard.filter((h) => h.startsWith("DELETE"))).toEqual([`DELETE localhost:${i.port}/api/v1/token`]) + expect(readFileSync(join(paths.config, "lembas", "example.key"), "utf8").trim()).toBe("lmb_new") + expect(r.changes.some((c) => c.includes("signed out of"))).toBe(false) +}) + +test("a server that names another server's address as its own gets neither that server's token nor the new one's name there", async () => { + cleanConfig() + const first = instance() + first.state.token = "lmb_first_servers" + await loginWithToken(first.typed, first.state.token) + // A second server whose discovery claims the first one's address. + const second = instance({ reported: () => first.typed }) + await loginWithToken(second.typed, second.state.token) + // The first server's token never reached the second… + expect(second.state.signedOut).toEqual([]) + expect(second.state.heard.some((h) => h.startsWith("DELETE"))).toBe(false) + // …it was signed out where it belongs, and the second server's token was not named there. + expect(first.state.signedOut).toEqual([{ token: "lmb_first_servers", replacedBy: undefined }]) + // One login is left, at the address that was typed. + expect(Object.keys(index())).toEqual(["example"]) + expect(index().example!.base_url).toBe(second.typed) +}) + +test("logging in again at the same address hands the old token over to the new one, as before", async () => { + cleanConfig() + const i = instance() + i.state.token = "lmb_old" + await loginWithToken(i.typed, "lmb_old") + i.state.token = "lmb_new" + // Typed another way: still the same server by the one address rule. + await loginWithToken(`HTTP://127.0.0.1:${i.port}/`, "lmb_new") + expect(i.state.signedOut).toEqual([{ token: "lmb_old", replacedBy: "lmb_new" }]) + expect(Object.keys(index())).toEqual(["example"]) +}) + +test("an endpoint discovery names on another origin is not followed: refused in words, nothing written", async () => { + cleanConfig() + // Sign-in endpoints on another spelling of the host: another origin, as far as anybody can tell. + const i = instance({ endpoints: (asked) => asked.replace("127.0.0.1", "localhost") }) + let shown = 0 + const e = await login(i.typed, { onCode: () => void shown++ }).catch((x) => x) + expect(e).toBeInstanceOf(LembasError) + expect(e.code).toBe("other_origin") + expect(e.message).toContain(`names an address on another server (http://localhost:${i.port}/api/device/`) + expect(e.message).toContain("does not follow it") + expect(shown).toBe(0) + // Only discovery was asked: the code endpoint never heard from this machine. + expect(i.state.heard).toEqual([`GET 127.0.0.1:${i.port}/.well-known/lembas.json`]) + expect(existsSync(join(paths.config, "lembas.json"))).toBe(false) + // What the CLI reaches by its own paths on the typed address is not affected: a token handed + // over (as the desktop app does) signs in. + const r = await loginWithToken(i.typed, i.state.token) + expect(r.instance.base_url).toBe(i.typed) +}) + +test("min_clients: a CLI below the server's minimum is told so at discovery, with both versions, and goes no further", async () => { + cleanConfig() + const below = instance({ min_clients: { cli: "99.0.0", nvim: "1.2.0" } }) + const e = await loginWithToken(below.typed, below.state.token).catch((x) => x) + expect(e).toBeInstanceOf(LembasError) + expect(e.code).toBe("client_too_old") + expect(e.message).toBe(`127.0.0.1:${below.port} needs LLeMbas CLI 99.0.0 or later, and this is ${VERSION}. Update LLeMbas CLI. Run lembas update.`) + expect(below.state.heard).toEqual([`GET 127.0.0.1:${below.port}/.well-known/lembas.json`]) + expect(existsSync(join(paths.config, "lembas.json"))).toBe(false) + // No minimum for this product, an empty table, a value that is not a version, a minimum met: fine. + for (const min_clients of [{}, { desktop: "99.0.0" }, { cli: "soon" }, { cli: "0.0.1" }, { cli: VERSION }, "nonsense", null]) { + cleanConfig() + const ok = instance({ min_clients }) + expect((await loginWithToken(ok.typed, ok.state.token)).instance.base_url).toBe(ok.typed) + } +}) + +test("the stdio agent tells its client the server's minimum for the client's own product: _meta.lembas.min_client", async () => { + cleanConfig() + const i = instance({ min_clients: { nvim: "1.2.0", vscode: "1.0.0-beta.9", desktop: "not a version" } }) + await loginWithToken(i.typed, i.state.token) + expect(index().example!.min_clients).toEqual({ nvim: "1.2.0", vscode: "1.0.0-beta.9", desktop: "not a version" }) + const quiet = console.error + console.error = () => {} + stops.push(() => (console.error = quiet)) + const ask = async (clientInfo?: Record) => (await stdioClient({ ...(clientInfo ? { clientInfo } : {}), clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }).init)._meta.lembas.min_client + expect(await ask({ name: "llembas-nvim", version: "1.0.0" })).toBe("1.2.0") + expect(await ask({ name: "llembas-vscode", version: "1.0.0" })).toBe("1.0.0-beta.9") + // No minimum for the product, one that is not a version, a client that is no LLeMbas product, none named: absent. + expect(await ask({ name: "llembas-tty", version: "1.0.0" })).toBeUndefined() + expect(await ask({ name: "llembas-desktop", version: "1.0.0" })).toBeUndefined() + expect(await ask({ name: "some-editor", version: "1.0.0" })).toBeUndefined() + expect(await ask()).toBeUndefined() + expect(minClientFor("llembas-nvim")).toBe("1.2.0") + // What the server says later is kept at the next look (a refresh, the service's dial). + const next = instance({ min_clients: { nvim: "1.3.0" } }) + writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { ...index().example, base_url: next.typed } } })) + await refreshDiscovery() + expect(minClientFor("llembas-nvim")).toBe("1.3.0") + // Not logged in: absent. + cleanConfig() + expect(await ask({ name: "llembas-nvim", version: "1.0.0" })).toBeUndefined() +}) diff --git a/tests/lembas-login.test.ts b/tests/lembas-login.test.ts index 3e8f731..690a980 100644 --- a/tests/lembas-login.test.ts +++ b/tests/lembas-login.test.ts @@ -97,7 +97,9 @@ function lembas(o: Partial - expect(body.client_id).toStartWith("lembas-cli ") + // One name everywhere (harness connection.md §3): the User-Agent's own string. + expect(body.client_id).toMatch(/^llembas-cli\/\d+\.\d+\.\d+/) + expect(req.headers.get("user-agent")).toBe(body.client_id!) expect(body.scope).toBe("models memory link") return Response.json({ device_code: "dev-123", user_code: "CDFG-HJKM", verification_uri: `${base}/device`, verification_uri_complete: `${base}/device?code=CDFG-HJKM`, expires_in: 600, interval: 1 }) } @@ -115,7 +117,8 @@ function lembas(o: Partial {} })).rejects.toThrow("Update LLeMbas CLI") fake.stop() fake = lembas({ protocol: 2 }) - await expect(login(fake.url, { ...quick, onCode: () => {} })).rejects.toThrow("needs a LLeMbas 2.0 server (protocol 3). Update the server, or use LLeMbas CLI 1.x with it.") + await expect(login(fake.url, { ...quick, onCode: () => {} })).rejects.toThrow("which is too old for this LLeMbas CLI. Update the server. Or use LLeMbas CLI 1.x with it.") fake.stop() const other = Bun.serve({ port: 0, fetch: () => new Response("hello", { status: 404 }) }) try { - await expect(login(`http://127.0.0.1:${other.port}`, { ...quick, onCode: () => {} })).rejects.toThrow("not a LLeMbas instance") + await expect(login(`http://127.0.0.1:${other.port}`, { ...quick, onCode: () => {} })).rejects.toThrow("answers, but is not a LLeMbas server") } finally { other.stop(true) } @@ -523,7 +526,7 @@ test("--token-stdin refuses, writing nothing: no link, a token not accepted, an fake.stop() // Another protocol: the device login's own words. fake = lembas({ protocol: 2 }) - await expect(loginWithToken(fake.url, "lmb_secret")).rejects.toThrow("needs a LLeMbas 2.0 server (protocol 3). Update the server, or use LLeMbas CLI 1.x with it.") + await expect(loginWithToken(fake.url, "lmb_secret")).rejects.toThrow("which is too old for this LLeMbas CLI. Update the server. Or use LLeMbas CLI 1.x with it.") fake.stop() fake = lembas({ protocol: PROTOCOL + 1 }) await expect(loginWithToken(fake.url, "lmb_secret")).rejects.toThrow("Update LLeMbas CLI")