Skip to content

Node Services

root edited this page Dec 4, 2026 · 5 revisions

Node Services

🌐 English · 简体中文

This page lists all Node RPC services defined under proto/trizano/node/v1/*.proto and walks through the workbench capabilities a Node exposes to clients—files, review baselines, Git and worktrees, port discovery, preview tunnels, managed headless browser, host telemetry, usage and subscription rate limits, project scripts, and non-RPC HTTP endpoints. It is aimed at developers inspecting Node API contracts or modifying these services.

Service Overview

n.Handler() (server/node/node.go) mounts all 13 trizano.node.v1 services on both the owner socket and reverse connections. Clients reach them via /nodes/{node}/<procedure>:

Service Proto file Core responsibility Detailed in
FileService file.proto Workspace directory listing, file read/write, file/content search, and read-only external file preview Below
ReviewService review.proto Per-directory review baselines independent of Git staging, plus accept/reject Below
GitService git.proto Git status, diff, commit history, branches, stage/commit/push, and worktrees Below
PortService port.proto On-demand discovery of local dev-server listening ports and process termination Below
PreviewService preview.proto WebSocket-bridged TCP tunnel to Node loopback ports with optional annotation injection Below
BrowserService browser.proto Node-managed headless Chromium tabs, CDP screencast streaming, and DOM annotation capture Below
SystemService system.proto Node info, settings, host health telemetry, control bridge, Roster sync, shutdown, and build upgrades Telemetry section below / Node Internals
UsageService usage.proto Per-Turn token/cost records and agent subscription rate-limit windows Below
WorkspaceService workspace.proto Workspace CRUD, directory browsing/creation, and three-layer project script merging Project Scripts section below
TerminalService terminal.proto PTY/tmux/ConPTY terminal management, shell probing, and bidirectional attach Node Internals
SessionService session.proto Session lifecycle, queued steering, tasks, fork/rewind, import, orchestration, and Discussion Rooms Node Internals / Multi-Agent Orchestration / Discussion Rooms
AgentService agent.proto Available coding agents on the Node plus probed models, modes, and options Agent Drivers
EventService event.proto Node-level Watch real-time event stream with boot and node_seq cursors Event Synchronization

Path convention: All absolute and relative paths returned by a Node use forward slashes (for example C:/Users/... on Windows). Incoming parameters accept both forward and backward slashes.

File Service (FileService)

FileService (server/node/svc_files.go, server/node/files/) provides sandboxed Workspace file access for the file tree and built-in editor. Every Workspace path is opened through Go's os.Root, so symlinks cannot escape the Workspace boundary.

RPC Behavior and constraints
ListDirectory Lists directory entries (directories first, case-insensitive sort), up to 5000 entries per directory (truncated set when exceeded), marking symlinks and .gitignore status
ReadFile Reads file content and MIME type; text cap is 1 MiB (truncated set when exceeded), with lowercase hex sha256 included for non-truncated text; binary files omit content so clients fetch via /raw
WriteFile Overwrites or creates a UTF-8 text file through review.WriteFile to stay in sync with the review baseline; supports expected_sha256 optimistic locking (mismatch returns FAILED_PRECONDITION, bypassed with force=true), atomic temp-file rename, and file-search index invalidation
SearchFiles Fuzzy-matches Workspace file and directory paths (skipping Git-ignored entries), returning byte offsets for match highlighting; default limit 50 results
SearchContent Full-text search supporting regex, case sensitivity, whole-word matching, and include_glob/exclude_glob filters; skips binary, > 1 MiB, and Git-ignored files; default limit 500 matches
ReadExternalFile Read-only preview of files outside a Workspace (such as plans or reports written by agents to ~/.claude/plans or /tmp), capped at 1 MiB

ReadExternalFile enforces a strict allowlist and credential blocklist in server/node/files/external.go and svc_files.go. After resolving all symlinks, it rejects any path inside .ssh, .gnupg, .aws, .kube, or .docker, any credential filename (such as .env*, id_rsa*, .netrc, auth.json, oauth_creds.json), and any private-key/keystore extension (.pem, .key, .p12, .pfx, .jks, .keystore). The resolved real path must fall within one of the following roots, and is then opened via os.Root to prevent TOCTOU symlink swaps:

  1. Any registered Workspace on the Node or the WorktreePath of a running/recorded Session;
  2. Agent scratch directories: ~/.claude, ~/.codex, ~/.gemini, ~/.agents, /tmp, and os.TempDir();
  3. If none of the above matches, a linked worktree sharing a repository (git rev-parse --git-common-dir) with a registered Workspace.

Review Baselines (ReviewService)

Review baseline vs. Git staging area

ReviewService (server/node/svc_review.go, server/node/review/) tracks all on-disk changes relative to the last accepted baseline per Workspace directory. It is completely independent of the Git staging area and captures edits regardless of source (agent tools, shell commands, or external editors).

  • Per-directory actor and baseline advancement: review.Manager runs one dirActor goroutine per directory to serialize file writes and Git hooks. When a Session begins a new Turn (OnTurnStart) and the directory currently has no pending review changes, the baseline advances automatically to the current disk state. If pending changes already exist, edits across multiple Turns accumulate until you accept or reset them.
  • Dual storage modes:
    • Git mode: Inside a Git working tree, the baseline is stored as a base commit hash plus an override table for files that were already dirty when the baseline was created (persisted in SQLite review_baselines and review_overrides, with content-addressed snapshots under <root>/review/blobs/). Reading the baseline version uses git cat-file --filters so line-ending filters match the working tree. If a branch switch or rebase moves HEAD away from the baseline commit, responses set head_drifted=true.
    • Snapshot mode: For non-Git directories or hosts without git, Go walks the directory to snapshot files (skipping .git, node_modules, target, .venv, dist, build, and honoring .gitignore). Directories exceeding 5000 files or containing files over 1 MiB opt out and return REVIEW_AVAILABILITY_TOO_LARGE.
  • Event integration: Fingerprints are recomputed after tool calls carrying FileChange (debounced 300 ms per directory), Turn completion, WriteFile, accept/reject/set-base calls, and Workspace-level GitService write operations. ReviewChanged (carrying only file count and rev) is broadcast only when the diff list actually changes.
RPC Purpose
GetReview Returns the Workspace's pending review file list (change kind, added/removed lines, binary flag, head_drifted, and rev)
GetReviewFile Returns the baseline text/hash and current on-disk text/hash for one file so the editor can render a diff
AcceptFiles Records the current on-disk state of specified files (empty list means all) into the baseline—never modifies disk or the Git index
RejectFiles Restores baseline content to disk for specified files (or all); newly created files absent from the baseline are deleted
SetReviewBase Updates a single file's baseline text to a client-computed result (for hunk-by-hunk acceptance), guarded by expected_base_sha256 against concurrent edits
ResetReview Rebuilds the directory baseline from the current on-disk state, clearing all pending review items

Git and Worktrees (GitService)

GitService (server/node/svc_git.go, server/node/git/) wraps the Node's local git CLI for code review, branching, commits, and multi-worktree management.

  • Multi-worktree addressing and guardrails: Every single-tree RPC except ListWorktrees and RemoveWorktree accepts an optional worktree path—empty targets the Workspace itself; non-empty must match an exact non-prunable entry from git worktree list --porcelain -z in the same repository, or the call fails with INVALID_ARGUMENT. Write operations targeting the Workspace itself run inside review.RunGitOp so review baselines stay consistent.
  • All 13 RPCs:
    • Read-only queries: GetGitStatus (branch, ahead/behind, staged and unstaged entries, total insertions/deletions), GetGitDiff (unstaged, staged, against HEAD, or GIT_DIFF_SCOPE_BRANCH via merge-base base_ref HEAD; supports specific commit and -w ignore-whitespace; truncates cleanly on whole-file boundaries when a single response exceeds 4 MiB), GetGitDiffSummary (file list and line counts ordered identically to GetGitDiff, without the 4 MiB cap), ListCommits (all_refs topological graph with --date-order, parents, and skip/has_more pagination), and ListBranches (local branches first, then remotes, sorted by newest commit).
    • Write operations: SwitchBranch (checkout or create=true; fails with FAILED_PRECONDITION if a running Session is active in that worktree), StageFiles and UnstageFiles (path lists, all=true, or unified-diff patch for hunk-level staging/unstaging), DiscardFiles, CommitChanges (supports amend), and PushBranch (supports set_upstream).
    • Worktree management: ListWorktrees (main worktree first, others sorted by path, with dirty-file count, longest-prefix workspaces, and default_base_ref), RemoveWorktree (supports force, delete_branch, and pruning stale prunable entries; refuses to remove the main worktree, a locked worktree, or any worktree still bound to an unarchived Session).

Port Discovery, Preview Tunnels, and Managed Browser

Nodes support two complementary web-preview and DOM-annotation paths: local port forwarding for desktop/Android, and a Node-hosted headless browser stream for web clients or external URLs.

flowchart LR
    DevSrv["Node dev server (127.0.0.1:PORT)"]

    subgraph Path1["Path A: Desktop / Android local port forwarding"]
        PClient["Client binds 127.0.0.1:PORT locally"]
        PHub["Hub WS: PreviewService/Dial"]
        PNode["Node previewService (injects /__trizano/annotate.js via net.Pipe when annotate=true)"]
        PClient <-->|"WS binary Protobuf"| PHub <-->|"h2c bidi"| PNode <-->|"TCP"| DevSrv
    end

    subgraph Path2["Path B: Web / external URL via managed browser"]
        BClient["Client browser pane"]
        BHub["Hub WS: BrowserService/AttachTab"]
        BNode["Node browser.Manager + cdpClient"]
        Chrome["Headless Chromium (--headless=new)"]
        BClient <-->|"WS frames (seq/ack) + input/annotations"| BHub <-->|"h2c bidi"| BNode <-->|"Local CDP WS (flatten)"| Chrome --> DevSrv
    end
Loading

Port Discovery (PortService)

PortService (server/node/svc_ports.go, server/node/ports/) discovers listening development servers on the Node on demand:

  • Scanning and filtering: Reads /proc/net/tcp{,6} and /proc/*/fd on Linux, runs lsof on macOS, and combines netstat -ano with the process table on Windows. Automatically excludes the Node daemon itself and managed Chromium processes. Keeps only ports tied to a registered Workspace directory or returning text/html to a GET / probe (1 s timeout, 64 KiB read cap, cached by (port, pid)). Display names follow the priority <title> → workspace + framework → entry script / process name → :port.
  • RPCs:
    • WatchPorts (server-stream): Scans every 3 seconds only while at least one subscriber is active; sends the full list on the first message and emits updates only when the list changes.
    • KillPort: Sends SIGTERM to the given PID (terminates the process on Windows), explicitly refusing to signal the Node daemon's own PID.

