Agent Executor Integration in Practice: From Protocol Adaptation to Production Rollout
This article presents a practical blueprint for integrating a general-purpose agent executor into a production AI-assisted coding platform. It explains why a working prototype is far from production-ready, then walks through a five-layer architecture, explicit protocol state machine modeling for ACP-style protocols, session pooling with leases and backpressure, distributed runtime concerns such as idempotent submission and event ordering, front-end/back-end contract synchronization, observability and recovery, and a security baseline. A final checklist helps teams turn each new executor from a high-risk change into a low-cost, plugin-style extension.
Agent Executor Integration in Practice: From Protocol Adaptation to Production Rollout
1. Background: Why “It Runs” Is Far From “Production-Ready”
Almost every team building an AI-assisted coding platform faces the same requirement: support local developers on their desktop environments while also enabling team collaboration and elastic cloud scaling. To do this, the platform typically integrates a standardized agent execution engine that handles the real work of code understanding, tool invocation, and task execution, while the platform itself focuses on session orchestration, access control, and artifact management.
The hard part is not “spawn a child process and feed it a prompt.” The hard part is a set of engineering constraints:
- Heterogeneity: Multiple executor types often run in parallel (local CLI, cloud service, in-house), so a unified abstraction is needed to avoid writing separate branching logic for each one.
- Statefulness: Agent sessions are long-lived and context-bearing, so they cannot be retried casually the way stateless HTTP requests can.
- Process cost: Cold-starting an executor process often takes hundreds of milliseconds to several seconds, which is unacceptable overhead under high-frequency interaction.
- Distributed consistency: Sessions may migrate, reconnect, or be observed by multiple front-end tabs at once, so message ordering and identity must remain stable.
- Observability gaps: A child process’s stdout/stderr mixes protocol frames with business logs, making troubleshooting extremely difficult.
This article follows one main thread: integrating a general-purpose agent executor into a backend built on a distributed virtual Actor model, with a React/TypeScript front end. All component names below are illustrative, used to clarify responsibility boundaries, and do not refer to any specific product.
2. Overall Architecture: Splitting Responsibilities Across Five Layers
The core idea is to push protocol complexity down and pull business semantics up. The design has five layers:
- Backend core layer: Implements a unified AI Provider interface as the single entry point for executors, plus a platform configuration object describing the executable path, launch arguments, authentication details, timeout thresholds, and so on.
- Transport layer: A bidirectional frame transport over standard input/output, responsible for line- or length-based framing, JSON encoding/decoding, request-response correlation, and error mapping.
- Protocol adaptation layer: Implements the method semantics for handshake, authentication, session creation, prompt submission, cancellation, and result notification.
- Runtime layer: An Actor (Grain) carries the lifecycle of a single session, with a session pool reusing underlying processes.
- Front-end layer: Executor visual identity, type-mapping adapters, and a real-time message channel that keeps executor identity consistent across the message stream.
The payoff of this split: adding a new executor requires only a Provider implementation and a protocol adapter, with zero changes to the runtime and front end.
[React front end] --SignalR/real-time channel--> [Session Actor] --> [Provider abstraction]|-- Local CLI executor|-- Cloud service executor`-- In-house executor[Session pool] --> [Frame transport] --> [Child process]
3. Protocol Adaptation: Taming an ACP-Style Protocol Into a Controllable State Machine
Take the mainstream Agent-Client Protocol (commonly abbreviated ACP) as an example. Its interaction is essentially one handshake + multiple sessions + a bidirectional event stream. In practice, model it explicitly as a state machine rather than scattering if checks around:
Uninitialized: only handshake methods are allowed.Authenticating: waiting on the credential check result.Ready: sessions can be created.SessionActive: prompts can be submitted, incremental events received, and cancellation initiated.Closing: new requests are rejected while in-flight requests drain.
Key implementation points:
1) Request-response correlation. Every request carries an auto-incrementing id, and the transport layer maintains an id -> PendingRequest map. On receiving a response, resolve or reject it, with a timeout fallback to avoid a “permanent hang.”
2) Separate notifications from requests. Incremental text and tool-call status pushed by the agent are notifications; they carry no id semantics and need a separate event bus to fan out to subscribers.
3) Cancellation must actually take effect. Cancellation is not “discard subsequent messages.” It should send an interrupt signal to the child process and wait for it to converge; otherwise you get a cost black hole where “the front end has stopped but the backend is still burning tokens.”
4) Error normalization. Map process exit codes, protocol parse failures, authentication failures, and upstream rate limiting into a single internal error enum carrying a retryable flag, so upper layers can decide whether to retry or degrade.
// Illustrative: state machine skeleton for the protocol adaptertype Phase = 'init' | 'auth' | 'ready' | 'active' | 'closing';class ProtocolAdapter {private pending = new Map<number, Pending>();constructor(private phase: Phase = 'init') {}async call<T>(method: string, params: unknown, send: SendFn): Promise<T> {const id = nextId();return new Promise<T>((resolve, reject) => {const timer = setTimeout(() => {this.pending.delete(id);reject(new NormalizedError('TIMEOUT', { retryable: true }));}, 30_000);this.pending.set(id, { resolve, reject, timer });send({ jsonrpc: '2.0', id, method, params });});}}
4. Session Pooling: Process Reuse Is the Dividing Line for Performance and Cost
Frequently starting and stopping child processes carries three costs: startup latency, memory jitter, and repeated execution of the authentication flow. The goal of a session pool is to decouple “logical sessions” from “physical processes” and enable many-to-one reuse.
Design points:
- Idle cap and lease mechanism: each rented session carries a lease duration and must be renewed via periodic heartbeats, preventing an abnormal client from holding it indefinitely.
- Sticky routing: keep the same logical session pinned to the same physical process to preserve context continuity; cold-start only when no idle instance is available.
- Health probing: use a lightweight protocol method as a liveness check; mark the instance unavailable and reclaim it after consecutive failures.
- Graceful eviction: prefer evicting the instance that has been idle longest with the shortest context; send a close notification before eviction to give the child process a chance to save its state.
- Backpressure control: queue when the pool is full instead of scaling infinitely; when the queue limit is hit, fail fast and return a clear message to the front end.
// Illustrative: session pool leasing semanticspublic sealed class CliSessionPool{private readonly SemaphoreSlim _gate = new(8, 8);public async Task<ISession> RentAsync(CancellationToken ct){await _gate.WaitAsync(ct);var session = _idle.FirstOrDefault(s => s.IsHealthy);if (session is null) session = await ColdStartAsync(ct); // cold-start pathsession.Lease.Heartbeat();return session;}}
One point deserves emphasis: pooling must align with the Actor lifecycle. When an Actor is deemed unreachable due to a network partition, the session lease it holds must be reclaimable; otherwise “zombie sessions” will keep consuming resources.
5. Distributed Runtime: Session State and Message Ordering
Under the virtual Actor model, each session maps to a stable identity (such as session:{tenant}:{id}), which brings three natural advantages: per-session serialization, automatic state persistence, and cross-node activation.
Practical recommendations:
- Idempotent submission: attach a client-generated idempotency key to each prompt submission so that replays on the Actor side do not trigger duplicate execution.
- Event sequence numbers: maintain a monotonically increasing sequence number for the session event stream so the front end can deduplicate and backfill, avoiding scrambled messages after a reconnect.
- Reminder-driven timeouts: implement idle session reclamation and long-task timeouts with persisted reminders so timing is not lost on process restart.
- Shard affinity: place sessions for the same tenant on the same shard as much as possible to reduce latency from cross-node hops.
6. Keeping the Front-End/Back-End Contract in Sync: The Most Underrated Pitfall
Once the type definitions on the front end and back end drift apart, you get “the field changed but the UI fails silently.” Three hard rules are recommended:
- Single source of truth: use the protocol description file as the only source, generate types separately for the front end and back end, forbid hand-written duplicate definitions, and verify in CI that generated output has no diff.
- Version negotiation: exchange protocol version and capability sets during the handshake, and let the front end degrade rendering based on capabilities (for example, hide the corresponding panel when tool-call visualization is unsupported).
- Contract tests: establish bidirectional validation of request/response samples for key methods, so any breaking change fails the pipeline outright.
// Illustrative: executor type-mapping adapterconst registry: Record<string, ExecutorMeta> = {cli_agent: { label: 'General CLI agent', icon: 'terminal', capabilities: ['tools', 'cancel'] },cloud_agent:{ label: 'Cloud agent', icon: 'cloud', capabilities: ['tools'] },};export const toExecutorMeta = (t: string) => registry[t] ?? fallbackMeta;
The front end must also guarantee identity consistency: message bubbles, avatars, and status badges should all derive from the same executor metadata, so a single session never shows two different visual identities.
7. Observability and Failure Recovery
- Structured logging: split protocol frames from business logs, and record
sessionId,requestId,latency, andtokenUsage; never print full credentials. - Metrics: build in five core metrics — cold-start duration, pool hit rate, in-flight request count, cancellation success rate, and protocol error rate — with monitoring and alerting.
- Tracing: a single prompt submission spans “front end -> Actor -> transport layer -> child process -> upstream model,” tied together by a unified trace identifier.
- Recovery strategy: after a process crash, rebuild context from the “last confirmed event sequence number”; when recovery is impossible, return a clear error to the front end and offer a “create new session” entry point instead of retrying indefinitely.
8. Security and Compliance Baseline
An executor has file system and network access, so it must default to least privilege: a working-directory allowlist, command argument validation, secrets injected via environment variables rather than command-line arguments, and short-lived credentials on the cloud side. All tool calls should include a human confirmation step, and high-risk operations should have an audit trail.
9. Rollout Checklist
- Does the Provider abstraction cover all three contracts: configuration, lifecycle, and errors?
- Is the protocol state machine explicitly modeled, with illegal transitions rejected?
- Does the session pool have leases, health probing, backpressure, and graceful eviction?
- Does cancellation actually propagate to the child process?
- Are front-end and back-end types generated from a single source and verified in CI?
- Do events carry sequence numbers to support deduplication and backfill?
- Are core metrics such as cold-start duration, pool hit rate, and error rate in place?
Conclusion
Bringing an agent executor into a production system is essentially a combined exercise in protocol engineering + resource governance + contract governance. Get these four things right — clear layering, explicit state, proper pooling, and verifiable contracts — and adding a new executor turns from a “high-risk overhaul” into a “low-cost, plugin-style extension.”
