Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ each crate's `docs.md`.
| --- | --- |
| [glossary.md](glossary.md) | Canonical terms for actors, turns, sessions, and tools |
| [turn-lifecycle.md](turn-lifecycle.md) | Turn state, `session/update` routing, and cancellation |
| [remote-control.md](remote-control.md) | Remote ACP transport behind `--remote` and `/remote-control` |
| [remote-control.md](remote-control.md) | Remote ACP transport, authenticated background hosts, and attached terminals |
| [nori-client-mcp.md](nori-client-mcp.md) | The backend-owned `nori-client` MCP server and goals |
| [headless.md](headless.md) | `nori exec` plaintext mode and the ACP stdio facade |
| [transcripts.md](transcripts.md) | Transcript file locations and schema |
Expand Down
153 changes: 139 additions & 14 deletions docs/remote-control.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
# Remote ACP Transport

**Status:** Implemented ACP transport plus feature-gated managed-session transport

**Date:** 2026-08-23 (revised 2026-11-15)

**Upstream:** [ACP Streamable HTTP & WebSocket Transport RFD](https://agentclientprotocol.com/rfds/streamable-http-websocket-transport)

## 1. Decision
Expand All @@ -21,8 +17,10 @@ wildcard listener or separate session-host crate is introduced.
Without `[features] multi_session`, `nori exec --acp` remains a bounded,
terminal-independent stdio facade and `/acp` exposes the interactive harness.
With the flag, `/sessions` and the existing exec facade share the managed
session commands described in section 10. This adds transport primitives only;
it does not introduce host/attach commands or a persistent host lifecycle.
session commands described in section 10. The separate `nori host` process
owns sessions without a terminal; `nori attach` is its feature-gated terminal
frontend. Its authenticated endpoint and controller/watcher policy are
described in section 11.
Sections 3–6 describe the legacy `/acp` projection unless stated otherwise.

## 2. Topology
Expand Down Expand Up @@ -277,8 +275,9 @@ nori-rs/
```

The `--remote` flag lives on the interactive CLI surface and is normalized into
the same TUI-owned manager as runtime commands; the `cli` crate itself remains
unchanged. Remote prompts use the same harness-originated user-message
the same TUI-owned manager as runtime commands. Background host commands are
dispatched separately by [`cli/src/host`](../nori-rs/cli/src/host/docs.md).
Remote prompts use the same harness-originated user-message
notifications as local prompts, so their
original content is visible in the observing TUI and every attached frontend.

Expand All @@ -301,9 +300,11 @@ v1 transport:
- An initialized socket receives live session updates before it explicitly
attaches to the session through `session/load` or `session/resume`.

Authentication, TLS, endpoint discovery, broker routing, Handroll federation,
capability aggregation across hosts, Streamable HTTP/SSE, and replay across a
host-process restart remain outside this implementation. Legacy `/acp` retains
The legacy `--remote` surface remains unauthenticated. The background host
requires a token and supports same-machine discovery (section 11). TLS
termination, broker routing, Handroll federation, capability aggregation across
hosts, Streamable HTTP/SSE, and replay across a host-process restart remain
outside this implementation. Legacy `/acp` retains
its transcript-based recovery; managed envelopes add bounded reconnect replay
within the current manager lifetime.

Expand Down Expand Up @@ -406,9 +407,9 @@ supply `replay_cursors` for all-session live following, or the chosen row's
`latest_seq` for one session. This is an explicit new observation point, not
recovery of the missing prefix.

`/acp` and `/sessions` share one controller slot across all exact listeners;
last connect wins. Whether future clients can both control, or one can control
while another watches, remains a pending D2 decision. Disconnect or listener
On the legacy `--remote` surface, `/acp` and `/sessions` share one controller
slot across all exact listeners; last connect wins. The background host uses
the controller/watcher policy below instead. Disconnect or listener
shutdown detaches managed clients without stopping sessions, cancelling admitted turns, or answering pending
permissions. Those permissions remain visible and answerable after reconnect
or from the TUI. A slow managed consumer is dropped when its bounded live queue
Expand All @@ -421,3 +422,127 @@ resubscribe share the same cursor validation, so expiry cannot silently lose
history. Stdio encoding or writer failure cannot guarantee an ending
notification. At the exec process boundary, stdin EOF shuts down all managed
sessions.

## 11. Background host and attached terminals

`nori host` starts a detached Unix process with an initially empty
`SessionManager`. The host owns the agent processes and remains alive when
every terminal detaches or the last session ends. It binds only loopback,
defaults to port 7420, and accepts `--port 0` to allocate a port. `nori host stop`
authenticates, requests shutdown, and waits for the host's singleton lock to be
released after cleanup. Startup and stop do not require a terminal.

| Command | Behavior |
| --- | --- |
| `nori host` | Start the background host, or report the already-running host. |
| `nori host ls` | Print the flat `ID AGENT STATUS AGE TITLE` table; TTY output colors status and truncates titles to the terminal width, while piped output keeps full titles without color. |
| `nori attach` | Open the host session list; requires `[features] multi_session = true`. |
| `nori attach <id>` | Open the named Nori conversation. |
| `nori attach --host <URL> --token-file <path>` | Connect to an explicit managed endpoint using a private token file. |
| `nori host stop` | Stop the listener and all host-owned sessions. |

The CLI stores discovery state, token, log, and lock under `$NORI_HOME/host`.
The directory is created with mode `0700`; files are created with mode `0600`.
Existing paths must be owned by the effective user and inaccessible to group
and other users; files must be regular and cannot be symlinks. An OS-held lock,
not the saved PID, determines whether the host is running. Each host start
generates a new token and publishes its endpoint only after binding. Local
commands read that token automatically; startup prints its path, never its
value. Background hosting is refused on platforms without the implemented Unix
permission checks.

`RemoteAcpServer::bind_host` exposes only `/sessions`, with no legacy `/acp`
route. A valid `Authorization: Bearer <token>` header is required before the
WebSocket upgrade, including on loopback; a missing or wrong token returns
HTTP 401. This policy applies to `nori host`, not the separate `--remote` or
`/remote-control` listeners.

Successful authenticated upgrades include `x-nori-host-instance`, a UUID
generated for that router lifetime independently of the bearer token. It stays
stable across connections and changes when a new host router starts, even if
the address and token are reused. Reconnecting clients check this identity
before initialization or replay so an old cursor cannot silently target a new
manager.

The terminal table budgets display cells, preserving grapheme boundaries and
adding an ellipsis when a title exceeds the remaining width. If the terminal
cannot fit the metadata columns, the row prefix is clipped too. Piped output
has no width limit; control characters are sanitized in either mode.

```text
attached controller -- commands --+
v
attached watchers --------> authenticated /sessions --> HostService
^ | |
| +-- role changes v
+---------- ordered replay/live events ------ SessionManager
|
ACP agent processes
```

### Control and lifecycle requests

The first successful interactive `initialize` claims control when the slot is
empty. Later clients remain connected as watchers. `initialize` with
`{"observe":true}` never claims the slot, so polling `host ls` and running
administrative stop do not take control. Initialization returns
`result.control` containing `role` and `controller_connected`.

| Method | Meaning |
| --- | --- |
| `_nori/control/status` | Return this connection's role and whether a controller is connected. |
| `_nori/control/take` | Transfer control to the caller without closing another connection. |
| `_nori/session/new` | Start a session with the host configuration; optional `agent` selects its agent. |
| `_nori/session/close`, `_nori/session/cancel`, `_nori/session/resume` | Apply the operation to the required `session_id`; resume retains the Nori conversation ID. |
| `_nori/host/stop` | Request host shutdown; any authenticated initialized client may call it. |

`_nori/control/changed` notifications carry the new `role` to terminals affected
by a handoff. The admission mutex serializes the ownership check with handoff,
then releases before awaiting the backend. An already-admitted operation may
finish after control moves; new mutations from the previous controller are
refused. A slow operation on one connection does not hold up another client's
initialization, list, takeover, or stop. Watchers can list, subscribe, and take
control; session mutations, including prompts and permission answers, fail with
`-32016` and a read-only error. When the controller disconnects, existing
watchers are not automatically promoted. They may take control explicitly, or
a new interactive initializer may claim the empty slot.

### Attached frontend and recovery

The dedicated [`attach` frontend](../nori-rs/tui/src/attach/docs.md) uses the
managed client through harness re-exports. It owns terminal state and replay
cursors, never the host's agent processes. Alt+T takes control; Ctrl+D or
`/quit` detaches. The configured `hotkeys.open_session_list` binding, Left with
an empty composer, or `/sessions` opens the session list. Ctrl+R resumes its
highlighted failed session with the same conversation ID. The status line shows
controlling, watching/read-only, reconnecting, or disconnected state. The
current session marker appears inside TITLE, leaving its short ID visible.
Session commands address the host; they do not launch local agents.

Socket loss or a receive-liveness deadline starts recovery. Periodic session
list requests keep idle connections observable; receiving JSON renews the
deadline, while outgoing traffic alone does not. The deadline also bounds
blocked sends. The frontend retains its rendered sessions, reconnects, verifies
the host-instance identity, initializes again, and subscribes to the selected
conversation with its last applied cursor. Switching conversations uses that conversation's saved cursor;
the session list refreshes independently without subscribing to every session.
It advances a cursor only after applying that envelope and ignores duplicates.
Transcript restoration is distinct: `ReplayStarted` replaces the rendered
conversation and pending permissions without resetting transport sequence
tracking. Permission prompts also clear when the turn becomes idle or begins
cancelling, the session ends, or a matching answer is resolved. The frontend
does not retransmit mutations whose acknowledgement may have been lost.
Replay expiry or an unexpected sequence gap is visible as an error; the
frontend does not silently jump to live output. Replay is bounded to the
current host process lifetime, so a fresh attachment may also encounter an
expired prefix. Restarting a host does not restore its in-memory manager.

On HTTP 401 or 403 during reconnect, a locally discovered attachment rereads
the current token file using the same ownership, permission, and regular-file
checks as startup, then retries once. An explicit `--host` attachment never
rediscovers local credentials. An unavailable token, failed retry, or changed
or unavailable host identity stops recovery and leaves a persistent message
in the terminal. A confirmed identity change reports that the host restarted
and its sessions were lost; authentication failures report that the host may
have restarted. The rendered history and unsent draft remain visible. Detach
with Ctrl+D and rerun `nori attach` to connect afresh.
5 changes: 5 additions & 0 deletions nori-rs/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion nori-rs/acp-host/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ tokio = { workspace = true, features = [
"time",
] }
tokio-util = { workspace = true, features = ["compat"] }
tokio-tungstenite = { workspace = true }
tracing = { workspace = true, features = ["log"] }
uuid = { workspace = true, features = ["v4"] }
which = { workspace = true }

[dev-dependencies]
pretty_assertions = { workspace = true }
tokio-tungstenite = { workspace = true }
rmcp = { workspace = true, features = [
"client",
"transport-streamable-http-client-reqwest",
Expand Down
33 changes: 31 additions & 2 deletions nori-rs/acp-host/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ implementing the WebSocket profile of the upstream ACP "Streamable HTTP &
WebSocket Transport" RFD, serving the hosted harness session outward as an ACP
Agent. The optional `/sessions` endpoint carries managed session commands and
full manager envelopes (see [the wire contract](../../docs/remote-control.md)).
The background-host listener has a separate authenticated `/sessions` route
with controller/watcher ownership and a reusable managed WebSocket client.

### How it fits into the larger codebase

Expand Down Expand Up @@ -77,7 +79,7 @@ the session registry nor replay retention. The dependency direction stays
`features.goals = false`, leaving Nori-owned goal state to the `nori-client`
MCP server. `error_category.rs` preserves structured ACP errors before
falling back to message classification.
- `remote/` serves one logical ACP surface through one or more exact-address
- The legacy remote surface serves ACP through one or more exact-address
axum listeners. `RemoteAcpServer::bind_many` binds every socket before any
begins serving; a zero port after the first address reuses the first
listener's allocated port. The listeners share one active-connection slot
Expand All @@ -91,6 +93,27 @@ the session registry nor replay retention. The dependency direction stays
bounded live queues and timed socket writes prevent a slow client from
blocking manager publication. The frontend opts into this route only with
runtime `multi_session` enabled.
- `bind_host` serves only authenticated `/sessions`, using
[`host_wire.rs`](src/remote/host_wire.rs) and
[`host_control.rs`](src/remote/host_control.rs). The first interactive
initializer controls; other clients watch until an explicit takeover.
Observation-only initialization never claims control. A mutex serializes
mutation admission with handoff, then releases before backend work. An
admitted operation may finish after takeover, while later old-owner mutations
are refused. Slow backend operations cannot lock out other clients' control
or administrative requests. Role notifications preserve every connection.
Watcher mutations fail before reaching `ManagedAgent`; listing,
subscribing, taking control, and authenticated host stop remain available.
Successful authenticated upgrades include `x-nori-host-instance`, a UUID
generated once per router lifetime independently of the bearer token. Clients
can compare it before replaying against a replacement listener at the same
address.
- [`ManagedClient`](src/remote/client.rs) authenticates the upgrade and exposes
the optional host-instance UUID and HTTP 401/403 authentication classification,
alongside streaming send/receive for frontends that retain notifications.
Its sequential request helper intentionally ignores intervening notifications and is used by
short-lived administrative commands. Reconnect policy and cursor state belong
to the frontend, not this socket wrapper.
- Each `/acp` listener sends a fresh `Acp-Connection-Id` on a 101 upgrade and
`426 Upgrade Required` for plain HTTP. One JSON-RPC message occupies each
UTF-8 text frame, adapted into the SDK's `Lines` transport
Expand Down Expand Up @@ -195,7 +218,7 @@ the session registry nor replay retention. The dependency direction stays
- Terminal and extension request families are not advertised by the current
host. Adding them requires an explicit host-policy decision, not a generic
protocol mirror.
- The remote WebSocket server is unauthenticated. `parse_bind_addr` treats a
- The legacy `--remote` WebSocket surface is unauthenticated. `parse_bind_addr` treats a
bare port as a loopback bind and refuses non-loopback addresses without the
caller's explicit opt-in flag. Exact-address selection, wildcard rejection,
dangerous-exposure confirmation, endpoint reporting, and runtime listener
Expand All @@ -204,6 +227,12 @@ the session registry nor replay retention. The dependency direction stays
snapshots `local_addrs()` and consumes the old server; if the new bind fails,
it uses `bind_many` to restore the previous exact surface. A failed restore is
distinct from the original bind failure and leaves no server running.
- The background-host listener requires a nonempty bearer token, even on
loopback, and returns HTTP 401 before upgrade for missing or invalid tokens.
It exposes no `/acp` fallback. The CLI owns token generation, private file
validation, daemon lifetime, and loopback bind policy; this crate owns
authentication and connection roles. A disconnected controller leaves the
slot empty without promoting an existing watcher.
- Every accepted upgrade receives a child of the server-wide cancellation
token. Consuming `RemoteAcpServer::shutdown` cancels that token before the
active controller, then aborts and awaits every accept task; an upgrade whose
Expand Down
Loading
Loading