Preview Tunnel (PreviewService)

PreviewService (server/node/svc_preview.go) exposes a single bidirectional streaming RPC, Dial, which maps a remote Node's 127.0.0.1:<port> to the same port locally on desktop or Android without opening any network port on the Node.

  • Protocol and half-close: Clients connect via Hub WebSocket (/nodes/{node}/trizano.node.v1.PreviewService/Dial) and must send DialOpen{port, annotate} as the first message (port in 1–65535; target host is hardcoded to 127.0.0.1). Subsequent messages carry data byte chunks; either side sends close_write for TCP half-close, and the stream closes cleanly only once both sides reach EOF—preserving HTTP keep-alive and WebSocket upgrades transparently.
  • Annotation script injection (annotate=true): The Node pipes the stream via net.Pipe into a single-connection HTTP/1.1 reverse proxy (http.Server). For document/iframe requests it strips Accept-Encoding; for uncompressed text/html responses it injects <script src="/__trizano/annotate.js"></script> right after <head> (or at the start if <head> is absent) and strips Content-Length and Content-Security-Policy. It also serves GET /__trizano/annotate.js directly by combining the shared annotate.js with server/node/preview_bridge.js (which handles click/marquee selection, navigation, and URL updates via postMessage inside the iframe).

Managed Browser (BrowserService)

