// 1. Accept POST request with RunAgentInput
app.post('/agent', async (req, res) => {
const input: RunAgentInput = req.body;
// 2. Set up Server-Sent Events
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// 3. Create event encoder
const encoder = new EventEncoder();
try {
// 4. Emit RUN_STARTED
res.write(encoder.encode({
type: EventType.RUN_STARTED,
threadId: input.threadId,
runId: input.runId
}));
// 5. Process request and stream response
// ... your agent logic here ...
// 6. Emit RUN_FINISHED
res.write(encoder.encode({
type: EventType.RUN_FINISHED,
threadId: input.threadId,
runId: input.runId
}));
res.end();
} catch (error) {
// 7. Handle errors with RUN_ERROR
res.write(encoder.encode({
type: EventType.RUN_ERROR,
message: error.message
}));
res.end();
}
});