Repository navigation
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.
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)"]
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.
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.
-
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.Speccarries 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 EventandErr() error: Streams normalized events; closes the channel when the process exits, withErr()returning the exit cause. -
Send(in Input) error: Starts a new Turn.Inputaccepts 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; returnsErrPromptNotPendingif 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 returnsdriver.ErrRestart, and the Session layer restarts and resumes via the native handle automatically. -
Close() error: Terminates the subprocess.
-
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.
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.
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-sessionperSpec. Read-only Sessions additionally pass--disallowedTools Edit,Write,NotebookEdit. -
Control protocol: Outgoing
control_requestframes coverinitialize,get_settings,set_model,set_permission_mode,apply_flag_settings,interrupt,stop_task, andget_usage. Incomingcontrol_requestframes from the CLI cover tool Approvals (can_use_tool) and structured forms (elicitation), answered viacontrol_response. Mid-turn steering sends a user message frame withpriority: "now". -
Background subagent continuation: When the primary
resultarrives while background subagents (TASK_KIND_AGENTwithbackground=true) are still running, the driver holds off emittingTurnEnded. It finishes the Turn and accumulates usage only after subagent completions triggerorigin=task-notificationcontinuations 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 checksasRoot = os.Geteuid() == 0; when running as root,bypassPermissionsAvailable()exposesbypassPermissionsand passes--allow-dangerously-skip-permissionsonly if the process or Session environment setsIS_SANDBOX=1or a truthyCLAUDE_CODE_BUBBLEWRAP(1/true/yes/on), hiding the mode otherwise.
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 theinitializednotification, readsconfig/read, and invokesthread/startorthread/resume. Messages useturn/start, steering usesturn/steer, cancellation usesturn/interrupt, live setting updates usethread/settings/update, and fork/rollback usethread/forkandthread/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_reviewreviewer), andfull-access(danger-full-accesswith fine-grained approval policy while preserving MCP elicitation prompts). -
Background tasks: Only background shell commands declare
Task.stoppable = trueand support stopping and reading output through theTasksinterface.
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 preferssession/resumewhen advertised, thensession/load(ignoring replayedsession/updateframes during load so already-persisted Node items are not duplicated), falling back tosession/newwith 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 optionalelicitationforms), mapped toPromptcards. Pending requests are cancelled per protocol on Turn end or interruption. -
Configuration negotiation: Parses
configOptions(matchingcategoryoridsuch asmodel,mode,thought_level,thinking,model_config, with fallback for legacymodels/modes), dynamically updating available options viadriver.Cataloganddriver.Selection. -
Antigravity specifics: Automatically passes
<root>/orch/via--add-dirinto the sandbox so the agent can invoke"$TRIZANO_CLI"directly, supports injecting orchestration guidance viasystemPrompt.append, and provides adangerously-skip-permissionsmode (returningErrRestartwhen toggled so the Session restarts and resumes).
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.
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.
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 sendsinitializeandget_settingsconcurrently to extract models, effort levels, Fast, Ultracode, extended thinking toggle, and slash commands. -
Codex (
server/node/driver/codex/probe.go): Starts a short-livedcodex app-serverand callsmodel/list(paginated),config/read,account/read, and optionalcollaborationMode/listand skills endpoints to mapreasoningEffort,serviceTier, Plan mode support, and sign-in warnings. -
ACP (
server/node/driver/acp/probe.go): Launches the CLI in a persistent probe directory, callinginitializeandsession/new(error code-32000reports a sign-in warning). When amodelconfig option exists, it iterates through models within a 30slearnBudgetto discover per-model options, restores the default model, and cleans up withsession/deleteorsession/close.
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): ReusesprobeControlto sendinitialize+get_usage, fetching 5-hour, 7-day, per-model quotas, and monthly extra usage; live Sessions passively mergerate_limit_eventframes. -
Codex (
server/node/driver/codex/rate_limits.go): Spawns a short-livedcodex app-serverto callaccount/read+account/rateLimits/read; API-key accounts are markedUSAGE_BILLED; live Sessions passively update fromaccount/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 asERROR.
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.
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/*/*.jsonland~/.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 implementingdriver.Importer, listing viasession/listand filtering by Workspace path in the Session layer. Agents that do not advertiselist+loadSessionor are not signed in return no entries.
-
Claude Code and Codex: Scans on-disk transcripts read-only (
-
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 historicalItems. The Node creates a regularIDLESession bound tonative_handle; sending a new message resumes the conversation natively. - If the native Session was already imported and
refresh=trueis requested, the Node requires the Session not to be running, re-reads native history, appends only items missing fromsess.index, incrementsrev, and broadcastsItemsChangedfor incremental sync.
- On first import, Claude/Codex transcripts are parsed locally while ACP invokes
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 thelook()path and do not wake the timeline). -
Agent process shutdown (
agentIdle = 30m): When a Session is notRUNNINGand 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 persistednative_handle.
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):
-
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, andTurnEnded(close the Turn with token, cost, and throughput totals). -
Unified
Itemmodel (proto/trizano/node/v1/item.proto): Every item has a per-Sessionid,turn, timestamp, and optionalparent_tool_id(nesting native subagent steps under their parent tool call). ItsbodycoversUserMessage,AssistantText,Reasoning(the Node computesdurationwhen reasoning finishes),ToolCall(ShellDetail,FileChangesDetail,SubagentDetail),Prompt(tool Approval, question, plan),TodoList,Notice,TurnEnd, and Discussion Room items. -
50 ms streaming batching:
Deltachunks are not broadcast character by character. They accumulate in memory for up tostreamWindow = 50msand flush as a singleItemDeltaper item; any non-Deltaevent or incoming request flushes immediately so streaming deltas stay strictly ordered withrev.
If a coding CLI implements standard ACP (JSON-RPC 2.0 over stdio), integrating it usually takes only a small set of registrations:
-
Register the ACP agent: Append an
Agent{ID, Title, Command, Args, Env, ProbeEnv}entry toAgentsinserver/node/driver/acp/acp.go.factories()inserver/node/settings.goiterates overacp.Agentsautomatically—no routing or protobuf changes are needed. -
Verify mode levels and usage accounting (if needed):
- If the agent uses mode IDs not covered by
modeLevel()inserver/node/driver/acp/config.go, map them toModeLevel(READ_ONLY/ASK/ACCEPT_EDITS/AUTO/FULL_ACCESS) so Delegation and read-only Discussion Rooms pick the right mode. - If the agent's
session/promptresponse reportsusage.inputTokensexcluding cached tokens and omitstotalTokens, add itsagentIDtonormalizeACPUsage()inacp.go.
- If the agent uses mode IDs not covered by
-
Register
#agentdelegation aliases (if needed): Add the agent ID tobuiltinAgentIDs(and optionalaliases) inserver/node/session/policy.goso#node/agentmention rewriting recognizes it. -
Add client brand icons (optional): Add an icon in
web/src/components/AgentIcon.tsx(Web/desktop) andandroid/app/src/main/kotlin/top/onemolchuan/code/ui/AgentBrand.kt(Android); otherwise clients fall back to a generic icon. -
Rebuild and verify: Follow Development to rebuild
trizano-h3(includingbin/dist/*) and testProbe, chat, Approvals, and native import.
English
Getting Started
Deployment & Networking
Architecture & Nodes
Agents
Clients & Development
Project & Community
中文文档
新手指引
部署与网络
架构与节点
智能体
客户端与开发
项目与社区