Tulip Logo IconTulip
Recipes

Agents on Events

Run an agent in the background when something happens, as itself, with approvals for its changes.

An agent can react to a domain event, such as a new task, without anyone watching. It runs in the background, as itself with its own grants, and its changes wait for a person to approve them. Example: a triage agent that estimates new tasks without story points.

The agent

Give it an identity: the grants of exactly this job, and who approves its changes.

export const triageAgent = defineAgent({
  name: "task_triage",
  title: "Taaktriage",
  model,
  instructions,
  tools: { get_project_context: getProjectContext, estimate_task: estimateTask },
  identity: {
    grants: { project: ["view"], initiative: ["view"], task: ["view", "update"] },
    // The people who plan the work decide on estimates.
    approvers: async () => {
      const planningRoles = Object.entries(roles)
        .filter(([, role]) => role.authorize({ initiative: ["create"] }).success)
        .map(([name]) => name);
      const planners = await db
        .select({ id: users.id })
        .from(users)
        .where(inArray(users.role, planningRoles));

      return planners.map((planner) => planner.id);
    },
  },
});

The tool that changes data asks first (confirmation: "approval"). An admin can later allow it for the agent without asking (see Manage agents).

Run it in the background

Background runs need a queue. Give Agents.init an enqueueRun, and handle the job with agents.runs.execute:

// Agents.init
enqueueRun: async (runId) => {
  // No dedupe key: a run is queued again when it continues after its approvals.
  await queue.enqueue(agentRunTask, { runId });
},

// server/ai/handlers.ts
export const agentRunTaskHandler = agentRunTask.handle("execute-agent-run", async ({ payload }) => {
  await agents.runs.execute(payload.runId);
});

Start it on the event

export const agentEventListeners = {
  taskTriage: taskCreatedEvent.listen(async ({ payload, event }) => {
    if (payload.after.story_points != null) return;

    // Loaded here: the agents' tools publish events, so a top-level import would make a cycle
    // with the event bus.
    const { agents } = await import("@/server/ai/init");
    const via = payload.actor.via;

    await agents.start("task_triage", {
      as: "agent",
      trigger: { type: "event", event: event.name, eventId: event.id },
      prompt: `Task ${payload.code} ${payload.title} (id ${payload.taskId})`,
      // A task another agent created counts as caused by that run, for the loop guard.
      causedBy: via?.type === "agent" ? via.id : undefined,
    });
  }),
};

agents.start returns null when the agent is not active, so turning the agent off stops it without a deploy. Keep the listener cheap: filter first, then start the run.

Approvals

When the agent calls estimate_task, the run waits, an approval is stored for every approver, and approvals.notify tells them. Link the notification to an approval page; once someone approves, the run continues through the queue and the change is made, recorded in history as made by the agent via its run. See Approvals inbox.

Guidance

  • Grant only what the job needs; the agent's grants are all it has.
  • Always name approvers for an agent with tools that ask first, or its runs fail.
  • Pass causedBy from the event's actor, so agents cannot trigger each other without end.
  • Watch the agent's runs: a failed background run is only visible there.

On this page