Skip to content

Orchestration

root edited this page Dec 4, 2026 · 4 revisions

Multi-Agent Orchestration

🌐 English · 简体中文

This page explains how Trizano handles multi-agent Delegation and cross-Node orchestration: injected environment variables and managed skills, the trizano-h3 orchestration CLI and built-in MCP server, socket isolation and hop limits, cross-Node forwarding over the control bridge, watch callbacks, Git worktree isolation, cross-Node handoffs, and read-only write interception. It is intended for contributors and power users.

End-to-End Path

Agents inside a Session never connect directly to the Hub or other hosts. Instead, they talk to their local Node over an isolated orchestration Unix socket (~/.trizano/node/orch/s.sock). Same-Node actions execute locally; cross-Node calls are forwarded by the Node over the Hub-initiated SystemService.OpenControlBridge bidirectional stream to the target Node.

flowchart LR
    A["Agent subprocess ($TRIZANO_CLI / mcp)"] -->|"POST /internal/orch/{method} + Bearer Token"| S["orch/s.sock (Node)"]
    S -->|"Same Node"| LM["Local session.Manager"]
    S -->|"Cross-Node (hop < 1)"| CB["SystemService.OpenControlBridge"]
    CB <-->|"Bidi stream"| H["Hub (server/hub/orch.go)"]
    H -->|"Connect RPC"| RN["Target Node (trizano-h3)"]
    RN -.->|"watch callback / cross-Node delivery"| H
Loading

For Node dual-socket isolation and Hub proxy restrictions, see Security and Network Topology. For structured multi-agent workflows governed by scripts, see Discussion Rooms.

Environment Injection and Managed Skills

When the Node spawns any agent subprocess, it injects the orchestration runtime context and writes a managed trizano-delegation skill into standard agent skill directories so agents can discover and invoke delegation commands out of the box.

Injected Environment Variables (server/node/session/manager.go)

