Repository navigation
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.
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
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.
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 13trizano.node.v1Connect services plus/raw,/media, and/attachments. - Requests arriving on this socket carry an
ownerKeycontext marker (withOwner).SystemService.Shutdownonly accepts the owner socket; calls over a reverse connection or the orchestration socket fail withPermissionDenied. - When
OpenControlBridgereceives aBridgeHellofor an Entry over the owner socket, the Node automatically pauses its reverse connector to that same Entry so duplicate connections are never maintained.
- Mounts
-
Agent socket
orch/s.sock(0600):- Mounts
n.OrchHandler(), exposing onlyPOST /internal/orch/{method}—notrizano.node.v1management or file endpoints are reachable here. - The Node injects
TRIZANO_CLI(pointing toorch/trizano-h3) andTRIZANO_SOCKET(pointing toorch/s.sock) into agent subprocesses. Sandboxed agents only needorch/mounted to run delegation and Discussion Room orchestration, and cannot reachrun/node.sockto shut down the daemon or alter Node configuration.
- Mounts
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. |
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 (
dovs.look):- External callers submit closures over the actor's
cmdschannel. -
do(ctx, fn)is for operations that read or mutate the timeline: before invokingfn, it flushes pending streaming deltas, callswake()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.
- External callers submit closures over the actor's
-
Two-stage idle reclamation:
-
Timeline sleep (5 minutes,
timelineIdle): When a Session has no live agent process, 5 minutes of inactivity triggerssleep(), flushing any unsaved streaming items to SQLite and releasing in-memoryitemsandindex. 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 != RUNNINGand no running background tasks), 30 minutes without agent events or external commands callscloseConn()to stop the child process and put the timeline to sleep. The next user message respawns the CLI and resumes context via its persistednative_handle, keeping idle subagent sessions from holding RAM and file watchers indefinitely.
-
Timeline sleep (5 minutes,
-
Crash recovery (
recover): When the daemon loads existing Sessions at startup, any Session left inRUNNINGorAttentionfrom an unexpected exit is settled beforerun()begins: pendingPromptitems are canceled, unfinished tool calls are markedCANCELED, anINTERRUPTEDTurnEndand notice are appended, and the Session returns to idle.
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/ptyand setsTERM=xterm-256color,COLORTERM=truecolor, and a UTF-8LANGwhen missing. - When
tmuxis installed on the host,EnablePersistenceuses an isolated Node socket atrun/tmux.sock(always passing-u -f /dev/nullso user tmux configs cannot interfere, and probingtmux-256color/screen-256color). Terminal sessions run inside background tmux sessions with metadata stored in SQLite'sterminalstable. After a daemon upgrade or restart, the new process iterates over the table, callsreattachTmuxon surviving tmux sessions, and restores the initial screen buffer viacapture-pane -p -e -S -500. Withouttmux, terminals exit with the daemon.
- Spawns pseudo-terminals with
-
Windows ConPTY (
pty_windows.go,shells_windows.go):- Creates pseudo-consoles via Windows
CreatePseudoConsoleandPROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE; the child process starts suspended and is assigned to a dedicatedsysproc.Jobbefore resuming so the process tree cannot escape. -
ListShellsprobes PowerShell 7 (pwsh), Windows PowerShell,cmd.exe, Git Bash (injectingCHERE_INVOKING=1to preserve working directory), and non-Docker-Desktop WSL distributions listed under theLxssregistry key. - Because ConPTY output pipes do not reliably signal EOF when the shell exits, the Node calls
ClosePseudoConsoleimmediately once the main process terminates to end the read loop. Hangup closes the pseudo-console first and, if the process does not exit withinkillGrace(3 seconds), terminates the entire Job Object. Windows does not support tmux, so terminals do not survive daemon restarts.
- Creates pseudo-consoles via Windows
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
datacolumn so field additions rarely require schema changes. Schema migrations run transactionally at startup via an orderedmigrationsslice tracked withPRAGMA user_version(the Node refuses to start if the on-disk schema version is newer than the binary). -
Core tables:
workspaces,sessions(includinghandle,pending_context,fork_from),items(indexed bysession_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, andreview_overrides. -
Durability semantics: Timeline items commit individually, so
WAL + synchronous=NORMALis 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.
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).
-
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 whenoffer.version > running.version; equal or older versions neither downgrade nor setpending_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.
-
Active-Turn protection: Once replacement is warranted, the Hub calls
SessionService.ListSessionsto check whether any Session is inSESSION_STATE_RUNNING. If a Turn is in progress, the Hub keeps using the running daemon, recordspending_buildon 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.
-
Local and SSH / WSL / Windows Nodes: After transitioning the Node state to updating, the Hub opens a temporary
EventService.Watchand callsSystemService.Shutdownover 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 runsattachwith 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 viaSystemService.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 inn.restart, and runs the same graceful shutdown path asShutdown. OnceServereleases the lock and closes SQLite, it returnsnode.Restart{Exe}andmainswitches binaries:-
Unix (
restart_unix.go): callssyscall.Exec(exe, ...)to replace the process image in place with the same PID, transparent tosystemdandlaunchd. -
Windows (
restart_windows.go): callsnode.StartDaemon(exe, layout)to launch the new detached daemon, then exits the old process.
-
Unix (
-
Old-build pruning (
server/node/builds.go): After acquiring the lock on startup, the new daemon runspruneBuilds(exe). If it is running from abin/<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.
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.
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:
-
Probe (30 s timeout): Runs
uname -smto identifyos/archand pickdist/trizano-h3_<os>_<arch>. For WSL targets with a relative--remote-dir, it also runsprintenv HOMEto build an absolute Linux path (preventing an outer Windows shell from expanding~to the Windows home directory). -
Install check: Runs
test -x <remote-dir>/bin/<build>/trizano-h3(exit code1means missing). -
Streaming upload and verification (5 min timeout): Without requiring SFTP, runs
mkdir -p,dd of=<bin>.partial bs=65536(numeric block size for macOS BSDddcompatibility),chmod 700,sha256sum(shasum -a 256on macOS) to verify the full digest, and atomicmvinto place. -
Attach and keepalive: Launches
<remote-dir>/bin/<build>/trizano-h3 attach --root <remote-dir>/node, wraps the subprocess's stdin/stdout as anet.Conncarrying h2c, and enables a 10 s idle ping with a 5 s timeout. On disconnect,sshx.CloseMastertears down any stale OpenSSHControlMastersocket and reconnects with 1 s to 30 s exponential backoff (resetting after 60 s of stable uptime).
-
Command wrapping: When the Hub runs locally on Windows, it invokes
wsl.exe -d <distro> --exec <argv>directly (settingWSL_UTF8=1so errors are UTF-8). Over SSH to a remote Windows host, it invokesssh <host> wsl.exe -d <distro> --exec <argv>. Because arguments pass through Windows OpenSSH's default shell before reachingwsl.exewith 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 ofPATHafter merging the login shell'sPATH, preventing Windows-side npm shims from shadowing Linux-installed agent CLIs.
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
DefaultShellto becmd.exe,powershell.exe, orpwsh.exe(ensuring binary-clean stdio pass-through). Checks for the binary via PowerShellTest-Path; if missing (Windows lacksdd), uploads throughsftp -b -batch commands to create directories,putto.partial, andrenameinto 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), avoidingcmd.exetreating/as a switch or PowerShell parsing.trizanoas 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. Whenattachlaunches the daemon,sysproc.SetDetachedqueries the active job's limit flags and addsCREATE_BREAKAWAY_FROM_JOBwhenever the job kills on close and allows breakaway, combined withCREATE_NO_WINDOWto 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 throughsysproc.StartwithCREATE_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/.batwrappers (such as npm-installed CLIs),CheckBatchArgsrejects%, newlines, and unquoted& | < > ^to blockcmd.exeargument injection (BatBadBut) and instructs switching to a native.exe.
- Win32-OpenSSH assigns each SSH session a Job Object with
English
Getting Started
Deployment & Networking
Architecture & Nodes
Agents
Clients & Development
Project & Community
中文文档
新手指引
部署与网络
架构与节点
智能体
客户端与开发
项目与社区