Skip to content

Latest commit

 

History

History
397 lines (309 loc) · 25 KB

session-supervisor.adoc

File metadata and controls

397 lines (309 loc) · 25 KB

Identity-keyed daemons: many sessions on one machine, and the road to a server

Abstract

CALYPSO now supports several personal daemons on one machine — one engine and one CUBE identity per daemon, with many surfaces sharing each isolated session. An operator can hold two logins, or two trusted operators can share a box, each driven by the same chell --daemon <user>@<url> they already type. It does this without touching the engine: calypso process is the isolation boundary, and multiplicity is a matter of keying berths by identity and resolving them behind one interface.

The design is deliberately staged in two tiers that share one seam:

  • Tier 1 (shipped). Local, identity-keyed berths. No new package, no new network surface, no new auth — edits to calypso’s discovery and chell’s remote client. It shipped with full value for the many-identities-on-one-box job.

  • Tier 2 (future, gated on the web surface). A reachable porter — a new package: a server/dispatch front that many clients on many machines attach to, with auth at the door. Not built now; noted so tier 1 leaves the door open.

The one thing tier 1 had to get right so tier 2 needs no rework was the berth resolver seam.

1. The two jobs (they are different)

It is easy to conflate these; they are not the same job, and only the first is on the table.

Job Covered by Reach

Several CUBE identities, one machine, one OS user

Tier 1

Local berth files, 0600, same host

Different humans, different machines, a browser that cannot run a local engine

Tier 2 (porter)

Network listener + auth (the server)

Tier 1 fully solves job one. It cannot reach job two — no network listener, no cross-host auth. Tier 2 is not "more of tier 1"; it is a different perimeter. Build tier 2 only when the web surface (argus, the surfaces model) forces it.

1.1. Attaching across hosts without tier 2

CALYPSO_BIND opens the wire to the network for a demo on a trusted network, and the attach token still gates every session. But discovery stays local: a berth is a file in one host’s runtime directory, so a surface on another machine has none to read. For a while that meant the wire was reachable and nothing could tell a remote chell where to point — the browser could attach and a terminal could not, which is a topology accident rather than a policy.

An explicit address closes that without a listener or a directory service:

chell --remote --attach http://pangea:41234/?token=abc123

The address accepted is the one calypso prints. The web surface and the wire share a port, so the ARGUS link names both, and pasting it is the whole interaction; --token supplies the token separately where an address carries none. The berth this builds is constructed in memory and never written, because nothing about another machine’s daemon belongs in this machine’s berth directory.

This is not tier 2. There is no listener beyond the one CALYPSO_BIND already opened, no cross-host auth beyond the attach token, and no way to discover a daemon you were not told about. It removes an accident; the perimeter is unchanged.

2. The invariant: the process is the isolation boundary

Multiplicity costs almost nothing because chell --daemon hosts a brasa engine in its own process, and a brasa engine encapsulates one whole single-user world — one chrisConnection, one session (cwd, context), one ProcCache. Two identities means two chell --daemon processes; the OS gives the isolation for free.

Important

Because every identity is a separate OS process, module-level state in brasa/cumin/salsa (the sink set by sink_set, the surface set by surface_set, any ProcCache or connection singleton) is per process — it physically cannot cross-wire between identities. This holds in tier 2 as well: the porter spawns one calypso child process per identity and hosts no engine itself. Process-per-identity is the isolation mechanism in both tiers; there is no shared-state engine to design and no request-time identity to thread through the engine.

3. User perspective

Unchanged verbs; the identity becomes the key.

# two identities (two logins, or two operators sharing a box) on the same host
chell --daemon me@https://cube.example.org/api/v1/ -p <pwd>       # my daemon (foreground)
chell --daemon them@https://cube.example.org/api/v1/ -p <pwd>     # their daemon (foreground)
# → two calypso daemons, fully isolated. Neither sees the other's session.

# attach later, by identity
chell --remote me@https://cube.example.org/api/v1/               # finds MY daemon
chell --remote                                                    # sole berth attaches; picker if several

The identity string <user>@<url> is the key everything routes on.

4. Tier 1: identity-keyed berths

4.1. Before tier 1

The original packages/calypso/src/daemon/discovery.ts recorded one berth in one file keyed by OS user only:

interface Discovery { url: string; token: string }
// legacy path: ${tmpdir}/chell-calypso-${username}.json   ← one per OS user

launch.ts called discovery_write({ url, token }); the chell remote client called discovery_read(). Exactly one daemon could advertise per OS user — the single-session assumption, made physical. This is retained as the before-state; current discovery uses the identity-keyed berth described below.

4.2. The berth

Key the berth by identity, and store the full identity inside it so a resolve can verify an exact match (never route on a hash alone).

interface Berth {
  identity: string;   // full "<user>@<cubeUrl>", stored for exact-match verify + list display
  url: string;        // the daemon's WebSocket address (ws://127.0.0.1:<port>)
  token: string;      // the attach token (liveness/handshake; see trust boundary)
}

Identity normalisation (lexical only, no I/O). The berth key is a hash of a normalised identity:

  • lowercase the URL scheme and host (HTTP://Ekanite → http://ekanite);

  • keep the trailing slash — CUBE requires it;

  • keep the port exactly as written; do not infer default ports;

  • keep the user’s case exactly — CUBE usernames may be case-sensitive.

Note

Normalisation is lexical only. http://ekanite:3223/api/v1/ and http://ekanite.tch.harvard.edu:3223/api/v1/ are treated as different identities, because merging them is DNS resolution, not string rewriting — and a berth key that depends on DNS breaks under load balancers, IP churn, and split-horizon DNS. The identity is the connection coordinate you typed, not the physical CUBE behind it. Rule: same string, same daemon. Operators should adopt one canonical URL per CUBE by convention; list() shows each berth’s full identity so any accidental duplicate is visible, never silent.

function identity_normalise(user: string, cubeUrl: string): string; // lexical rules above
function berthKey_compute(identity: string): string;                // sha256(identity), short hex

4.3. Where berths live

A berth is runtime state holding a secret, so it belongs in the runtime directory, not a shared folder, and in a folder only its owner can use:

$XDG_RUNTIME_DIR/calypso/berth-<berthKey>.json     # dir 0700, files 0600
<tmpdir>/calypso-<uid>/berth-<berthKey>.json        # no runtime directory: this account's own name
  • $XDG_RUNTIME_DIR (Linux /run/user/UID, 0700 tmpfs) is used when set: it is per-user and cleared at logout.

  • Without it the folder is tmpdir()/calypso-<uid>, so no other account can hold the name for everyone.

  • The folder is held before every use (fond ownFolder_settle): a real directory of this uid with no group or other bits, reached through a trusted path. The path is walked as spelled from /: every folder on it root’s or this uid’s and not open to others (unless root’s and sticky, as /tmp is), and a link is followed only from such a folder, its target walked the same way (trustedPath_resolve). A reader never makes it; a writer makes it 0700.

  • A record is read only as a regular 0600 file of this uid, opened without following a link and bounded in size (ownFile_read); it is written as a fresh 0600 file renamed over its name (ownFile_write), so a link planted at the name is refused and left as it is, never written through. A refused folder or record is skipped with one line naming its path and why.

  • list() reads berth-*.json in that folder and in each porter session’s runtime folder.

  • The attach note (attach.txt) and a host’s closing note sit in the same folder under the same rules. The note outlives its daemon, so it holds no credential: who the daemon was, when, and that calypso --berths gives the address and token of each daemon that proves it is running.

  • Every later read or write names the folder’s resolved path (ownFolder_settle returns it); only a missing folder or record is absence, any other failure is said.

No process removes a berth record or the attach note. Node has no lock a crash releases, so no remover can be sure the file it checked is still the one it would unlink: a daemon’s next launch for the same identity replaces the record by rename, and a reader treats a record whose daemon does not prove itself as absent (see liveness). One record per identity, so they do not accumulate. A daemon of an earlier release, which wrote into a shared tmpdir()/calypso, is not found there: restart it once.

4.4. The resolver seam

Important

Put all berth lookup behind one interface from day one:

interface BerthResolver {
  resolve(identity: string): Promise<Berth | null>;   // find a live berth for one identity
  list(): Promise<Berth[]>;                            // live berths, for bare --remote + picker
}

Tier 1 uses a LocalBerthResolver that reads the identity-keyed files. Tier 2 would supply a PorterBerthResolver that asks the porter over the network. The surface code (--remote, --daemon) depends only on BerthResolver and never learns which backs it. The interface lives in calypso (chell already imports calypso; a tier-2 porter would import calypso to spawn it) — no new shared package, no cycle.

If tier 1 instead hard-codes "berth = local file" at the call sites, tier 2 is a rewrite. With the seam, tier 2 is a new implementation of an existing interface — additive, no surface rework.

4.5. Liveness: a berth file is a claim, not a guarantee

A berth file can outlive its daemon (crash, reboot), and its port can since be another program’s, another account’s among them. A record is believed only when the instance that wrote it answers:

  1. A key per launch. Each launch writes a fresh random probeKey (32 bytes) into its private record beside identity, pid and booted.

  2. A challenge with no secret. A probe is GET /instance?nonce=<64 lowercase hex> (anything else is 400). The daemon answers { proof }, HMAC-SHA256 under the key over calypso-instance-v1, the nonce, the identity, the pid and the boot time, one per line. The verifier, holding the record, computes the proof itself and compares in constant time. Neither the attach token, the key nor the identity travels, and a proof for another nonce or from another instance (another key, pid or boot) fails.

  3. An earlier release’s record carries no key and cannot prove itself. Only a refused connection means it is gone; an address that accepts, a timeout or a name that does not resolve leaves it unverified: never grounds to start beside it, adopt it or attach to it. calypso --berths lists it as unverified (earlier release), a start for its identity refuses with "Stop the old daemon from its original terminal (Ctrl-C at the idle daemon prompt) or through its service manager, then retry.", and porter neither adopts it nor starts beside it, and says so in its log.

  4. What the proof covers. It proves which instance answered at the moment of the probe. The attach that follows is a separate connection, authenticated by the attach token alone: should the daemon end and another program take its port in the moment between the probe and the attach, the token would go to that program. The window is the time between two local calls; closing it needs the attach itself to carry the challenge, which the wire does not yet do.

  5. Every candidate probed. The resolver walks an identity’s records in order (this runtime’s, then each porter session’s) and probes each before one is chosen, so a dead record never hides a live one behind it. Nothing is removed.

4.6. --daemon: find-or-host (foreground) with a duplicate guard

chell --daemon <user>@<url> hosts in the foreground exactly as today (that terminal becomes calypso). The only new behaviour is a guard: before hosting, it resolves the identity’s berth and probes it. If a live daemon already exists for that identity, it prints where to find it and exits rather than starting a split-brain second daemon (an unverified one, of an earlier release, is refused the same way, with how to stop it):

daemon for me@https://cube.example.org/api/v1/ already running at ws://127.0.0.1:54321
attach with:  chell --remote me@https://cube.example.org/api/v1/

Otherwise it hosts and writes the identity-keyed berth. (Detached/background start is a later ergonomic follow-up; it changes how the process starts, not the berth semantics, so deferring it costs nothing.) The standalone calypso binary likewise writes an identity-keyed berth from the session it restores.

On a terminal, the boot ends at a login. Once the daemon is listening, chell --daemon puts an ordinary chell --remote --attach <url> --token <token> surface on its own terminal, as a child process on the wire: the same hop every other surface pays, and no share of the daemon’s in-process sink or surface. exit detaches and leaves the daemon running with its terminal idle; Enter attaches again; Ctrl-C at the idle terminal stops the daemon. Whatever the daemon writes to its terminal while a surface holds it is held and printed on detach, so it never lands across the surface’s prompt. Off a TTY nothing attaches. The design record is in the ARGUS AEGIS document, The daemon console.

4.7. --remote: resolve by identity, pick on ambiguity

Invocation Behaviour

chell --remote <user>@<url>

Resolve that identity’s berth directly; never a menu.

chell --remote — no live berth

Error: no daemon running.

chell --remote — one live berth

Attach directly (do not menu a single choice).

chell --remote — several, TTY

Interactive picker over list(); choose identity, attach.

chell --remote — several, non-TTY

Error + list; the caller must be explicit.

There is no backwards-compatibility burden: the picker only triggers on bare --remote with several live berths, and non-interactive callers simply pass the identity.

4.8. Trust boundary

Tier 1’s trust boundary is the OS user. Berth files are 0600 inside a 0700 runtime directory, so another Unix user cannot read a token or reach a calypso session (loopback-bound). Within one OS login, all of that user’s own berths are mutually readable — which is correct: anyone sharing your OS login already holds your ssh keys and saved CUBE session; the attach token is a liveness/handshake token, not a defence against your own account. Walling two humans apart is precisely tier-2 porter’s job (auth at the door). Two humans who must not see each other today use two OS logins; filesystem permissions isolate them.

4.9. Host control (--host-control)

Capabilities are declared, never detected. A surface declares on attach what it can do on its own machine — run a ! shell command, run a pipe segment, receive a file, open an editor — and calypso relays each of those to the surface that typed the command, never running anything on its own host. That is the default, and it is right for a calypso session on a server nobody is sitting at.

chell --daemon --host-control lets the HOST declare too: the AI-harness permission model applied to the session daemon. The operator who starts the daemon decides what it may do on the machine it runs on. Tiers: shell (!cmd runs on the daemon host, in the daemon’s own working directory: for a surface that is a terminal, on a pseudo-terminal of the daemon’s own, see below; for any other, sh -c with stdin closed and output on the session bus like any command), files (upload reads and download writes the daemon host’s disk), pipes (ls | grep x runs the segment on the daemon host), tasks (the engine may start long jobs through the core’s runner, kill and wait them: on a substrate daemon, jobs that change a cloud and bill; docs/stratus.adoc, D10). Bare, and all, mean the first three: tasks reaches beyond this host into money, so it is only ever named (--host-control tasks, or shell,tasks). CALYPSO_HOST_CONTROL is the env twin. Under the policy the host always wins — one ! means one machine, even from a remote shell that could run it itself.

A ! under the shell tier has a terminal when the surface that typed it is one. A browser’s terminal is a chell on the daemon host, which runs the command in its own pty. A remote chell whose input and output are both a terminal (ssh, berth-enter, a laptop) declares tty on attach, its terminal type and size; the daemon runs the command under sh -c on a pty of that size with TERM from it, sends the program’s bytes to that surface alone (hostPtyStart, hostPtyData, hostPtyExit), and takes back its keys raw and its window sizes (hostPtyInput, hostPtyResize). The chell sets its line editor aside and puts its terminal in raw mode until the program ends, so !nvim notes.txt draws, edits and quits back to the chell prompt; Ctrl-C goes to the program; Ctrl-Z and a program’s own suspend (:suspend) stop nothing, since the program’s process group has no parent in its session and job-control stops do nothing there, so no program can stop and hold the session; the line ends with the program’s exit status; a surface that goes away hangs the program up. A surface with no terminal gets pipes, and a program that would wait forever there (Neovim with no terminal on any descriptor starts with no user interface and waits for one to attach) is refused by name rather than left holding the session.

Without the files tier, upload refuses under a calypso session (calypso host’s disk is nobody’s), as download has always refused to write there. Every surface is told: the attach ack carries hostControl, calypso’s face shows HOST CONTROL: SHELL FILES PIPES, the prompt wears an amber HOST segment, argus lights an amber HOST lamp, and a remote shell prints a banner on attach.

The guard: on loopback the policy adds nothing an attacker did not have (the port is reachable only from the host, the attach file is mode 0600). On a non-loopback CALYPSO_BIND the attach token — a bearer secret in a URL — becomes a shell on the host for anyone holding it, so that combination refuses at launch unless --expose-host-control is typed as well, and then the boot log and the face say HOST CONTROL EXPOSED ON <bind> in the alert color, every launch.

5. Tier 2: the porter (future, gated on the web surface)

When a browser surface must attach — it cannot spawn a local engine — a reachable front is required. porter is a thin new package: a registry + a spawner + an auth gate. It is not an engine, and it hosts none; it spawns one calypso child process per identity, exactly as tier 1’s isolation model requires.

surface ──handshake(user@url, cube-token)──▶ porter
                                             │ validate token via CUBE whoami   (ride CUBE as IdP)
                                             │ find-or-spawn calypso child for identity
                                             │ registry: identity → { addr, token, pid }
              ◀──── berth (addr + attach token) ┘
surface ─────────────attach WS─────────────▶ calypso  (that identity's child daemon)

What tier 2 adds on top of tier 1 (all additive):

  • Auth at the door. Ride CUBE as the identity provider — validate a presented CUBE token via whoami, bind a berth to it, honour CUBE’s TTL. The porter holds live tokens, never passwords, and invents no parallel user database.

  • Network perimeter. TLS on the wire; per-identity attach tokens minted after auth (the single-host 0600 perimeter does not survive network exposure); per-session event/progress topics so one identity never sees another’s job bars.

  • Lifecycle. Idle-daemon eviction, token-expiry reaping, crash restart — the porter owns the fleet.

The first seam tier 2 needed is in: the door hands a token. A session can now be started with a CUBE token rather than a password — cumin connection_connectWithToken, brasa sessionWithToken_connect, and chell --daemon <user>@<url> --auth-token-stdin, which reads the token from stdin (one line, never argv, where ps would show it) and refuses by name when it arrives without an identity, beside a password, or not at all. The token is proved against the server before anything is written, so a refused login changes nothing on disk. Off a TTY the daemon no longer tries to end its boot at a console, because a front holding its pipe is not a terminal; it says so and keeps listening. The porter’s spawn is therefore: exchange the password at CUBE, spawn chell --daemon with per-identity XDG directories, write the token to its stdin, watch its stdout for the boot rows.

What tier 2 reuses unchanged: the calypso daemon, the engine, the Berth concept (addr + attach token), the <user>@<url> identity key, and — through the resolver seam — the surface’s attach path (PorterBerthResolver replaces LocalBerthResolver).

5.1. Cloud persistence posture

CUBE remains the durable state authority. Calypso’s /proc checkpoint is a restart accelerator, not workflow truth: losing it causes a cold topology sweep against CUBE but does not lose feeds, jobs, outputs, or provenance. This makes a container filesystem sufficient for the first cloud deployment.

Storage Behaviour Recommendation

Ephemeral container filesystem

Correct after restart, with a cold CUBE rebuild and additional startup load.

Acceptable for an initial deployment while restart time and CUBE load are measured.

Per-daemon persistent volume

Retains the identity-keyed checkpoint across pod restarts and preserves the current atomic-rename semantics.

Preferred first production shape: one daemon writer per identity on an encrypted volume.

Shared read/write filesystem

Permits competing daemons to overwrite one checkpoint; the current file adapter has no distributed lock or compare-and-swap.

Do not share one identity’s checkpoint between writers. Enforce an exactly-one-daemon lease first.

Database

Makes a disposable snapshot shared but does not solve daemon ownership, WebSocket routing, resumable commands, or active-session failover.

Do not introduce MongoDB for /proc alone.

If node-portable checkpoints become operationally necessary, the natural second adapter is blob/object storage: the checkpoint is a roster plus per-feed JSON shards loaded and saved by identity, not a query workload. Add a small checkpoint-store seam when that second adapter is built; do not layer it over the current file writer in advance. Distributed concerns remain separate: porter supplies authentication and routing, while Redis, PostgreSQL, or Kubernetes Lease objects can supply registry and exactly-one-daemon coordination if multiple porter replicas require it.

The trigger for more machinery is an observed service objective: cold rebuilds overload CUBE, pod rescheduling cannot reattach volumes quickly enough, or cross-node/cross-region recovery must retain a warm checkpoint. Seamless recovery of in-flight commands is a different session/event-persistence problem and must not be inferred from durable /proc cache storage.

6. Scope and staging

Stage Content

Tier 1 (shipped)

Identity-keyed Berth + lexical normalisation; BerthResolver
LocalBerthResolver (owner-only berth folder, instance-proof liveness, nothing removed); --daemon foreground duplicate-guard; --remote <id>@<url> resolution with picker/non-TTY fallback; standalone calypso writes an identity-keyed berth. No new package — edits to calypso discovery + chell remote client.

Tier 2

porter package: PorterBerthResolver, auth-at-door (CUBE IdP), TLS
per-identity tokens, per-session topics, lifecycle. Built only when the web surface lands.

7. See also