BrowserService (server/node/svc_browser.go, server/node/browser/) lets any client—particularly plain web browsers or sessions inspecting external URLs—drive a headless browser running directly on the Node.

  • Process lifecycle: browser.Manager runs a single owner actor managing the Chromium instance and tabs. On demand, it probes installed Chrome / Chromium / Edge binaries (honoring TRIZANO_BROWSER_BIN, never auto-downloading; returns FAILED_PRECONDITION with platform install instructions if absent) and launches --headless=new --remote-debugging-port=0 with a persistent profile at <root>/browser/profile (adding --no-sandbox when running as root), contained inside a sysproc.Group. Chromium shuts down automatically after 60 seconds with no open tabs or 10 minutes with no attached viewers (preserving tab URLs across sleep).
  • CDP streaming and annotations: Uses a lightweight coder/websocket-based cdpClient multiplexing sessions with flatten over one browser WebSocket. Frames stream via Page.startScreencast with monotonic seq numbers and client frame_ack backpressure capped at 2 in-flight frames; mouse/keyboard input batches over 16 ms windows. Built-in annotate.js pierces open Shadow DOM trees to resolve component and source locations. Tab changes broadcast BrowserTabChanged / BrowserTabRemoved over EventService.Watch.
  • RPCs: ListTabs, CreateTab, CloseTab, AttachTab (bidirectional stream over Hub WebSocket carrying viewport sizing, navigation, input events, hit_test, and frame acks), and CaptureAnnotation (point or box selection returning DOM/component/source metadata; when with_screenshot is set, crops a PNG ≤ 1024 px on its longest edge and saves it directly as an /attachments upload).

