Skip to content

Node Internals

root edited this page Dec 4, 2026 · 5 revisions

Node Internals

🌐 English · 简体中文

This page documents the internals of the trizano-h3 Node daemon: dual-socket isolation, CLI subcommands, the Session actor model, terminal and SQLite storage layers, build replacement, and how SSH, WSL, and native Windows Nodes bootstrap and manage child processes. It is aimed at developers debugging or modifying Node-side code.

Daemon and Directory Layout

The Node daemon (server/cmd/trizano-h3/, server/node/) runs as a single-instance background process on every managed machine. State lives under ~/.trizano/node by default (overridable via --root), guarded by an exclusive file lock at run/node.lock so only one daemon can own a state directory at a time.

flowchart LR
    subgraph External["Callers"]
        Attach["trizano-h3 attach (local / SSH / WSL)"]
        Admin["trizano-h3 admin / stop"]
        Agent["Sandboxed agent CLI / MCP"]
        Entry["Remote Entry Hub (/nodes-connect)"]
    end

    subgraph Daemon["trizano-h3 serve daemon"]
        OwnerSock["Owner socket run/node.sock (0600, owner context)"]
        OrchSock["Agent socket orch/s.sock (0600)"]
        RevConn["Reverse connectors (outbound WS + inner mTLS)"]
        MainH["n.Handler(): 13 Node RPC services + /raw /media /attachments"]
        OrchH["n.OrchHandler(): POST /internal/orch/{method} only"]
        Subsys["Session actors · Terminals · Files/Review/Git · Ports/Browser · Telemetry/Rate limits"]
        DB["SQLite state.db (WAL)"]
    end

    Attach -->|"h2c"| OwnerSock
    Admin -->|"h2c"| OwnerSock
    OwnerSock --> MainH
    RevConn -->|"h2c (non-owner)"| MainH
    Entry <==>|"Reverse tunnel"| RevConn
    Agent -->|"h2c"| OrchSock
    OrchSock --> OrchH
    MainH --> Subsys
    OrchH --> Subsys
    Subsys --> DB
Loading

node.Layout (server/node/daemon.go) manages the following state directory layout:

Path (relative to --root) Purpose
run/node.sock Owner Unix socket (0600)
run/node.lock Exclusive file lock holding the current daemon PID; a starting daemon waits up to 10 seconds for a previous process to release it
run/tmux.sock Dedicated Node tmux server socket (used on Unix when tmux is available)
orch/s.sock Agent orchestration Unix socket (0600)
orch/trizano-h3 Atomically copied self-binary (0700, .exe on Windows) so sandboxed agents only need orch/ mounted
state.db SQLite state database (Workspaces, Sessions, timelines, tasks, Roster, review baselines, usage, etc.)
node.log stdout/stderr log file when StartDaemon spawns the daemon in the background
node_key.pem Long-term ECDSA P-256 Node identity private key (0600, held by every Node type)
entries.json Roster root public key and bootstrap Entry info for Reverse Nodes (automatically migrated from legacy hub.json on startup)
bin/<build>/ Immutable directory where SystemService.InstallBuild places new builds (on SSH Nodes, <remote-dir>/bin/<build>/)
attachments/ Uploaded chat and browser-annotation attachments
review/blobs/ Content-addressed file snapshots for review baselines
browser/profile/ Persistent profile directory for managed headless Chromium
scripts.json Node-wide shared project scripts manifest applied to every Workspace on this Node

On startup, the daemon also merges the login environment PATH (reading $PATH from an interactive login shell on Unix, or the system and user Path registry values on Windows) and writes the managed trizano-delegation skill into ~/.claude/skills and ~/.agents/skills.

Dual Unix Sockets and Privilege Isolation

