<!-- source: https://cli.dreamlake.ai/sessions/control @ 0.134.0 99837ab -->

# Session control plane

This unreleased source change adds a control plane for agent sessions. A **command**
is a durable intent stored by dreamlake-server ("send this text to that
session", "start Claude in a worktree of this repo"). A **runner**,
`dl sessions serve`, is a process on your own machine that claims
commands under a lease, executes them with the Codex or Claude CLI and posts
one receipt. The server never executes anything and never reaches into the
machine; the runner only talks outwards with your token.

The same commands are exposed three ways with identical permissions, inputs
and error codes: the `dl sessions control` CLI, the TypeScript API
(`@dreamlake/dreamlake-cli/api`, see [TypeScript API](/dev/typescript-api.md))
and the built-in agent's tools (`dreamlake_session_*`), which call the same
HTTP routes as the signed-in user.

## Runner

```bash cli-help="sessions serve"
dl sessions serve
# Handle one command and exit (useful in scripts and tests):
dl sessions serve --once --json
# Let a person raise sessions on this runner up to full access (control restart --raise):
dl sessions serve --max-human-permission full-access
```

The runner registers itself under your personal namespace with a stable key
kept in `~/.dreamlake/session-runner.json` (not a credential). With `tmux` on
the machine it starts sessions as detached tmux sessions (named like the
DreamLake terminal gateway's, and marked with this runner's ownership); attach
to one locally with `tmux attach -t <name>`. Attaching through the browser
terminal or `dl sessions open` still requires an enrolled host and a
gateway-saved descriptor; a runner-started session is registered as metadata
only. Without tmux it runs **headless**: `start` and `send` execute one
provider turn (`claude -p`, `codex exec`) and the receipt carries the reply.

Claude Code keeps its login in `<config dir>/.claude.json`, and the default
profile is `~/.claude.json`, not `~/.claude/.claude.json`. A session whose
recorded `claudeConfigDir` is the runner's default directory (what Nymph
records for an ordinary session) therefore runs **without** `CLAUDE_CONFIG_DIR`
exported; exporting it made Claude create an empty profile and answer "Not
logged in". The variable is exported only for a different directory that is
the user's own — owned by the runner's Unix user, or inside its home, judged
on the path with symlinks resolved; a session descriptor can name any readable
path, and another user's profile is not this user's login — and whose
`.claude.json` holds a login: a non-empty
`oauthAccount` or a non-empty `primaryApiKey`. Anything else runs without the
variable. Every receipt of a Claude turn says what was done:
`claudeConfig: { dir, exported, reason }` with `reason` one of `inherited` (no
directory recorded), `default_config_dir`, `profile_missing`,
`profile_not_owned`, `profile_logged_out` or `exported`.

Prompts and messages reach a provider on stdin, or behind a `--` boundary
for an interactive launch, never as an argument that could parse as an
option. The permission level recorded at `start` is re-applied to every later
provider process (`resume`, headless `send`); a session without a recorded
level needs `--permission` on those commands. A headless `send` is refused
(`native_session_active`) while another process wrote the conversation in
the last minute. The runner's own previous turn is not another process: it
remembers the exact transcript state each of its turns left behind, per
native session id, and only a change made since then counts as a writer. The
check runs again once the turn holds a provider slot, and a turn whose
provider never ran (cancelled while queued, refused, or the CLI did not
start) remembers nothing, so a write made meanwhile stays another process's.

```bash cli-help="sessions runners"
dl sessions runners
```

Lifecycle commands are routed to an explicit `--runner`, to the runner that
started the session, or to the single online runner; with none or several
online the command is refused (`session_runner_offline`,
`session_runner_ambiguous`) rather than queued blindly. A runner is online
while it keeps claiming and renewing. On Ctrl-C, SIGTERM, `--once` or a fatal
error it abandons its long poll, posts the receipts of commands in flight and
then deregisters itself (`DELETE /namespaces/:ns/session-runners/:id`,
`sessions(ns).runners.deregister`) so it is listed offline at once. A server
without that route answers 404; the runner logs it and the server lists it
offline once its 90 s heartbeat window passes.

## Commands and receipts

Every command moves through `pending → running → completed | failed`, or
`cancelled` (owner, while pending) or `uncertain`: the runner stopped renewing
its lease, the command was interrupted, or a side effect may have started
before a failure (for example the agent process exists but registration was
refused). An uncertain receipt carries a `result.checkpoint` with what is
known (native session id, tmux session, working directory) and must be
inspected, never retried blindly. A failed or uncertain receipt also carries
`result.error`: the runner's error code and message, and for a provider that
ran, its exit code, signal and bounded, credential-redacted stderr/stdout
tails (`stderrTail`, `stdoutTail`), so "Not logged in" or a stack trace is
readable from `sessions control list` instead of a bare `claude_failed`. The
top-level `error` stays the short code callers branch on. `--wait` polls for
the receipt; `--wait 0` returns the pending command for later
`sessions control wait`.