Host Telemetry (SystemService.WatchHealth)

Host telemetry is driven by the single-owner healthSampler actor (server/node/health.go) with pure-Go, zero-CGO implementations on Linux, macOS, and Windows (health_{linux,darwin,windows}.go).

  • On-demand sampling and ring buffer: No timer runs when no subscriber is attached. With active subscribers, the sampler ticks every 2 seconds and retains a 5-minute / 150-point ring buffer in memory; after the last subscriber disconnects, sampling stops following a 30-second grace period.
  • Tiered metrics: Base snapshots include total CPU, per-core CPU, memory and swap breakdown, root/home disk usage, aggregate non-loopback network RX/TX rates, process count, uptime, and load average (always 0 on Windows). Per-interface network rates, per-mount disk usage, and Top 5 CPU / memory aggregated processes are collected only while at least one subscriber requests detail=true.
  • RPCs:
    • SystemService.GetInfo: Static Node metadata (version, hostname, OS/arch, kernel, distro, CPU model/cores, Node public key) plus the latest health snapshot.
    • SystemService.GetHealth: On-demand single health snapshot (samples once if idle).
    • SystemService.WatchHealth (server-stream): First message carries the full history ring buffer so clients can plot charts immediately, followed by a new sample every 2 seconds; slow consumers drop older frames and keep only the latest reading.

Usage Accounting and Subscription Rate Limits (UsageService)