The Node enforces a hard boundary between the owner/Entry management surface and the agent orchestration surface by serving them on separate Unix sockets with completely distinct HTTP handlers (server/node/daemon.go, server/node/node.go):

  • Owner socket run/node.sock (0600):
    • Mounts n.Handler(), exposing all 13 trizano.node.v1 Connect services plus /raw, /media, and /attachments.
    • Requests arriving on this socket carry an ownerKey context marker (withOwner). SystemService.Shutdown only accepts the owner socket; calls over a reverse connection or the orchestration socket fail with PermissionDenied.
    • When OpenControlBridge receives a BridgeHello for an Entry over the owner socket, the Node automatically pauses its reverse connector to that same Entry so duplicate connections are never maintained.
  • Agent socket orch/s.sock (0600):
    • Mounts n.OrchHandler(), exposing only POST /internal/orch/{method}—no trizano.node.v1 management or file endpoints are reachable here.
    • The Node injects TRIZANO_CLI (pointing to orch/trizano-h3) and TRIZANO_SOCKET (pointing to orch/s.sock) into agent subprocesses. Sandboxed agents only need orch/ mounted to run delegation and Discussion Room orchestration, and cannot reach run/node.sock to shut down the daemon or alter Node configuration.

Subcommands

trizano-h3 is a single multi-purpose binary whose subcommands are dispatched in server/cmd/trizano-h3/main.go:

Subcommand Flags and behavior
serve [--root DIR] Runs the daemon in the foreground, listening on both sockets and maintaining outbound reverse connectors according to entries.json and the Roster. --connect is accepted as a deprecated no-op so older service units continue to start. If Serve returns node.Restart{Exe}, main performs an in-place or detached binary switch.
join [--root DIR] [--title NAME] [--allow-insecure-http] <hub-url> Interactively enrolls this host with an Entry as a Reverse Node: creates or loads node_key.pem, verifies and pins the Entry public key, prints a 6-digit code while waiting for approval, and atomically writes entries.json once approved.
attach [--root DIR] Bridges stdin/stdout bidirectionally to run/node.sock. If no daemon is running, calls StartDaemon to launch it detached in the background and polls for up to 15 seconds. Used by the Hub for local, SSH, WSL, and Windows Nodes.
stop [--root DIR] If a daemon holds the lock, calls SystemService.Shutdown over run/node.sock and waits until the lock is released (after the daemon stops all running agents and exits).
admin [--root DIR] <sessions|show|prompts|answer|send|cancel> Owner emergency CLI that talks directly to run/node.sock without a Hub (never auto-starts the daemon). Plain-text output: list Sessions, view the last N items (default 20), list pending prompts/approvals, answer prompts, send messages, or cancel the active Turn (server/node/admin_cli.go).
nodes / delegate / thread / discuss Agent-facing orchestration CLI speaking to orch/s.sock using TRIZANO_SOCKET and an HMAC session token (discuss modes supports offline validation and --dry-run). See Multi-Agent Orchestration and Discussion Rooms.
mcp Runs the built-in MCP server over stdio, exposing orchestration operations as tools for MCP-capable agents.

Session Actors and Idle Reclamation

Each Session runs as an independent actor goroutine (server/node/session/session.go). All mutable Session state, timeline items, and the active driver connection belong exclusively to run(), eliminating lock contention.

  • Command dispatch (do vs. look):
    • External callers submit closures over the actor's cmds channel.
    • do(ctx, fn) is for operations that read or mutate the timeline: before invoking fn, it flushes pending streaming deltas, calls wake() to load the timeline from SQLite if asleep, and resets both idle timers.
    • look(ctx, fn) (light: true) is for metadata-only reads and lightweight mutations (listing Sessions, pinning, archiving, renaming, watch reconciliation). It never wakes a sleeping timeline, preventing background scans from pulling historical threads into memory.
  • Two-stage idle reclamation:
    • Timeline sleep (5 minutes, timelineIdle): When a Session has no live agent process, 5 minutes of inactivity triggers sleep(), flushing any unsaved streaming items to SQLite and releasing in-memory items and index. All non-running Sessions start asleep when the Node boots.
    • Agent process eviction (30 minutes, agentIdle): When an agent process is alive but idle (State != RUNNING and no running background tasks), 30 minutes without agent events or external commands calls closeConn() to stop the child process and put the timeline to sleep. The next user message respawns the CLI and resumes context via its persisted native_handle, keeping idle subagent sessions from holding RAM and file watchers indefinitely.
  • Crash recovery (recover): When the daemon loads existing Sessions at startup, any Session left in RUNNING or Attention from an unexpected exit is settled before run() begins: pending Prompt items are canceled, unfinished tool calls are marked CANCELED, an INTERRUPTED TurnEnd and notice are appended, and the Session returns to idle.

