Event handlers are the main way to observe what the relay is doing in real time. Attach callbacks to the AgentRelay instance to log activity, update UI, trigger follow-up work, or keep your own state in sync.
Basic pattern
Assign a function to subscribe. Set the handler back to null / None to clear it.
const relay = new AgentRelay();
relay.onMessageReceived = (msg) => {
console.log(`${msg.from} -> ${msg.to}: ${msg.text}`);
};
relay.onAgentReady = (agent) => {
console.log(`ready: ${agent.name}`);
};Message handlers
Use these when you want to react to communication events.
relay.onMessageReceived = (msg) => {
console.log('received', msg.threadId, msg.text);
};
relay.onMessageSent = (msg) => {
console.log('sent', msg.to, msg.text);
};onMessageReceived/on_message_received: fires when the relay delivers a message into your session.onMessageSent/on_message_sent: fires after your app or agent sends a message through the relay.
Agent lifecycle handlers
Use lifecycle handlers when you care about worker state transitions.
relay.onAgentSpawned = (agent) => {
console.log(`spawned: ${agent.name}`);
};
relay.onAgentReady = (agent) => {
console.log(`ready: ${agent.name}`);
};
relay.onAgentReleased = (agent) => {
console.log(`released: ${agent.name}`);
};
relay.onAgentExited = (agent) => {
console.log(`exited: ${agent.name}`, agent.exitCode, agent.exitSignal);
};
relay.onAgentExitRequested = ({ name, reason }) => {
console.log(`exit requested: ${name}`, reason);
};
relay.onAgentIdle = ({ name, idleSecs }) => {
console.log(`idle: ${name}`, idleSecs);
};These hooks are useful for status dashboards, retry logic, timeout nudges, and cleanup when a worker finishes or requests exit.
Output and delivery handlers
Use these when you need low-level visibility into what the relay is streaming.
relay.onWorkerOutput = ({ name, stream, chunk }) => {
console.log(`[${name}] ${stream}: ${chunk}`);
};
relay.onDeliveryUpdate = (event) => {
console.log('delivery update', event.type, event);
};onWorkerOutput/on_worker_output: raw stdout or stderr from a worker.onDeliveryUpdate/on_delivery_update: broker-level delivery events when you need transport visibility.
Good uses for handlers
- Update a UI timeline or status panel without polling.
- Capture logs and metrics while agents run.
- Trigger follow-up work when a message arrives or a worker becomes ready.
- Detect exit conditions and clean up local resources.