Skip to content

Agent Drivers

root edited this page Dec 4, 2026 · 5 revisions

Agent Drivers

🌐 English · 简体中文

This page documents the Node-side agent driver layer in Trizano: the required and optional driver.Driver / driver.Conn interfaces, the three built-in driver implementations, live capability and rate-limit probing, native session discovery and import, idle reclamation, event normalization, and how to integrate a new ACP-compatible agent. It is aimed at contributors and advanced users customizing agent integrations.

Overall Architecture

For each Session, the Node runs a dedicated actor goroutine (server/node/session/session.go) decoupled from specific agent CLIs via driver.Driver and driver.Conn. Each driver normalizes protocol-specific output into unified timeline items so clients do not need to know which underlying CLI produced them.

flowchart LR
    S["session.Session (actor)"] -->|"Agent / Probe / Start"| D["driver.Driver"]
    S -->|"Send / Interrupt / Answer / Apply"| C["driver.Conn"]
    C -->|"driver.Event (Upsert / Delta / ...)"| S
    D --> CL["claude (stream-json + control_request)"]
    D --> CX["codex (app-server JSON-RPC)"]
    D --> AC["acp (ACP v1 JSON-RPC 2.0)"]
    CX -.shared.-> RPC["driver/rpc"]
    AC -.shared.-> RPC
    D -->|"Interactive()"| T["TerminalService (PTY / tmux / ConPTY)"]
Loading

For the Node daemon and Session actor lifecycle, see Node Internals. For the unified display model and cross-client synchronization, see Architecture and Event Sync.

Core Interfaces and Optional Extensions

The driver contract lives in server/node/driver/driver.go. It consists of two required interfaces—Driver (static discovery and process launch) and Conn (a single running Session process)—plus seven optional capability interfaces that the Session layer activates via type assertions.