Token/cost tracking and subscription quota windows span trizano.node.v1.UsageService on Nodes and trizano.hub.v1.UsageService on the Hub:

  • Node usage persistence (QueryUsage): At the end of every regular Session Turn, the Node writes tokens, cost, duration, and throughput into SQLite usage_records (Discussion Room coordinator Turns are excluded to avoid double-counting participant subagent Sessions). QueryUsage returns raw records filtered by since, until, and agent.
  • Node subscription rate limits (GetRateLimits, server/node/rate_limits.go): The single-owner rateLimits actor reads quota windows from drivers implementing driver.RateLimitReader. It refreshes only on Node startup, Turn completion, passive rate-limit events from active Sessions, and explicit GetRateLimits{refresh: true} calls (20 s timeout per call, never polled on a timer), emitting RateLimitsChanged only when values change. Usage-billed API accounts report RATE_LIMIT_STATUS_USAGE_BILLED; read failures retain the last valid window and report RATE_LIMIT_STATUS_ERROR.
  • Hub aggregation and pricing (server/hub/usage.go):
    • GetUsageSummary queries QueryUsage concurrently across all online Nodes (or a specified node_id), listing offline Nodes in unavailable_nodes. It fills in missing costs using the built-in price table (server/internal/pricing) plus custom Hub overrides, then aggregates totals, cache hit rate, and average throughput by agent, model, Node, and local date.
    • GetPricing / SetPricing read and update custom model price overrides stored on the Hub.

Project Scripts (WorkspaceService.ListScripts)

Project scripts let you launch common commands into a Workspace terminal in one click, combining three configuration layers with file-context template variables (server/node/scripts.go, server/node/workspaces.go, server/node/terminal/script.go):

  • Three-layer merge order: WorkspaceService.ListScripts returns scripts in order from:
    1. Workspace-local scripts saved in the app (edited via UpdateWorkspace, SCRIPT_SOURCE_UNSPECIFIED);
    2. Repository manifest <workspace>/.trizano/scripts.json (IDs prefixed with repo:, SCRIPT_SOURCE_REPOSITORY);
    3. Node-wide manifest <root>/scripts.json (applied to all Workspaces on this Node; IDs prefixed with node:, SCRIPT_SOURCE_NODE).
  • Validation: Missing manifest files are treated as empty. Invalid JSON, missing required fields (id, name, command), duplicate ids, unknown icon values (allowed: play, test, lint, build, debug, configure), or extensions not starting with . return INVALID_ARGUMENT with file path and entry details.
  • Variable expansion: When running a script via TerminalService.CreateTerminal, the Node expands ${workspaceFolder} and—when file context is supplied—${file}, ${relativeFile}, ${fileDirname}, ${fileBasenameNoExtension}, and ${lineNumber}, single-quoting values appropriately for the target shell (POSIX shell or PowerShell). Referencing a file variable without providing file context returns an error.

Non-RPC HTTP Endpoints

Large binary transfers and media previews bypass Protobuf encoding and are mounted as plain HTTP endpoints on n.Handler() (server/node/node.go). Clients access them under /nodes/{node}/... with the same Hub device auth, credential stripping, and CSP sandbox isolation:

Endpoint Method and parameters Implementation and constraints
/raw GET /raw?workspace={ws}&path={path}[&download=1] server/node/files/raw.go: Reads Workspace file bytes through os.Root. Only image/*, video/*, audio/*, application/pdf, and text/plain may render inline (when download=1 is absent); all other types force Content-Disposition: attachment. Sets ETag and private, no-cache.
/raw POST /raw?workspace={ws}&dir={dir}&name={name} server/node/files/upload.go: Streams an upload into a Workspace directory (100 MiB cap; returns 413 if exceeded), writes via temp file + atomic rename, returns JSON metadata, and invalidates the file-search index.
/media GET /media?path={absPath}[&download=1] server/node/files/raw.go: Previews media files at an absolute path outside a Workspace (~/ supported). Sniffs the first 512 bytes plus extension and allows only image/*, video/*, audio/*, and application/pdf; all other types return 403 Forbidden.
/attachments POST /attachments?name={filename} server/node/files/attachments.go: Uploads chat or browser-annotation attachments (50 MiB cap), atomically storing them in <root>/attachments/<id>/<name> (outside Workspaces so Git stays clean) and returning JSON metadata.
/attachments/{id} GET /attachments/{id}[?download=1] server/node/files/attachments.go: Validates ID format and serves the attachment with private, max-age=31536000, immutable. Orphaned attachments never sent in a message and older than 24 hours are cleaned up by Sweep on Node restart.

Clone this wiki locally