Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

Event-Driven Agents

Event-driven agents turn external signals into agent runs. Instead of waiting for a user prompt, the agent starts when a webhook arrives, a file changes, or a message queue delivers a job.

When to use event-driven agents

  • A pull request is opened and you want an automatic code review.
  • A ticket is created and you want the agent to investigate a repository.
  • A monitoring alert fires and you want the agent to gather diagnostics.
  • A file lands in cloud storage and you want the agent to process it.

Architecture

A typical event-driven deployment has three parts:

  1. Event source - a webhook, message queue, file system watcher, or pub/sub topic.
  2. Router - a lightweight worker that validates the event and starts an agent session.
  3. Agent - the Autohand SDK client that streams events and reports results.

The router should be stateless. It validates signatures, extracts identifiers, and hands the rest to the agent.

Webhook example

Validate the incoming event, extract the useful fields, and hand reasoning to Autohand. The same router shape works in workers, web servers, and API handlers.

export default {
  async fetch(request, env) {
    const payload = await request.json();
    if (payload.action !== 'opened') return new Response('Ignored');

    const pr = payload.pull_request;
    const prompt = `Review pull request #${pr.number}: ${pr.title}`;
    const result = await env.AUTOHAND.run({ cwd: '/tmp/repo', prompt });

    await postComment(pr.comments_url, result.text, env.GITHUB_TOKEN);
    return new Response('Review posted');
  }
};
import { AutohandSDK } from '@autohandai/agent-sdk';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const payload = await request.json() as GitHubPullRequestEvent;
    if (payload.action !== 'opened') return new Response('Ignored');

    const sdk = new AutohandSDK({ cwd: '/tmp/repo', apiKey: env.AUTOHAND_KEY });
    const result = await sdk.run(`Review pull request #${payload.pull_request.number}`);
    await postComment(payload.pull_request.comments_url, result.text, env.GITHUB_TOKEN);

    return new Response('Review posted');
  }
};
from fastapi import FastAPI, Request
from autohand_sdk import AutohandSDK

app = FastAPI()

@app.post("/github")
async def github_webhook(request: Request):
    payload = await request.json()
    if payload.get("action") != "opened":
        return {"status": "ignored"}

    pr = payload["pull_request"]
    async with AutohandSDK(cwd="/tmp/repo") as sdk:
        result = await sdk.run(f"Review pull request #{pr['number']}: {pr['title']}")
    await post_comment(pr["comments_url"], result.text)
    return {"status": "review_posted"}
func githubWebhook(w http.ResponseWriter, r *http.Request) {
  var payload PullRequestEvent
  json.NewDecoder(r.Body).Decode(&payload)
  if payload.Action != "opened" {
    w.WriteHeader(http.StatusOK)
    return
  }

  sdk := autohand.NewClient(autohand.Config{Cwd: "/tmp/repo"})
  result, _ := sdk.Run(r.Context(), fmt.Sprintf("Review pull request #%d", payload.PullRequest.Number))
  postComment(payload.PullRequest.CommentsURL, result.Text)
}
@PostMapping("/github")
ResponseEntity<String> githubWebhook(@RequestBody PullRequestEvent payload) {
  if (!payload.action().equals("opened")) {
    return ResponseEntity.ok("ignored");
  }

  var sdk = AutohandClient.builder().cwd("/tmp/repo").build();
  var result = sdk.run("Review pull request #" + payload.pullRequest().number());
  github.postComment(payload.pullRequest().commentsUrl(), result.text());
  return ResponseEntity.ok("review posted");
}
app.post("github") { req async throws -> String in
    let payload = try req.content.decode(PullRequestEvent.self)
    guard payload.action == "opened" else { return "ignored" }

    let sdk = AutohandClient(cwd: "/tmp/repo")
    let result = try await sdk.run("Review pull request #\(payload.pullRequest.number)")
    try await github.postComment(payload.pullRequest.commentsURL, body: result.text)
    return "review posted"
}
curl -X POST "$WEBHOOK_URL/github" \
  -H "Content-Type: application/json" \
  -H "X-GitHub-Event: pull_request" \
  -d '{"action":"opened","pull_request":{"number":42,"title":"Add auth","comments_url":"https://api.github.com/repos/acme/app/issues/42/comments"}}'

File system and queue triggers

For local automation, watch a directory and start an agent when files change. For cloud deployments, consume a queue such as Cloudflare Queues, AWS SQS, or RabbitMQ. The pattern is the same: validate, extract context, run the agent, and acknowledge the message only after success.

Best practices

  • Verify webhook signatures and authenticate queue consumers.
  • Store event identifiers so you can deduplicate retries.
  • Run agents in sandboxes when processing untrusted input.
  • Return HTTP 200 quickly for webhooks and process the agent asynchronously if the work is long.
  • Emit structured logs with the session ID so you can correlate events.

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification