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. Give your main agent a tool that creates that session, hands it a task and returns the result.
Add a delegation tool
Start from the quickstart's client and imports. 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({
agentloop: { name: "pi" },
model: { provider: "openai", name: "gpt-5-mini", apiKey },
});
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, then send
"Ask the other agent to suggest three short names for an order-tracking app." and run the app.
The parent gets the child's conversation back as a tool result and can use it in its answer.
This child has no tools; give it only the ones it needs when you create it. The parent doesn't automatically share its conversation, files or permissions with the child.
Lifetime and history
The tool runs in your process, which must stay connected while the child works. Passing
ctx.signal stops the child's current turn if the parent's tool call is cancelled. Use the child
exclusively during the call so cancelling can't interrupt someone else's work.
The example ends the child but keeps its history. Save the child's ID to inspect it later, and call
child.delete() after ending it once you no longer need it. Brain records each session
separately; your application owns the parent–child relationship.