Aex Brain
Customize and operate

Add a subagent

Give an agent a tool that asks a separate agent to do a task.

A subagent is another session with its own conversation and tools. Your main agent can call a tool that creates that session, sends a task, and returns its result.

Add a delegation tool

Use the client and imports from the quickstart. Declare this tool after creating brain and before creating the parent session:

import { hostEnv } from "@aexhq/brain";

const delegate = tool({
  name: "delegate",
  description: "Ask another agent to work on a self-contained task.",
  input: z.object({ task: z.string() }),
  run: async ({ task }, ctx) => {
    const child = await brain.sessions.create({
      model: { provider: "openai", name: "gpt-5-mini", apiKey },
      agentloop: pi(),
    });
    try {
      const after = child.state.lastSequence;
      await child.send(task, { signal: ctx.signal });
      for await (const event of child.events(after)) {
        if (event.type === "turn_failed") throw new Error(JSON.stringify(event.data));
      }
      return ctx.finish(await child.transcript());
    } finally {
      await child.end();
    }
  },
});

Add delegate({ env: hostEnv({ name: "app" }) }) to the parent's tools array. Send "Ask the other agent to suggest three short names for an order-tracking app." and run the app. The parent receives the child's conversation as a tool result and can use it in its answer.

The child in this example has no tools. Add only the tools it needs when creating it. The parent does not automatically share its conversation, files or permissions with the child.

Lifetime and history

This tool runs in your process, which must stay connected while the child works. Passing ctx.signal stops the child's current turn when the owning tool is cancelled. Use that child exclusively during the call so cancellation cannot interrupt another caller's work.

The example ends the child but keeps its history. Save the child's ID if you want to inspect it later; call child.delete() after ending when you no longer need it. Brain records each session separately; your application owns the relationship between parent and child.

On this page