Required Interfaces

  • driver.Driver:
    • Agent(ctx) *nodev1.Agent: Lightweight check for the binary path and version (or an unavailability reason); invoked on every refresh.
    • Probe(ctx) (*nodev1.Agent, error): Queries models, options, permission modes, defaults, and slash commands from the CLI without starting a conversation Turn. Results are cached by the manager per CLI version.
    • Start(ctx, spec Spec) (Conn, error): Spawns the agent subprocess. Spec carries the working directory (Cwd), resume handle (Resume), native fork flag (Fork), read-only flag (ReadOnly), settings (Settings: model, mode, Plan, and custom options), and Node-injected environment variables (Env).
    • Interactive() []string: Declares the command line used to launch the agent's native interactive TUI.
  • driver.Conn:
    • Events() <-chan Event and Err() error: Streams normalized events; closes the channel when the process exits, with Err() returning the exit cause.
    • Send(in Input) error: Starts a new Turn. Input accepts text and attachments (images are inlined as base64 within each driver's byte and MIME limits; other files are appended to the prompt as paths).
    • Interrupt() error: Cancels the currently running Turn.
    • Answer(prompt, option, text) error: Responds to an Approval, question, or plan card; returns ErrPromptNotPending if the prompt is no longer active in the driver.
    • Apply(s Settings) <-chan error: Applies model, mode, Plan, or option changes live. If a setting can only take effect by restarting the process (such as toggling Claude extended thinking or Antigravity skip-permissions mode), it returns driver.ErrRestart, and the Session layer restarts and resumes via the native handle automatically.
    • Close() error: Terminates the subprocess.

Optional Extension Interfaces

All optional interfaces are defined in server/node/driver/driver.go and implemented selectively according to each protocol's capabilities:

Interface Implemented On Methods Purpose Implementations
Importer Driver Conversations(ctx, cwd), Read(ctx, cwd, handle) List and replay historical conversations managed by the agent itself acp
RateLimitReader Driver ReadRateLimits(ctx) Actively query subscription rate-limit windows for the current account claude, codex
Tasks Conn StopTask(id), TaskOutput(id) Stop a background task and read its trailing output claude, codex
Steerer Conn Steer(in Input) Inject a mid-turn instruction without interrupting the active Turn (may return ErrSteerQueue to fall back to queuing) claude, codex, Discussion Room Conn
WatchReceiver Conn DeliverWatch(callbacks) Consume watch callbacks while the Session is RUNNING without waiting for idle Discussion Room Conn
Forker Conn Fork(ctx) (string, error) Fork an active Session in place and return a new native handle codex
Rollbacker Conn Rollback(ctx, numTurns) Natively roll back the latest numTurns Turns codex

Note: Claude forks via launch flags (--resume <id> --fork-session) rather than Forker. For drivers that do not implement Steerer, steering interrupts the active Turn and re-sends immediately at the Session layer.

Built-in Driver Implementations

The Node registers driver factories in factories() (server/node/settings.go): claude, codex, and every built-in ACP agent in acp.Agents. Executable paths for all drivers can be overridden in Node settings.

claude (server/node/driver/claude/)

The Claude driver launches the claude CLI directly and communicates bidirectionally over stdio, using the stream-json and control protocol underlying the Claude Agent SDK:

  • Launch flags: claude -p --output-format stream-json --verbose --input-format stream-json --permission-prompt-tool=stdio --include-partial-messages --thinking-display summarized, appending --model, --effort, --settings '{"fastMode":...}', --permission-mode, --thinking disabled, and --session-id / --resume / --fork-session per Spec. Read-only Sessions additionally pass --disallowedTools Edit,Write,NotebookEdit.
  • Control protocol: Outgoing control_request frames cover initialize, get_settings, set_model, set_permission_mode, apply_flag_settings, interrupt, stop_task, and get_usage. Incoming control_request frames from the CLI cover tool Approvals (can_use_tool) and structured forms (elicitation), answered via control_response. Mid-turn steering sends a user message frame with priority: "now".
  • Background subagent continuation: When the primary result arrives while background subagents (TASK_KIND_AGENT with background=true) are still running, the driver holds off emitting TurnEnded. It finishes the Turn and accumulates usage only after subagent completions trigger origin=task-notification continuations and no background subagents remain active. Background shell tasks do not block Turn completion.
  • Root-user branch (server/node/driver/claude/catalog.go): Claude Code refuses to skip permission checks when running as root by default. The driver checks asRoot = os.Geteuid() == 0; when running as root, bypassPermissionsAvailable() exposes bypassPermissions and passes --allow-dangerously-skip-permissions only if the process or Session environment sets IS_SANDBOX=1 or a truthy CLAUDE_CODE_BUBBLEWRAP (1/true/yes/on), hiding the mode otherwise.

codex (server/node/driver/codex/)

The Codex driver runs codex app-server and exchanges JSONL JSON-RPC messages (omitting the "jsonrpc" field) over stdio through the shared server/node/driver/rpc package:

  • Handshake and Turns: Calls initialize, sends the initialized notification, reads config/read, and invokes thread/start or thread/resume. Messages use turn/start, steering uses turn/steer, cancellation uses turn/interrupt, live setting updates use thread/settings/update, and fork/rollback use thread/fork and thread/revert.
  • Permission mode mapping (server/node/driver/codex/settings.go): Exposes four modes: read-only (read-only sandbox, untrusted), default (workspace-write, on-request), auto (workspace-write + auto_review reviewer), and full-access (danger-full-access with fine-grained approval policy while preserving MCP elicitation prompts).
  • Background tasks: Only background shell commands declare Task.stoppable = true and support stopping and reading output through the Tasks interface.

acp (server/node/driver/acp/)

The ACP driver implements an Agent Client Protocol v1 client, sharing server/node/driver/rpc with codex (ACP includes "jsonrpc": "2.0"), to support any coding agent that speaks ACP.

Built-in registrations live in the Agents slice in server/node/driver/acp/acp.go:

Agent ID Display Name Default Command & Args Default Injected / Scrubbed Env (Env)
antigravity Antigravity agy acp AGY_CLI_DISABLE_AUTO_UPDATE=true
opencode OpenCode opencode acp OPENCODE_CLIENT=acp, OPENCODE_ENABLE_QUESTION_TOOL=false
copilot GitHub Copilot copilot --acp -COPILOT_ALLOW_ALL (removed before launch)

Key implementation details:

  • Opening and resuming Sessions: After initialize, the driver prefers session/resume when advertised, then session/load (ignoring replayed session/update frames during load so already-persisted Node items are not duplicated), falling back to session/new with a notice if neither is available or both fail.
  • Permissions and forms: The client does not advertise filesystem or terminal proxy capabilities; agents use their own tools and emit session/request_permission (plus optional elicitation forms), mapped to Prompt cards. Pending requests are cancelled per protocol on Turn end or interruption.
  • Configuration negotiation: Parses configOptions (matching category or id such as model, mode, thought_level, thinking, model_config, with fallback for legacy models/modes), dynamically updating available options via driver.Catalog and driver.Selection.
  • Antigravity specifics: Automatically passes <root>/orch/ via --add-dir into the sandbox so the agent can invoke "$TRIZANO_CLI" directly, supports injecting orchestration guidance via systemPrompt.append, and provides a dangerously-skip-permissions mode (returning ErrRestart when toggled so the Session restarts and resumes).

Shared JSON-RPC Layer (server/node/driver/rpc/rpc.go)

rpc.Peer implements newline-delimited bidirectional JSON-RPC: it correlates requests and responses via an atomically incremented ID, dispatches peer-initiated requests and notifications to rpc.Handler, and wakes pending calls immediately on subprocess exit or context cancellation (returning rpc.ErrExited or ctx.Err()). Non-JSON stdout noise occasionally printed by CLIs or late responses are logged at debug level and skipped by Dispatch without terminating a live Session.

Capability Probing and Rate-Limit Queries

Model lists, reasoning effort levels, Fast/service tiers, permission modes, and slash commands are always probed live from the CLI—never hardcoded in the Node or clients.

Capability Probing (probe.go per driver)

The Node manager (server/node/session/manager.go) calls each driver's Probe(ctx) asynchronously at startup and on refresh, caching catalogs per CLI version for up to catalogMaxAge = 1h. Default probe timeouts are 20s for claude, 15s for codex, and 45s for acp.

  • Claude (server/node/driver/claude/probe.go): Starts an ephemeral, non-persistent process in a temporary directory (--no-session-persistence --strict-mcp-config --settings '{"disableAllHooks":true}' --permission-mode default) and sends initialize and get_settings concurrently to extract models, effort levels, Fast, Ultracode, extended thinking toggle, and slash commands.
  • Codex (server/node/driver/codex/probe.go): Starts a short-lived codex app-server and calls model/list (paginated), config/read, account/read, and optional collaborationMode/list and skills endpoints to map reasoningEffort, serviceTier, Plan mode support, and sign-in warnings.
  • ACP (server/node/driver/acp/probe.go): Launches the CLI in a persistent probe directory, calling initialize and session/new (error code -32000 reports a sign-in warning). When a model config option exists, it iterates through models within a 30s learnBudget to discover per-model options, restores the default model, and cleans up with session/delete or session/close.

Rate-Limit Queries

Drivers can optionally implement driver.RateLimitReader. A single-owner Node goroutine (rateLimits in server/node/rate_limits.go) maintains snapshots:

  • Claude (server/node/driver/claude/rate_limits.go): Reuses probeControl to send initialize + get_usage, fetching 5-hour, 7-day, per-model quotas, and monthly extra usage; live Sessions passively merge rate_limit_event frames.
  • Codex (server/node/driver/codex/rate_limits.go): Spawns a short-lived codex app-server to call account/read + account/rateLimits/read; API-key accounts are marked USAGE_BILLED; live Sessions passively update from account/rateLimits/updated.
  • Refresh policy: Updated only on Node startup, Turn end, passive events, or explicit UsageService.GetRateLimits(refresh=true) calls—never via background polling. Each read times out after 20s; failures preserve the previous window and mark status as ERROR.

Native TUI (Interactive())

Opening an agent's native terminal UI is not a separate driver—it reuses the Node terminal service (TerminalService.CreateTerminal). The Session manager calls driver.Interactive() to get the command (such as ["claude"], ["codex"], ["agy"], ["opencode"], or ["copilot"]) and launches the native TUI in a Workspace PTY. It shares the 256 KiB scrollback snapshot, WebSocket bridge, and Unix tmux persistence with regular shell terminals. See Node Internals and Daily Use.

Native Session Discovery and Import

Trizano can import historical conversations started outside the Trizano UI on the Node host into regular, resumable Trizano Sessions (server/node/session/discover.go):

  • Discovery (DiscoverNativeSessions):
    • Claude Code and Codex: Scans on-disk transcripts read-only (~/.claude/projects/*/*.jsonl and ~/.codex/sessions/**) matching the normalized Workspace path without spawning any subprocess. Files modified within the last 3 seconds are flagged as active.
    • ACP agents: Calls Conversations(ctx, cwd) in parallel on enabled drivers implementing driver.Importer, listing via session/list and filtering by Workspace path in the Session layer. Agents that do not advertise list + loadSession or are not signed in return no entries.
  • Import and incremental refresh (ImportNativeSession):
    • On first import, Claude/Codex transcripts are parsed locally while ACP invokes driver.Importer.Read (session/load), passing through the same event normalization pipeline to produce historical Items. The Node creates a regular IDLE Session bound to native_handle; sending a new message resumes the conversation natively.
    • If the native Session was already imported and refresh=true is requested, the Node requires the Session not to be running, re-reads native history, appends only items missing from sess.index, increments rev, and broadcasts ItemsChanged for incremental sync.

Idle Reclamation

To keep long-running Nodes from exhausting memory, process slots, or inotify watches across historical and delegated Sessions, session.Session (server/node/session/session.go) enforces two idle timers:

  • Timeline memory eviction (timelineIdle = 5m): At startup, the Node loads only Session metadata; timelines load on demand from SQLite. A Session with no live agent process evicts its in-memory timeline after 5 minutes without access (lightweight operations like listing, pinning, archiving, and snapshots use the look() path and do not wake the timeline).
  • Agent process shutdown (agentIdle = 30m): When a Session is not RUNNING and has no active background tasks, 30 minutes with neither agent output nor Session requests shuts down the subprocess and frees the in-memory timeline. The next message automatically respawns and resumes using the persisted native_handle.

Event Normalization into Items

Drivers translate CLI output into driver.Event, and the Session actor normalizes, batches, persists, and broadcasts them in Session.apply() (server/node/session/session.go):

  1. Driver event kinds: Upsert (insert or replace an item), Delta (append streaming text to an item), Handle (persist native resume handle), Catalog/Selection (update available options and current selection), Context (context window usage), TaskUpdate, Commands, RateLimits, and TurnEnded (close the Turn with token, cost, and throughput totals).
  2. Unified Item model (proto/trizano/node/v1/item.proto): Every item has a per-Session id, turn, timestamp, and optional parent_tool_id (nesting native subagent steps under their parent tool call). Its body covers UserMessage, AssistantText, Reasoning (the Node computes duration when reasoning finishes), ToolCall (ShellDetail, FileChangesDetail, SubagentDetail), Prompt (tool Approval, question, plan), TodoList, Notice, TurnEnd, and Discussion Room items.
  3. 50 ms streaming batching: Delta chunks are not broadcast character by character. They accumulate in memory for up to streamWindow = 50ms and flush as a single ItemDelta per item; any non-Delta event or incoming request flushes immediately so streaming deltas stay strictly ordered with rev.

Adding a New ACP Agent

If a coding CLI implements standard ACP (JSON-RPC 2.0 over stdio), integrating it usually takes only a small set of registrations:

  1. Register the ACP agent: Append an Agent{ID, Title, Command, Args, Env, ProbeEnv} entry to Agents in server/node/driver/acp/acp.go. factories() in server/node/settings.go iterates over acp.Agents automatically—no routing or protobuf changes are needed.
  2. Verify mode levels and usage accounting (if needed):
    • If the agent uses mode IDs not covered by modeLevel() in server/node/driver/acp/config.go, map them to ModeLevel (READ_ONLY/ASK/ACCEPT_EDITS/AUTO/FULL_ACCESS) so Delegation and read-only Discussion Rooms pick the right mode.
    • If the agent's session/prompt response reports usage.inputTokens excluding cached tokens and omits totalTokens, add its agentID to normalizeACPUsage() in acp.go.
  3. Register #agent delegation aliases (if needed): Add the agent ID to builtinAgentIDs (and optional aliases) in server/node/session/policy.go so #node/agent mention rewriting recognizes it.
  4. Add client brand icons (optional): Add an icon in web/src/components/AgentIcon.tsx (Web/desktop) and android/app/src/main/kotlin/top/onemolchuan/code/ui/AgentBrand.kt (Android); otherwise clients fall back to a generic icon.
  5. Rebuild and verify: Follow Development to rebuild trizano-h3 (including bin/dist/*) and test Probe, chat, Approvals, and native import.

Clone this wiki locally