Skip to content

Architecture

root edited this page Dec 4, 2026 · 6 revisions

Architecture Overview

🌐 English · 简体中文

This page covers Trizano's process topology, API contracts and routing, normalized timeline display model, repository layout, core architectural decisions, and extension points. It is aimed at developers reading or contributing to the codebase.

Process Topology

Trizano splits responsibilities across three roles: a single always-on Hub (trizano-carbon), a per-machine Node (trizano-h3) daemon, and three clients that talk only to the Hub.

Trizano system architecture

flowchart TB
    subgraph Clients["Clients (connect to Hub only)"]
        Web["Web browser (web/)"]
        Desktop["Desktop app: MyGo (desktop-go/)"]
        Android["Native Android app (android/)"]
    end

    subgraph Entry["Always-on Entry host"]
        Hub["Hub: trizano-carbon (127.0.0.1:47900)"]
        AdminSock["Admin socket admin.sock"]
        LocalNode["Local Node: trizano-h3"]
        Hub -->|"LocalDialer: attach stdio (h2c)"| LocalNode
        Hub --- AdminSock
    end

    subgraph Remotes["Remote machines"]
        SSHNode["SSH / WSL / Windows Node: trizano-h3"]
        RevNode["Reverse Node: trizano-h3 serve"]
    end

    Web -->|"HTTPS: Connect + 3 WebSockets"| Hub
    Desktop -->|"47801 local proxy → Hub / in-process Hub"| Hub
    Android -->|"HTTPS: Connect binary + WS"| Hub

    Hub -->|"RemoteDialer: ssh / wsl.exe → attach (h2c)"| SSHNode
    RevNode -->|"Outbound WS /nodes-connect + inner mTLS 1.3 + h2c"| Hub
Loading
  • Hub (trizano-carbon): The sole external entry point, listening on 127.0.0.1:47900 by default (external HTTPS is provided by a reverse proxy or tunnel). It manages the Hub identity key, device authorization and session tickets, the multi-Entry Roster, embedded static web assets, Node supervision and proxying, event stream forwarding, the cross-Node delegation bridge, and usage aggregation. The Hub never runs coding agents itself; entry-only hosts can disable the local Node with --no-local-node. See Deployment and Multi-Entry & Failover.
  • Node (trizano-h3): One daemon per machine that runs agents. It never binds a public TCP port, exposing only a local owner socket (run/node.sock) and an agent orchestration socket (orch/s.sock). It manages agent processes, PTY/tmux/ConPTY terminals, files, review baselines, Git/worktrees, dev-server ports and preview tunnels, the managed headless browser, and host telemetry. See Node Internals and Node Services.
  • Three clients:
    • Web (web/): React 19 + Vite + Tailwind v4 + zustand. Its build output (server/hub/webui/dist) is embedded into the Hub with -tags embedweb and reused by the desktop app.
    • Desktop (desktop-go/, MyGo): Runs a local proxy on 127.0.0.1:47801 (falling back to a random port if occupied) serving the same web UI. In standalone mode it embeds the Hub in-process and only ships the trizano-h3 binary alongside itself.
    • Android (android/): Native Kotlin + Jetpack Compose client with no GMS dependency. A foreground service maintains the event stream and posts system notifications. See Client Internals.

Contracts and Code Generation

All cross-process APIs use Protobuf definitions under proto/ as the single source of truth, carried over the Connect protocol. Generated Go and TypeScript code is committed to the repository and must not be edited by hand.

Three Protobuf Packages

Package Path Responsibility and core services
trizano.hub.v1 proto/trizano/hub/v1/ Hub APIs: AuthService, NodeEnrollmentService, DeviceService, NodeService, EntryService, EventService, OrchestrationService, UsageService
trizano.node.v1 proto/trizano/node/v1/ Node APIs (13 services) and the normalized timeline model (item.proto): workspaces, sessions, agents, terminals, files, review, Git, ports, preview tunnels, managed browser, system, usage, and Node event stream
trizano.roster.v1 proto/trizano/roster/v1/ Signed Roster structures shared across Entries and Nodes (Signed, Statement, Epoch/Add/Remove, Member, Role) and cross-Entry session tickets (Ticket, tt1.)