Variable Value / Source Purpose
TRIZANO_CLI <node-root>/orch/trizano-h3 (.exe on Windows) Standalone copy of the CLI staged at daemon startup so sandboxes only need to mount orch/
TRIZANO_SOCKET <node-root>/orch/s.sock Mode-0600 orchestration Unix socket exposing only /internal/orch/*
TRIZANO_SESSION sessions/<id> Resource name of the current Session
TRIZANO_SESSION_TOKEN mc_<payload>.<mac> HMAC-SHA256 token bound to the current Session and hop count (must never be printed)
TRIZANO_NODE Current Node's ID on the Hub Injected once the Node has connected to a Hub and learned its Node ID

Managed Skill (server/node/skills.go)

On startup, ensureDelegationSkills() atomically writes the embedded trizano-delegation SKILL.md into two locations:

  • ~/.claude/skills/trizano-delegation/SKILL.md
  • ~/.agents/skills/trizano-delegation/SKILL.md

A sibling .trizano-sha256 file records the hash of the last written content. After a Node upgrade, the file is updated only if the existing SKILL.md still matches .trizano-sha256; manual user edits are never overwritten.

Additionally, typing #claude, #vps-1/codex, or inserting Session chips in the composer triggers RewriteDelegationMentions() (server/node/session/policy.go) before dispatch, rewriting them into explicit $TRIZANO_CLI delegation instructions.

Orchestration CLI: trizano-h3 nodes|delegate|thread

Orchestration subcommands live in server/cmd/trizano-h3/orch_cli.go. Every command calls /internal/orch/{method} over $TRIZANO_SOCKET and prints indented JSON. Session references (<ref>) accept sessions/<id>, <node>/sessions/<id>, or trizano-session://<node>/sessions/<id>.

Subcommand Reference

Command Key Flags Purpose
nodes None List all online machines, Workspaces, and available agents on the Hub (falls back to the local Node when offline)
delegate start --agent (required), --task (required, or positional), --node, --workspace, --model, --mode, --task-name, --worktree <branch>, --base <ref>, --watch, --note Spawn a real Subagent session and start executing; records a TOOL_KIND_TASK pointer item in the parent timeline
thread list --node, --parent <sessions/...> List unarchived Sessions, optionally filtered by Node or parent Session
thread read <ref> --messages, --from N, --to M Read the latest result, pending prompts, or historical messages by 1-based Turn range
thread wait <ref> --timeout (default 5m) Poll (every 250 ms) until the target leaves running or surfaces a pending prompt
thread send <ref> --text (or positional), --interrupt, --watch, --note Send a follow-up message to a Subagent session, optionally interrupting the current Turn and attaching a watch
thread answer <ref> --item (required), --option (defaults to primary allow/submit option), --text, --answers-json Respond to an Approval, plan, or question card on a Subagent session
thread cancel <ref> None Interrupt the currently running Turn of the target Session
thread archive <ref> None Archive an idle Subagent session spawned by the current Session, releasing its process and unsubscribing watches
thread watch <ref> --note Explicitly subscribe to a running Turn until completion
thread unwatch <ref> or --id <watch-id> [--node <node-id>] Unsubscribe an active or unreachable watch
thread watches None List all watches registered by the current Session

Practical Examples

# 1. Inspect all online Nodes, Workspaces, and available agents
"$TRIZANO_CLI" nodes

# 2. Delegate two parallel coding tasks locally in isolated Git worktrees with --watch
"$TRIZANO_CLI" delegate start \
  --agent claude --task-name "Fix auth boundary" \
  --worktree fix/auth-edge --watch \
  --task "Audit and fix the replay-window edge case in server/hub/auth, and add unit tests."

"$TRIZANO_CLI" delegate start \
  --agent codex --task-name "Add contract tests" \
  --worktree test/auth-contract --watch \
  --task "Add integration tests for ticket expiry and revocation under server/hub."

# 3. Delegate across Nodes (pass --workspace if the target Node has multiple Workspaces)
"$TRIZANO_CLI" delegate start \
  --node gpu-box --workspace workspaces/ml-app \
  --agent codex --watch \
  --task "Run the benchmark suite and summarize VRAM usage."

# 4. Read results, answer an Approval, and archive the Subagent session
"$TRIZANO_CLI" thread read gpu-box/sessions/abc123 --messages --from 1 --to 3
"$TRIZANO_CLI" thread answer gpu-box/sessions/abc123 --item perm-1 --option allow
"$TRIZANO_CLI" thread archive gpu-box/sessions/abc123

The managed skill also instructs parent agents to link results with [task name](trizano-session://<node>/sessions/<id>), which clients render as live status pills that open the Subagent session timeline on click.

Subagent session tree and isolated Worktree branches

Built-in MCP Server: trizano-h3 mcp

In addition to the CLI, trizano-h3 mcp (server/cmd/trizano-h3/mcp.go) serves standard MCP over stdio (JSON-RPC 2.0, protocol version 2024-11-05, server name trizano-orchestration), backed by the same callOrch() transport. Incoming tools/call requests dispatch concurrently so a long-running trizano_thread_wait never blocks ping or parallel tool calls.

MCP Tool Orchestration Method Required Arguments
trizano_nodes nodes.list None
trizano_delegate_start delegate.start agent, task
trizano_thread_list thread.list None
trizano_thread_read thread.read ref
trizano_thread_wait Polls thread.read ref
trizano_thread_send thread.send ref, text
trizano_thread_answer thread.answer ref, item
trizano_thread_cancel thread.cancel ref
trizano_thread_archive thread.archive ref
trizano_thread_watch thread.watch ref
trizano_thread_unwatch thread.unwatch None (pass ref or watchId)
trizano_thread_watches thread.watches None
trizano_discuss_start discuss.start topic, participants
trizano_discuss_post discuss.post ref
trizano_discuss_read discuss.read ref
trizano_discuss_stop discuss.stop ref

See Discussion Rooms for parameters and usage of the four trizano_discuss_* tools.

Socket Isolation, HMAC Tokens, and Cross-Node Bridge

The orchestration API is strictly separated from the owner admin channel. All request and response wire structs (covering 16 method constants) live in server/internal/orch/orch.go.

Isolated Channel and Auth (server/node/orch_http.go, server/node/session/token.go)

  • Dedicated endpoint: POST /internal/orch/{method} (2 MiB request body limit) is mounted exclusively on <root>/orch/s.sock—never on the owner socket run/node.sock or reverse connectors. The Hub reverse proxy also rejects external requests to /nodes/{node}/internal/* and sensitive RPCs such as SystemService/OpenControlBridge with HTTP 403.
  • HMAC session token: TokenIssuer generates a fresh 32-byte random key on every Node start, issuing tokens formatted as mc_<base64url(sessionName|hopCount)>.<base64url(HMAC-SHA256)> verified in constant time. Agents cannot forge their caller Session name or tamper with hop counts.
  • Cross-Node hop limit: orch.MaxCrossNodeHops = 1. Both the originating Node and the Hub enforce hopCount < MaxCrossNodeHops. Remote delegated Subagent sessions have their HopCount incremented to 1, preventing them from delegating across machines again and eliminating cross-Node loops.
  • Default mode and model selection (server/node/session/policy.go): ResolveDelegationMode resolves in order: explicit --mode → Node's configured delegation default mode → target agent's auto / auto-edit tier mode → agent default mode, never silently escalating to full-access. ResolveDelegationModel resolves: explicit --model → Node delegation default model → agent default model.

ControlBridge Cross-Node Forwarding (server/node/bridge.go, server/hub/orch.go)

When a Node connects to an Entry, the Entry opens a SystemService.OpenControlBridge bidirectional stream to the Node.

  • Multi-Entry resilience: On the Node side, controlBridge keeps the latest control bridge per BridgeHello.entry_id. Cross-Node calls try active bridges newest-first and automatically fall over to the next Entry if one returns Unavailable (see Multi-Entry & Failover).
  • Retryable Unavailable: When bridgeNodeClient() (server/hub/orch.go) cannot find the target Node in the registry (originally NotFound), it deliberately translates the error into connect.CodeUnavailable so callers such as watch delivery treat it as transient downtime and keep retrying rather than giving up permanently.
  • Cross-Node archive verification: When forwarding thread.archive, the Hub verifies the target Subagent session's parent against the bridge's fromNodeID and callerSession so a Session cannot archive unrelated Sessions.

Watch Callback Mechanism

Passing --watch lets a parent Session dispatch multiple Subagent sessions and finish its Turn immediately; the Node wakes the parent automatically when children reach notable states (server/node/session/watch.go).

sequenceDiagram
    participant P as Parent Session
    participant W as watchManager
    participant C as Subagent Session
    P->>C: SendMessage returns turn_seq
    P->>W: WatchSession (armed_turn = turn_seq)
    C-->>W: State change (needs_input / 15m no progress)
    W->>P: DeliverWatchNotice (intermediate, watch stays active)
    C-->>W: Turn finished (completed / failed / interrupted)
    W->>P: DeliverWatchNotice (terminal)
    W->>W: Delete watch record after delivery
Loading

Key behaviors and parameters:

  • Level-triggered reconciliation: When delegating or sending with --watch, the Node sends the message first to obtain its monotonically increasing turn_seq, then registers and persists the watch in SQLite with armed_turn = turn_seq. Even if the child finishes before registration completes, no callback is lost.
  • Intermediate notices keep the watch armed:
    • needs_input: Fires when the child raises an Approval or question card, including the prompt title, item_id, and selectable option IDs in the notice body. After calling thread answer, the parent does not need to re-watch.
    • stalled: Fires after stallAfter = 15m with no output or state progress since the child's last activity (instead of enforcing a rigid wall-clock cutoff).
  • Terminal cleanup and batching: Once the child reaches completed, failed, or interrupted, successful delivery deletes the watch record. If the parent is currently busy, multiple ready callbacks accumulate and coalesce into a single continuation Turn once the parent becomes idle (Discussion Rooms implementing driver.WatchReceiver consume callbacks directly while RUNNING).
  • Retries and expiration: Cross-Node delivery or busy parents retry every 2s (watchRetryInterval). After the 6h delivery window (defaultDeliveryWindow) or a permanent error (e.g., deleted parent Session), the record is marked undeliverable; the Node retains up to 50 recent undeliverable records for troubleshooting.

--worktree Isolation

When multiple Subagent sessions need to edit the same Git repository concurrently, passing --worktree <branch> (with optional --base <ref>, defaulting to HEAD) gives each one an isolated Git worktree (server/node/git/worktree.go):

  • Worktree paths anchor beside the main repository: <dirname(main)>/<basename(main)>.worktrees/<sanitized-branch> (for example, review/auth-check maps to app.worktrees/review-auth-check), even when triggered from inside an existing linked worktree.
  • git worktree add -b <branch> explicitly disables core.fsmonitor and Git hooks (core.hooksPath=/dev/null), and never copies uncommitted dirty changes from the main tree.
  • If the repository is mid-merge/rebase, has unresolved conflicts, or the target branch/directory already exists, the Node rejects the call with the corresponding Connect error code.

Cross-Node Handoff (HandoffSession)

Cross-Node handoff transfers an existing Session's context to another agent on the same or a different Node, orchestrated by OrchestrationService.HandoffSession (server/hub/orch.go) and packaged by server/node/session/handoff.go:

  1. Deterministic zero-LLM packaging: The source Node runs BuildHandoffContext (BuildHandoff) to extract Turns up to cutoff_turn (0 = latest completed Turn) into <handoff_context>, strictly capped at 16,000 UTF-8 bytes (table of contents, plan summaries, recent Q&A, file-edit/command activity, and Discussion Room DiscussionEntry items).
  2. Back-reference command: The header includes read_more: "$TRIZANO_CLI" thread read <ref> --messages --from <n> --to <m> so the receiving agent can fetch earlier Turn details on demand.
  3. Target Session creation: The Hub calls CreateSession on the target Node (auto-selecting the sole Workspace if target_workspace is omitted and only one exists; otherwise requiring an explicit target), stores <handoff_context> in PendingContext with SessionHandoff metadata, and attaches it automatically on the new Session's first message.

Write Interception for Read-Only Sessions

Read-only Sessions (Session.read_only = true, used by default for Discussion Room participants) enforce a synchronous interception policy at the Session layer (server/node/session/readonly_policy.go) that blocks unintended Workspace edits without bothering you with Approval prompts for read-only exploration:

  • Synchronous auto-answering: Neither sets Attention nor shows an Approval popup.
    • Auto-approved (strictly ALLOW_ONCE, never ALLOW_ALWAYS): TOOL_KIND_READ, TOOL_KIND_SEARCH, TOOL_KIND_FETCH, TOOL_KIND_TASK, ToolSearch, and shell commands verified safe by shellro.IsReadOnly().
    • Auto-denied with guidance: TOOL_KIND_EDIT, PROMPT_KIND_PLAN, tools carrying BypassSandbox/dangerouslyDisableSandbox, shell commands failing the read-only check, and unknown tools.
    • Passed through to the user: Only PROMPT_KIND_QUESTION cards surface for human input.
  • Conservative shell read-only analysis (server/internal/shellro/shellro.go):
    • Lexes quotes and pipeline/logical operators (|, ||, &&, ;), explicitly rejecting newlines, redirections (allowing only standalone 2>/dev/null and 2>&1), command substitutions ($(...) and backticks), and subshells (() / {}).
    • Checks every pipeline segment against an allowlist of programs and a denylist of dangerous flags—for instance, git allows only read-only subcommands (status, diff, log, show, branch/tag/remote queries), and flags enabling in-place writes or command execution in find/sed/uniq are rejected.
  • Mode and orchestration locks: A read_only Session cannot switch to any edit or auto-approval mode (isWriteOrAutoMode). Additionally, orchHandler.forbidOrchMutation() (server/node/orch_http.go) denies all mutating orchestration methods (delegate.start, discuss.{start,post,stop}, thread.{send,answer,cancel,archive,watch}) from read_only Sessions and Discussion Room participants with PermissionDenied.

Clone this wiki locally