Terminals: PTY, tmux, and Windows ConPTY

server/node/terminal/ manages interactive shells, project scripts, and interactive agent CLI terminals. Each terminal retains the last 256 KiB of output in memory as a snapshot for newly attaching clients. Multiple clients can attach concurrently (terminal dimensions follow the most recent resize); a slow subscriber whose backlog exceeds 512 chunks is disconnected so it can reconnect and rebuild from snapshot.

  • Unix PTY and tmux persistence (pty_unix.go, terminal.go):
    • Spawns pseudo-terminals with creack/pty and sets TERM=xterm-256color, COLORTERM=truecolor, and a UTF-8 LANG when missing.
    • When tmux is installed on the host, EnablePersistence uses an isolated Node socket at run/tmux.sock (always passing -u -f /dev/null so user tmux configs cannot interfere, and probing tmux-256color / screen-256color). Terminal sessions run inside background tmux sessions with metadata stored in SQLite's terminals table. After a daemon upgrade or restart, the new process iterates over the table, calls reattachTmux on surviving tmux sessions, and restores the initial screen buffer via capture-pane -p -e -S -500. Without tmux, terminals exit with the daemon.
  • Windows ConPTY (pty_windows.go, shells_windows.go):
    • Creates pseudo-consoles via Windows CreatePseudoConsole and PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE; the child process starts suspended and is assigned to a dedicated sysproc.Job before resuming so the process tree cannot escape.
    • ListShells probes PowerShell 7 (pwsh), Windows PowerShell, cmd.exe, Git Bash (injecting CHERE_INVOKING=1 to preserve working directory), and non-Docker-Desktop WSL distributions listed under the Lxss registry key.
    • Because ConPTY output pipes do not reliably signal EOF when the shell exits, the Node calls ClosePseudoConsole immediately once the main process terminates to end the read loop. Hangup closes the pseudo-console first and, if the process does not exit within killGrace (3 seconds), terminates the entire Job Object. Windows does not support tmux, so terminals do not survive daemon restarts.

SQLite State Store

Node state is persisted in <root>/state.db (server/node/store/store.go) using pure-Go modernc.org/sqlite (zero CGO), a single-connection pool (SetMaxOpenConns(1)), WAL journaling, synchronous=NORMAL, busy_timeout=5000, and foreign_keys=on.

  • Protobuf row payloads and migrations: Most tables store serialized Protobuf bytes in a data column so field additions rarely require schema changes. Schema migrations run transactionally at startup via an ordered migrations slice tracked with PRAGMA user_version (the Node refuses to start if the on-disk schema version is newer than the binary).
  • Core tables: workspaces, sessions (including handle, pending_context, fork_from), items (indexed by session_id, ord), agent_catalogs (cached probe results keyed by CLI version), tasks, settings, watches, usage_records, terminals, attachments (with session ownership, shared on fork), meta, roster_statements (signed Roster statements held by the Node), review_baselines, and review_overrides.
  • Durability semantics: Timeline items commit individually, so WAL + synchronous=NORMAL is used. A daemon crash loses no committed data and will not corrupt the database; only an abrupt host power loss can lose the last few uncheckpointed commits.