Connect Protocol and Three WebSocket Tunnels

  • Standard RPCs: Built on Connect (connectrpc.com/connect/v2 on Go). Unary and server-streaming RPCs work over plain HTTP/1.1, which passes cleanly through tunnels and reverse proxies. The web client uses JSON encoding by default for easy inspection; Android uses binary Protobuf.
  • Hub-to-Node link: Runs HTTP/2 cleartext (h2c) over either a stdio pipe or an inner mutual TLS 1.3 tunnel inside an outbound WebSocket, supporting native bidirectional streaming.
  • Browser bidirectional-streaming exception: Browsers cannot initiate HTTP/2 bidirectional streams directly, so the Hub accepts WebSocket upgrades on three specific procedure paths (each binary WebSocket frame carries one raw Protobuf message using the same proto types) and bridges them to the Node's bidirectional stream:
    1. /nodes/{node}/trizano.node.v1.TerminalService/AttachTerminal
    2. /nodes/{node}/trizano.node.v1.PreviewService/Dial
    3. /nodes/{node}/trizano.node.v1.BrowserService/AttachTab

Code Generation and Compatibility Checks

  • Running make gen (which invokes buf lint and buf generate using buf.yaml and buf.gen.yaml) produces:
    • Go server/client stubs and Connect handlers: server/gen/ (protoc-gen-go + protoc-gen-connect-go)
    • TypeScript types and service descriptors: packages/proto-ts/src/gen/ (protoc-gen-es)
  • Android does not commit generated code; the Gradle protobuf plugin under android/ generates java-lite, kotlin-lite, and connect-kotlin directly from the root proto/ directory at build time.
  • buf.yaml enforces STANDARD lint rules and FILE-level breaking-change checks. Contract changes must be made in proto/ followed by make gen, preserving existing field numbers, types, and file-level wire compatibility.

Path-Prefix Routing