```bash cli-help="sessions control start"
dl sessions control start --provider claude --repo /abs/repo --isolation worktree --branch feat/x --permission workspace-write --prompt "Run the tests and report" --name "Test runner"
# Reuse the checkout as is, headless:
dl sessions control start --provider codex --repo /abs/repo --isolation repo --permission read-only --mode headless --prompt "Summarize open TODOs"
```

A Codex session's identity is only known from its own launch (`codex exec
--json` reports the thread id), so an interactive Codex start runs one
headless first turn with the prompt and then resumes that thread in tmux;
Claude sessions start directly with a chosen session id. The runner never
guesses an identity from transcripts that appear in the directory.

`--isolation worktree` creates `~/.dreamlake/worktrees/<repo>-<branch>` with
`git worktree add`; `repo` uses the checkout as is. A start that fails or is
cancelled before its session exists removes the worktree it created and the
branch it created for it, and only those: once `git worktree add` returns, the
runner writes this creation's identity into the worktree's git admin directory
(`dreamlake-session`) and records the branch's tip, and it removes the
worktree only while it carries exactly that identity, checked out on that
branch at that tip. Removal is never `--force`, so a worktree the provider
edited is kept; a branch the provider committed to is kept with its worktree;
a worktree moved away, replaced or re-created at the same path is not touched;
a worktree whose `git worktree add` was itself cancelled or timed out has no
identity yet and is kept (`identity_missing`), its path in the checkpoint;
the branch is deleted only if it still points where it started and no worktree
has it checked out. The receipt's `checkpoint.worktree` reports `removed`,
`branchDeleted` and, for anything kept, the `reason`. A worktree is also kept
when a tmux teardown could not be verified (a process may still run there) or
when the agent process exists and only its registration failed
(`registration_failed`; the checkpoint carries the native session id and cwd
to register by hand). `pod` is part of the
contract and requires explicit `sessions serve --pod-config /abs/config.json`.
Without that configuration it returns `pod_not_configured`; pod mode is headless only. `--permission` maps to `claude --permission-mode`
(`plan`, `acceptEdits`, `bypassPermissions`) and `codex --sandbox`
(`read-only`, `workspace-write`, `danger-full-access`).

```bash cli-help="sessions control send"
dl sessions control send <session-id> "Please rebase on main and rerun CI"
# A turn under a lower ceiling than the recorded level, for this turn only:
dl sessions control send <session-id> "Summarize your state" --permission read-only
# A session registered without a level (sessions register, dl claude) is refused until one is recorded:
dl sessions control restart <session-id> --permission workspace-write --raise
```

A session that was registered rather than started by a runner has **no
recorded permission level**, and a runner refuses every turn for it
(`permission_level_unknown`) — `--permission` on `send` or `resume` only ever
lowers a recorded level for one turn, it never supplies a missing one. Record
it once with `control restart --permission <level> --raise` (the person
confirms on a terminal; the runner must have been started with
`--max-human-permission <level>`), then `send` plainly.

A runner executes one turn per session at a time; a second `send` while one
is running is refused (`session_busy`), and a provider that exits with an
error after running is reported `uncertain` (it may have edited files).

```bash cli-help="sessions control broadcast"
dl sessions control broadcast "Stop and summarize your state" --session <id-1> <id-2>
```

```bash cli-help="sessions control resume"
dl sessions control resume <session-id> --prompt "Continue"
```

```bash cli-help="sessions control restart"
# Lower a session to read-only and continue the same conversation:
dl sessions control restart <session-id> --permission read-only
# Raising is the person's explicit ask; the runner must have been started with --max-human-permission:
dl sessions control restart <session-id> --permission full-access --raise --reason "needs to run the deploy"
```

`restart` is the one sanctioned way to change a session's permission level:
the runner stops the session's process (the tmux session it owns, the
headless turn it is executing) and resumes the same native conversation under
the new level, which becomes the level recorded for every later turn. The
levels are ordered `read-only` < `workspace-write` < `full-access`. Lowering
always passes. **Raising** needs `--raise` and, on a terminal, a typed
confirmation: the server cannot tell a token holder from a person, so the CLI
asks the person and only then sends `raise: true`; without a terminal nobody
can be asked, so the raise is refused (exit 1): a script or an agent holding
the token cannot widen a session on its own. The raise must also stay within the
executing runner's **human cap**, `sessions serve --max-human-permission
<level>` (advertised as `capabilities.humanPermissionCap`, shown by
`sessions runners`); a runner without one allows no raise
(`session_permission_cap`). A session with no recorded level treats any level
as a raise. The built-in agent never raises (`agent_permission_ceiling`), and
a child session never passes its parent's level (`parent_permission_ceiling`;
`parent_permission_changed` when the parent moved meanwhile). A pod session
cannot change policy in place (`pod_restart_unsupported`): start a new one at
the wanted level. The receipt carries `permissionLevel`,
`previousPermissionLevel`, `stopped` (interrupted turns, tmux stopped) and
`argv`, the exact command line the runner ran, so the provider's permission
mode is readable next to the level that was authorized. A headless restart
without `--prompt` relaunches nothing (`executed: false`): the record moves
and the next headless turn runs under it. The server records the level it
validated at submission, never the one the runner echoes; a disagreement is
kept as `observedPermissionLevel` and a `permission_mismatch` history entry,
and `result.effectivePermissionLevel` says what the session is authorized at
when the receipt lands (a raise revoked while the command was queued is not
applied). Every receipt of a turn (`start`, `resume`, `send`, `restart`)
echoes its `argv`; a tmux resume into a live session reports `argv: null`.

```bash cli-help="sessions permission"
dl sessions permission <session-id> read-only --reason "review only"
```

`permission` moves the recorded level **without** a runner round-trip
(`PATCH …/permission`, `sessions(ns).permission`). Only the record moves: the
running process keeps its level until the next `resume`, `send` or `restart`
re-applies it, and the output says so when the runner last ran under a
different level. The runner records the level every tmux process was launched
under (`@dreamlake_policy`) and never types into a live process whose launch
level is not the authorized one: a `send` or `resume` into such a process
stops it and relaunches it under the record first (receipt `relaunched: true`,
`previousProcessLevel`), and a process whose launch level was never recorded
(started by an older runner) is refused with
`permission_unverified_restart_required` until `control restart` relaunches
it. The raise rule is the same as `restart`'s, with the cap taken
from the session's bound runner, else the owner's single online runner.
`permissionHistory` (origin `token` for the CLI and scripts, `agent` for the
built-in agent, `runner` only on a mismatch entry; oldest first, last 50),
`observedPermissionLevel` and `permissionChangedAt` are visible to the owner
on the session descriptor.

```bash cli-help="sessions control stop"
dl sessions control stop <session-id> --yes
```

`stop` ends the runner-owned tmux session and interrupts any headless turn
the runner is executing for that session, reporting only after the process
has ended (`stop_unverified`, uncertain, if it does not within the wait); it
reports `stopped: false` when nothing of this session was running on that
runner.

```bash cli-help="sessions control status"
dl sessions control status <session-id>
dl sessions control sync <session-id>
dl sessions control subagents <session-id>
```

`status` reports a heuristic run state from the transcript tail and process
liveness: an alive session whose last message is the assistant's and that has
been quiet is `waiting` (needs a human). `sync` uploads the current transcript
through the existing conversation API with a revision check. `subagents` lists
the subagents a Claude session spawned, from its project directory; Codex
records none on disk.

```bash cli-help="sessions control list"
dl sessions control list --session <session-id>
dl sessions control wait <command-id> --wait 120
dl sessions control cancel <command-id>
```

## Live state and subagent events

```bash cli-help="sessions heartbeat"
# From a Claude Code hook (settings.json): the hook JSON on stdin names the session and the tool.
dl sessions heartbeat --state running --hook-stdin
# From a script or another relay, for an explicit saved session:
dl sessions heartbeat --session <session-id> --state waiting-for-user --tool Bash
```

```bash cli-help="sessions event"
dl sessions event --kind SubagentStart --hook-stdin
dl sessions event --session <session-id> --kind SubagentStop --subagent agent-abc --finished --tokens 1200
```

`heartbeat` posts what a session is doing **now** to
`POST /namespaces/:ns/terminal-sessions/:id/heartbeat` (`sessions(ns).heartbeat`):
a `liveState` of `starting`, `running`, `waiting-for-user`, `idle`, `stopped`
or `uncertain`, with the current tool (at most 128 characters) and the start
of the prompt (`promptHead`, at most 200 characters, collapsed to one line,
redacted by the server and visible to the owner only). The CLI truncates to
those bounds, sends exactly one request with a 5 s timeout, prints the receipt
**without** the prompt head (JSON shows `promptHeadChars`) and exits 1, never
2, on failure, so a relay can never block the tool call it reports on. `event`
posts a native subagent's `SubagentStart` / `SubagentStop` to `…/:id/events`
(`sessions(ns).event`); one child row per session and `subagentId`
(`^[A-Za-z0-9._:-]{1,128}$`), merged so a late or replayed event never
overwrites a newer one. `--finished` defaults to `--at`; `--tokens` is a total.

Who the relay speaks for is decided by trusted evidence, never by a lookup
and never by the payload: `--session <id>` (with `--namespace`); else the
native identity the provider itself set in the environment
(`CLAUDE_CODE_SESSION_ID` for Claude Code hooks and tools, `CODEX_THREAD_ID`
for Codex; an explicit `CLAUDE_SESSION_ID` wins), resolved through the env
file `sessions register --write-env` wrote at
`~/.dreamlake/sessions/<native-uuid>.env`; else the sourced
`DREAMLAKE_TERMINAL_SESSION_ID` / `DREAMLAKE_SESSION_NAMESPACE` pair. An
unregistered native session is an error that names the registration to run.
`--hook-stdin` reads a Claude Code hook's JSON from stdin and uses only
`tool_name`, `prompt`, `agent_id` and `agent_type` (never tool input,
responses or paths) to fill the flags not given explicitly; its `session_id`
is checked against the environment's identity and a disagreement is refused
(exit 1, nothing sent). Ready-to-copy `settings.json` hooks are on
[Claude Code hooks for live state](/dev/claude-code-hooks.md).

```bash cli-help="sessions tree"
dl sessions tree <session-id>
```

`tree` reads `GET …/:id/tree` (`sessions(ns).tree`): the session, its managed
children (`control start --parent`, breadth-first, depth ≤ 3, ≤ 200 nodes)
and, under each, the native subagents its hooks reported. A session node
shows live state and current tool, permission level, isolation (what the
runner recorded at start: `repo`, `worktree` + branch, `pod`; the working
directory for sessions registered by Nymph or started before isolation was
recorded), runner and finish time; a subagent node (`↳`) its state, token
total, last event and finish time. The last line counts nodes and says
`truncated` when a bound was hit and when a looping parent link was cut.

```bash cli-help="sessions watch"
# One session, readable lines:
dl sessions watch --session <session-id>
# Everything in the namespace, one JSON frame per line:
dl sessions watch --json
```

`watch` follows `GET …/terminal-sessions/watch` (SSE, `sessions(ns).watch`)
and prints each frame as it arrives: `ready` (what is watched, from when),
`liveState` / `heartbeat` (state, source, tool, prompt head), `subagent`,
`receipt` (a control command reaching a final status, with its level and the
`argv` a restart ran) and `permission` (a recorded level change with its
origin). Frames are batched by the server (2 s of quiet or 5 s at most) and
the lapse into `uncertain` 60 s after the last active beat arrives as a
`liveState` frame of its own. There is **no catch-up**: the stream carries
exactly what happens after `ready.at`; re-read `sessions list` and `sessions
tree` after it ends. The server ends every stream after 15 minutes with an
`end` frame and `watch` exits 0 — reconnect in a loop; Ctrl-C also exits 0. A
stream that closes without `end` (network, server restart) exits 1 with a
memo; a stream `error` frame (`access_expired`, `access_unavailable`,
`session_watch_unavailable`) is printed and exits 1. `--json` writes NDJSON,
one `{"type": …}` object per line, keepalive comments dropped.

Who is reporting follows from `--runner`: present, the beat comes from that
runner (`source: runner`; the session must be bound to it, else
`409 session_runner_mismatch`); absent, from the session's own hooks
(`source: hook`). `--source` may only agree. `dl sessions serve`
reports on its own: `running` every 10 s while it executes a headless turn
of a session, then `waiting-for-user` (the reply awaits a person), `stopped`
after a `stop` or a cancelled turn, `uncertain` after a provider failure,
`starting` after a tmux launch; a session the server does not let the runner
speak for is logged once and dropped until a `resume` or `restart` of it
completes there. A `starting` / `running` beat older than 60 s reads as
`uncertain` on every descriptor (`liveState`; `liveStateReported` keeps the
raw value); `waiting-for-user`, `idle` and `stopped` do not go stale. Beats
are monotonic on `--at`: an older one than the stored beat is not written and
the receipt says `accepted: false`.

## Rename and archive

```bash cli-help="sessions archive"
dl sessions rename <session-id> "Flaky test hunt"
dl sessions archive <session-id>
dl sessions unarchive <session-id>
```

Archiving hides a session from default listings; `sessions list --archived
include` or `--archived only` shows it. The conversation, links and
descriptor stay; no process is stopped.

## Built-in agent from the CLI

```bash cli-help="sessions chat"
dl sessions chat "Which of my sessions need attention?"
# Allow lifecycle and messaging tools this turn:
dl sessions chat --control "Send 'rebase on main' to the two Claude sessions working on notes"
```

```bash cli-help="sessions tool-calls"
dl sessions tool-calls <conversation-id>
```

`chat` runs one turn of the same harness the app's agent uses. Control tools
are offered only with `--control`, memo appends only with `--notes-write`;
every tool call leaves a durable receipt that `tool-calls` lists.

Interactive runner mode requires tmux 3.2 or newer. Commands that take a
window or pane target address the session's pane as `=name:`; tmux 3.5a cannot
resolve a bare `=name` for them when no client is attached, which made every
tmux resume fail with `tmux_mark_failed`. Each new session receives
an atomic launch nonce in its tmux session environment. If creation is
interrupted, cleanup checks that nonce and targets the exact session ID;
it never kills another session that reused the same name. A cancelled paste
or submit is reported as uncertain if text may have reached the provider.

## Explicit local pod configuration

The configuration pins `image` to a SHA-256 digest, lists exact absolute
`repositories`, and sets `network` (`none` or `bridge`), `cpus` (up to 16),
and `memoryMb` (128–32768). Optional `envFiles` maps `codex` or `claude` to
absolute private files. Credentials are never inherited from the service.
The image must include Node, the provider CLIs and a system CA certificate bundle, with a writable
`/home/agent` for UID 1000. Containers have a read-only root, no capabilities,
no host home/socket mount, and an independent home volume. Read-only policy
also makes the repository mount read-only. Native Claude plan mode alone
is not an OS sandbox.

## Cancellation, children and recovery

Cancelling a running command requests interruption. The runner reads the
command every 2 s while it executes, on a clock of its own (lease renewal,
every 10 s, also carries the cancel but a slow renewal never delays it), sends
the provider process SIGTERM at once and SIGKILL 5 s later, so a running
headless turn is dead within about 10 s; it does not assert that its effects
were undone.
Interrupted work is uncertain. A `send` typed into a tmux session has already
completed by the time it could be cancelled; interrupt that session with
`control stop` or a follow-up message.
`--parent <session-id>` records a managed child and enforces its parent's
recorded permission ceiling. `sessions children <session-id>` lists those
children; normal control commands operate on their IDs. Native provider
internal subagents remain inspection-only.

The runner fsyncs intent and checkpoints to private journal files before
execution. `sessions runner-journal` inspects them. On restart it uploads
late observations through `commands.reconcile`, and periodically rechecks active leases until they expire, without changing uncertain
to completed or replaying the command. Verified old pod/tmux executions are
stopped; unverified old processes quarantine new provider work. Preserve
these files until the old process outcome has been checked. A journal is
recovery evidence, not proof that an interrupted action never happened. A missing
runner identity stays quarantined; restore its state file or inspect and stop
the old execution first. After verifying that it stopped, an operator can run
`sessions runner-journal --acknowledge <command-id> --reason "verified stopped"`
to retain an audit reason and release that local quarantine. This does not replay
the command or change its server outcome.

For commands originating from the built-in agent, `sessions serve` trusts only
its current repository by default. Repeat `--allow-repo <absolute-path>` to
configure exact allowed repositories. `--max-agent-permission` defaults to
`workspace-write`; increasing it is an explicit operator decision. Send/resume
cannot exceed the session's recorded startup policy, and sessions with no
confirmed startup policy must be inspected before execution.

`sessions browser-actions <conversation-id>` reads durable browser receipts.
`sessions agent-projects`, `sessions project-search <project-id> <query>
--content`, and `sessions project-file <project-id> <file-id>` use the same
permission-checked project tools as the agent. Content search is paginated;
inspect `partial`, `skipped` and `nextCursor` even when a page has no matches.

`sessions tool-calls <conversation-id> --limit 50 --json` returns `toolCalls`
and `nextCursor`. Pass that opaque value with `--cursor` for the next page.

The opt-in `scripts/verify-native-session.ts` can verify a real provider against
a clean disposable repository. `scripts/acceptance/codex-pod.Dockerfile` pins a
Codex test image with system CA certificates: Node's bundled trust store alone
does not establish that native Codex can validate TLS. The script stops and
removes its test container/home after checking same-session resume; production
runner homes remain retained. No credentials belong in the image or repository.