Build Identity and Non-Disruptive Replacement

A Node's "build" is the first 12 hex characters of its binary's SHA-256 digest (server/internal/buildid), paired with internal/version.Version injected via -ldflags at compile time. Remote and Reverse Node binaries live in immutable directories at bin/<build>/trizano-h3 (.exe on Windows).

Replacement Decision and Turn Deferral (server/hub/nodes/node.go)

  1. shouldReplace(offer, running) rules:
    • No replacement when the Hub's expected build hash matches the running Node's hash.
    • Both sides are release versions (MAJOR.MINOR.PATCH): upgrade-only. Replacement triggers only when offer.version > running.version; equal or older versions neither downgrade nor set pending_build (preventing multi-Entry setups on slightly different releases from fighting over a Node).
    • Either side is a dev build: any build-hash mismatch triggers replacement. For Reverse Nodes, dev builds are pushed only by the Roster's root Entry.
  2. Active-Turn protection: Once replacement is warranted, the Hub calls SessionService.ListSessions to check whether any Session is in SESSION_STATE_RUNNING. If a Turn is in progress, the Hub keeps using the running daemon, records pending_build on the Node status (surfaced in clients as a pending update), and watches Session state changes/deletions (endsTurn) on its internal Node event stream, triggering replacement the moment the last active Turn completes.

Two Replacement Paths and Old-Build Pruning

  • Local and SSH / WSL / Windows Nodes: After transitioning the Node state to updating, the Hub opens a temporary EventService.Watch and calls SystemService.Shutdown over the owner socket. The old daemon stops all agents and exits (after a 200 ms delay so the RPC response flushes). Once the Watch stream drops on process exit, the Hub immediately runs attach with the new build to start the replacement daemon.
  • Reverse Nodes: When idle, the Entry streams the matching platform binary from dist/ in 1 MiB chunks via SystemService.InstallBuild (server/node/svc_system.go). The Node writes to a temp file under <root>/bin/ while hashing on the fly, verifies size, SHA-256, and build ID, atomically renames it into <root>/bin/<build>/trizano-h3 (0755), stores the path in n.restart, and runs the same graceful shutdown path as Shutdown. Once Serve releases the lock and closes SQLite, it returns node.Restart{Exe} and main switches binaries:
    • Unix (restart_unix.go): calls syscall.Exec(exe, ...) to replace the process image in place with the same PID, transparent to systemd and launchd.
    • Windows (restart_windows.go): calls node.StartDaemon(exe, layout) to launch the new detached daemon, then exits the old process.
  • Old-build pruning (server/node/builds.go): After acquiring the lock on startup, the new daemon runs pruneBuilds(exe). If it is running from a bin/<build>/ directory matching its own 12-hex build ID, it scans sibling 12-hex build directories and keeps only the current build and the single most recent previous build (by modification time), removing everything older.

SSH Bootstrap, WSL, and Native Windows Nodes

Hub-outbound nodes vs. Reverse Nodes

RemoteDialer (server/hub/nodes/remote.go) handles probing, binary installation, and connection setup for standard SSH hosts, local WSL, WSL on remote Windows hosts, and native Windows SSH hosts.

Standard SSH Bootstrap Flow

To stay compatible with both POSIX shells and Windows OpenSSH default shells, every step invokes a single executable with plain arguments—no inline shell scripts:

  1. Probe (30 s timeout): Runs uname -sm to identify os/arch and pick dist/trizano-h3_<os>_<arch>. For WSL targets with a relative --remote-dir, it also runs printenv HOME to build an absolute Linux path (preventing an outer Windows shell from expanding ~ to the Windows home directory).
  2. Install check: Runs test -x <remote-dir>/bin/<build>/trizano-h3 (exit code 1 means missing).
  3. Streaming upload and verification (5 min timeout): Without requiring SFTP, runs mkdir -p, dd of=<bin>.partial bs=65536 (numeric block size for macOS BSD dd compatibility), chmod 700, sha256sum (shasum -a 256 on macOS) to verify the full digest, and atomic mv into place.
  4. Attach and keepalive: Launches <remote-dir>/bin/<build>/trizano-h3 attach --root <remote-dir>/node, wraps the subprocess's stdin/stdout as a net.Conn carrying h2c, and enables a 10 s idle ping with a 5 s timeout. On disconnect, sshx.CloseMaster tears down any stale OpenSSH ControlMaster socket and reconnects with 1 s to 30 s exponential backoff (resetting after 60 s of stable uptime).