The Hub reverse-proxies Node APIs without decoding payloads, so adding an RPC or field to trizano.node.v1 requires no changes to Hub routing code.

  • Prefix stripping and pass-through: server/hub/nodes/registry.go mounts at /nodes/, strips /nodes/{node} from /nodes/{node}/<procedure>, and forwards the request as-is through that Node's h2c RoundTripper (FlushInterval: -1 to preserve streaming responses). Non-RPC Node HTTP endpoints (/raw, /media, /attachments) pass through the same prefix.
  • Client addressing: Clients instantiate a Connect transport per Node with base URL /nodes/{node} (see web/src/rpc/client.ts on web). Globally, every resource is keyed by (node ID, node-local resource ID).
  • Trust boundary and 403 blocklist: isProxyForbidden unconditionally returns 403 Forbidden to external clients for:
    • internal/* (Node orchestration internal routes)
    • SystemService/Shutdown
    • SystemService/OpenControlBridge
    • SystemService/SyncRoster
    • SystemService/InstallBuild
  • Credential stripping and response isolation: Before forwarding to any Node, the Hub strips Authorization and Cookie request headers. Before returning a Node response to the client, the Hub strips Set-Cookie and X-Trizano-Token and overwrites X-Content-Type-Options: nosniff, Content-Security-Policy: sandbox; ..., and Cross-Origin-Resource-Policy: same-origin. See Security.

Node-Side Normalized Display Model

Protocol differences across coding agents are absorbed entirely inside each Node driver and normalized into timeline items defined in proto/trizano/node/v1/item.proto. Clients stay thin renderers.

  • Single timeline model (Item): Every record carries a session-unique id, owning turn, creation timestamp, optional native subagent attribution (parent_tool_id), and one of 11 body variants:
    • Conversation and thinking: UserMessage (including attachments and delegation WatchCallback), AssistantText (streaming and plan flags), Reasoning (the Node computes duration once streaming ends).
    • Tools and prompts: ToolCall (classified via ToolKind into shell, read, edit, search, fetch, task, skill, or other, with optional ShellDetail, FileChangesDetail, or SubagentDetail), Prompt (tool approvals, question cards, plan confirmations).
    • Auxiliary and turn closure: TodoList, Notice, TurnEnd (outcome, duration, tokens, cost, and throughput).
    • Discussion Rooms: DiscussionEntry, DiscussionProgress, DiscussionGraph.
  • Delta batching and cursor consistency:
    • Nodes buffer streaming text and tool output for 50 ms, coalescing chunks per item into one ItemDelta event. Any non-delta event or external request flushes immediately so snapshots and streams stay ordered.
    • Each Session maintains a monotonically increasing rev; each Node maintains a Node-level node_seq and a random per-boot boot token. A Session rev gap triggers a resync of only that Session; a Node stream that cannot resume resyncs only that Node. See Event Synchronization.

Repository Layout

The tables below map top-level directories and the core packages under server/.

Top-Level Directories

Directory Responsibility
proto/ buf module root defining trizano.hub.v1, trizano.node.v1, and trizano.roster.v1
server/ Go module (github.com/1molchuan/trizano/server) containing the Hub, Node daemon, agent drivers, shared internal packages, and generated Go stubs
web/ React + Vite + Tailwind v4 web frontend (forked from t3code v0.0.22, keeping UI primitives while rewriting all business logic), built into server/hub/webui/dist
packages/proto-ts/ TypeScript Protobuf / Connect code generated by make gen
android/ Native Kotlin + Jetpack Compose Android client (single app module, applicationId top.onemolchuan.code, minSdk 31)
desktop-go/ Desktop app (MyGo, standalone Go module) providing the 47801 local proxy, in-process standalone Hub, and system tray
deploy/ macOS launchd and Linux systemd user-service templates plus reverse-proxy/tunnel guides
docs/ Design docs (in Chinese), topic specs, and the source Markdown for this wiki (docs/wiki/)

Core Packages Under server/

Package Responsibility
server/cmd/trizano-carbon/ Hub entrypoint and admin subcommands (approve/deny/pairings/devices/revoke/backup/restore/entry join/roster reset)
server/cmd/trizano-h3/ Node daemon entrypoint (serve/join/attach/stop/admin), orchestration CLI (nodes/delegate/thread/discuss), and built-in mcp server
server/hub/ Hub assembly (hub.go), event fan-out (events.go), Node enrollment (enrollment.go), Roster management and Entry sync (roster.go, entry.go, entry_sync.go), cross-Node delegation and handoff (orch.go), usage aggregation (usage.go), encrypted backups (backup.go), and end-to-end tests with fake CLIs (testdata/)
server/hub/auth/ P-256 identity key, signed Hello, pairing approval, WebAuthn passkeys, device-key login, and tt1. ticket signing/verification
server/hub/nodes/ Node registry and /nodes/ reverse proxy (registry.go), supervision and build replacement (node.go), three Dialer implementations (dial.go, remote.go, reverse.go), Windows probing and SFTP bootstrap (winprobe.go, windows.go), and the three WebSocket bridges (terminal.go, preview.go, browser.go)
server/hub/sshx/ System OpenSSH wrapper, POSIX/SFTP quoting, and ControlMaster multiplexing
server/hub/store/ Hub SQLite persistence layer (hub.db)
server/hub/webui/ Embeds web build output under -tags embedweb and serves static assets
server/node/ Node daemon lifecycle (daemon.go, node.go, builds.go), reverse enrollment and connectors (join.go, connect.go, roster.go), emergency owner CLI (admin_cli.go), control bridge and orchestration HTTP endpoint (bridge.go, orch_http.go), host telemetry (health*.go), subscription rate limits (rate_limits.go), project script manifests (scripts.go), and thin Connect service handlers (svc_*.go)
server/node/session/ Session actor and lifecycle, native session import, queued steering, fork/rewind, watch subscriptions, and the discussion/ Starlark engine for Discussion Rooms
server/node/driver/ Driver interfaces and claude/, codex/, acp/ implementations, plus shared helpers (rpc/, proc/, diff/, elicitation/)
server/node/terminal/ Unix PTY (with tmux persistence), Windows ConPTY, shell probing, OSC status scanning, and script variable expansion
server/node/files/ os.Root-sandboxed file reads/writes, fuzzy file search, content search, ReadExternalFile, /raw, /media, and /attachments
server/node/review/ Per-directory review baseline engine independent of the Git staging area (Git mode and snapshot mode) and content-addressed blob storage
server/node/git/ Status, diff, log, branches, staging/commit/push, and worktree management built on the host's git CLI
server/node/ports/ Cross-platform dev-server listening-port scanner, HTML probe naming, and process termination
server/node/browser/ Managed headless Chromium process manager, single-connection CDP client, screencast streaming, and in-page DOM annotation script
server/node/store/ Node SQLite persistence layer (state.db)
server/internal/ Business-agnostic infrastructure shared by Hub and Node: buildid, eventlog, ids, nodeauth (crypto and inner mTLS), orch (JSON orchestration protocol), pricing, roster (Roster set evaluation), shellro (read-only shell detection), sysproc (file locks, Unix process groups, Windows Job Objects), version
server/gen/ Go Protobuf and Connect code generated by make gen

Key Architectural Decisions

Ten core decisions shape Trizano's stack and system boundaries:

  1. Go backend, TypeScript web frontend, Kotlin Android app: Both Hub and Node compile as CGO_ENABLED=0 static binaries with zero runtime dependencies on remote hosts and single-command cross-compilation across six targets (linux/darwin/windows × amd64/arm64). Agents that only ship a TypeScript SDK can be integrated through a lightweight ACP sidecar.
  2. Single Protobuf contract + Connect protocol: All three stacks generate from the same proto/ definitions. Standard RPCs run over Connect (HTTP/1.1-friendly), while the three browser bidirectional streams (terminal, preview tunnel, managed browser) carry raw Protobuf frames over Hub WebSockets instead of inventing a custom wire protocol.
  3. Path-prefix routing: The Hub strips /nodes/{node} and proxies transparently without unmarshaling Node payloads, keeping the Hub routing layer independent of Node RPC growth. Real-time Node events are wrapped as NodeEvent and fanned out on the Hub stream.
  4. Node-side normalized display model: Agent wire-protocol quirks stay confined to Node drivers, which emit item.proto records so clients focus on rendering and interaction.
  5. Unified h2c transport across all Node modes: Local (LocalDialer) and SSH/WSL/native-Windows (RemoteDialer) Nodes all run h2c over trizano-h3 attach stdio—no listening ports or port forwarding required on remote hosts. Machines behind NAT use ReverseDialer to carry the exact same h2c channel inside pinned mutual TLS 1.3 over an outbound WebSocket to /nodes-connect. See Network Topology.
  6. Immutable versioned builds and non-disruptive replacement: Node binaries are installed under content-hashed bin/<build>/ directories. Release builds only upgrade forward; dev builds replace on hash mismatch. If any Turn is running, replacement waits until the last active Turn completes. Local/SSH Nodes Shutdown and re-attach, while Reverse Nodes receive the binary via InstallBuild and switch in place. Old builds are pruned on startup.
  7. Session survivability and recovery: Structured drivers persist native_handle so Sessions resume via each CLI's native mechanism after a Node restart. On Unix hosts with tmux installed, terminals run on a dedicated tmux socket and survive daemon upgrades.
  8. Pinned identity and cross-Entry tickets: Each Hub holds a P-256 identity key. Browsers authenticate with passkeys (requiring an HTTPS secure context), while desktop and Android clients use device keys and pin the Entry's public key. Login issues signed tt1. tickets valid across every Entry in the same Roster. See Security.
  9. Web UI built on t3code primitives with a rewritten app layer: Forked from t3code v0.0.22, preserving components/ui primitives and CSS token structure while rewriting all application logic to speak packages/proto-ts directly and replacing all branding assets.
  10. Desktop app powered by MyGo (desktop-go/): Avoids bundling Chromium to keep installer size small. A local 47801 proxy serves the same web frontend and /_desktop/* control endpoints. It imports the server module directly to run an in-process standalone Hub (shipping only trizano-h3), stores data under top.onemolchuan.code.desktop (preserving compatibility with earlier desktop releases), and cross-compiles with CGO_ENABLED=0.

Extension Points

Trizano keeps explicit extension boundaries along its core paths so new agents, Node transports, or client features can be added cleanly:

  • Agent driver and optional capability interfaces (server/node/driver/driver.go):
    • Core Driver (Agent, Probe, Start, Interactive) and Conn (Events, Err, Send, Interrupt, Answer, Apply, Close) interfaces are currently implemented by claude, codex, and acp. Adding an agent means implementing the interface or registering an ACP entry.
    • Optional Driver extensions: Importer (listing and importing native sessions) and RateLimitReader (reading account subscription quota windows).
    • Optional Conn capabilities (enabled by the session layer via type assertion): Tasks (background task control and output), Steerer (mid-turn steering), WatchReceiver (delivering live watch callbacks to running agents, used by Discussion Rooms), Forker (native fork), and Rollbacker (native rewind). See Agent Drivers.
  • Node transport abstraction (server/hub/nodes/dial.go): The Dialer interface (Dial, Transport, Reset) decouples transport setup from Node supervision, proxying, and events. LocalDialer, RemoteDialer, and ReverseDialer implement it today, leaving a clean seam for additional transports.
  • Modules with clear boundaries (not yet extracted into interfaces): Authentication methods (passkey / device key / admin.sock), client notifications (derived purely from event-stream state), terminal persistence backend (currently tmux, structured to allow other multiplexers), and web command palette, settings sections, and multi-agent selectors.

Clone this wiki locally