WSL Node Handling

  • Command wrapping: When the Hub runs locally on Windows, it invokes wsl.exe -d <distro> --exec <argv> directly (setting WSL_UTF8=1 so errors are UTF-8). Over SSH to a remote Windows host, it invokes ssh <host> wsl.exe -d <distro> --exec <argv>. Because arguments pass through Windows OpenSSH's default shell before reaching wsl.exe with no universal quoting rules, every argument token is restricted to [A-Za-z0-9._/=-]+.
  • PATH ordering: When a Node detects it is running inside WSL, it moves /mnt/<drive> entries to the end of PATH after merging the login shell's PATH, preventing Windows-side npm shims from shadowing Linux-installed agent CLIs.

Native Windows Nodes and internal/sysproc

When the standard uname -sm probe fails (with an exit code other than SSH's 255 connection failure) or a WSL install fails, the Hub runs a lightweight fallback probe (server/hub/nodes/winprobe.go) via powershell -NoProfile -NonInteractive -EncodedCommand <UTF-16LE base64> that prints the CPU architecture, DefaultShell from HKLM\SOFTWARE\OpenSSH, and non-Docker-Desktop WSL distros from HKCU\...\Lxss in UTF-8.

If no WSL distro is configured, the Hub takes the native Windows path (server/hub/nodes/windows.go):

  • Shell check and SFTP install: Requires OpenSSH DefaultShell to be cmd.exe, powershell.exe, or pwsh.exe (ensuring binary-clean stdio pass-through). Checks for the binary via PowerShell Test-Path; if missing (Windows lacks dd), uploads through sftp -b - batch commands to create directories, put to .partial, and rename into place (supporting both home-relative paths and /C:/... absolute paths).
  • Command formatting: Launch commands always use backslashes and prefix relative paths with .\ (for example .\.trizano\bin\<build>\trizano-h3.exe attach --root .\.trizano\node), avoiding cmd.exe treating / as a switch or PowerShell parsing .trizano as a decimal literal. Once connected, the Hub caches the host as Windows in memory so reconnects go straight to this path, clearing the cache to re-probe if dialing fails.
  • Breaking away from OpenSSH Job Objects and process-tree containment (server/internal/sysproc/sysproc_windows.go):
    • Win32-OpenSSH assigns each SSH session a Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK, killing all child processes on SSH disconnect. When attach launches the daemon, sysproc.SetDetached queries the active job's limit flags and adds CREATE_BREAKAWAY_FROM_JOB whenever the job kills on close and allows breakaway, combined with CREATE_NO_WINDOW to create a hidden console (preventing flash windows while giving child console processes a shared hidden console). If the job kills on close but forbids breakaway, it fails explicitly with an error.
    • Every managed subprocess (agents, managed browser, Hub-spawned ssh/attach) starts through sysproc.Start with CREATE_SUSPENDED, is assigned to a fresh Job Object (KILL_ON_JOB_CLOSE | BREAKAWAY_OK), and is then resumed—ensuring the entire process tree is cleaned up on exit or termination.
    • Before launching .cmd/.bat wrappers (such as npm-installed CLIs), CheckBatchArgs rejects %, newlines, and unquoted & | < > ^ to block cmd.exe argument injection (BatBadBut) and instructs switching to a native .exe.

Clone this wiki locally