# Show an agent's sub-agents

> One line per sub-agent in the reply — its name, its task, what it is doing now, how far it got — for an AG-UI agent, a tool of your own loop, or a backend in any language, with its conversation under the line or in a pane of its own.

A sub-agent is an agent another agent hands part of its work to: it gets one task, works on it with its own model calls and its own tools, and reports back. Its work is not the reply, so the chat keeps it out of the reply and out of what the model reads next. With `@aparte/plugin-subagents`, each sub-agent becomes one line in the reply.

[An agent hands three tasks to sub-agents, one line each](/preview/demo/subagents/?play=Why%20does%20the%20CSV%20import%20break%20on%20quoted%20fields%3F)

```html
<!-- The model here is scripted: it hands the question to three sub-agents, which run
     through the real loop and call real tools. In your app:
     import { setupSubagents } from '@aparte/plugin-subagents'. -->
<aparte-chat placeholder="Ask the agent" style="height: 26rem"></aparte-chat>

<script>
  const { aparteGlobalConfig } = window.aparte;
  const { createScenarioProvider, scenarioSubagentTool } = window.apartePlugins.scenario;
  const { setupSubagents } = window.apartePlugins.subagents;

  // Each sub-agent has its own task and its own scripted model; read_file, search_docs and
  // run_command are tools the page registered, and they really run.
  const model = createScenarioProvider({
    id: 'delegating',
    name: 'Delegating',
    models: [{ id: 'delegating', name: 'Delegating' }],
    turns: [
      [{ text: 'Three questions, so three sub-agents.' }, { subagents: [
        { name: 'Reader', task: 'Read the parser', turns: [
          [{ wait: 600 }, { tool: 'read_file', input: { path: 'src/parser.ts' } }],
          [{ wait: 1800 }, { text: 'It splits each line on commas and never looks for quotes.' }],
        ] },
        { name: 'Searcher', task: 'Find what calls it', turns: [
          [{ wait: 1200 }, { tool: 'search_docs', input: { query: 'parse(' } }],
          [{ wait: 2400 }, { text: 'Two callers: import.ts and cli.ts.' }],
        ] },
        { name: 'Tester', task: 'Run the tests', turns: [
          [{ wait: 1800 }, { tool: 'run_command', input: { cmd: 'pnpm test' } }],
          [{ wait: 3000 }, { text: '12 pass, 1 fails on a quoted field.' }],
        ] },
      ] }],
      'All three are back: a comma inside quotes splits the field in two. The fix belongs in the parser.',
    ],
  });
  aparteGlobalConfig.registerAIProvider(model);
  aparteGlobalConfig.setModelConfig({ defaultProvider: 'delegating', defaultModel: 'delegating' });

  // The tool the model delegates with, and the plugin that draws its sub-agents.
  const { tool, handler } = scenarioSubagentTool(model);
  aparteGlobalConfig.registerTool(tool, handler);
  setupSubagents();

  // The call that hands the work over reads as a sentence above its sub-agents, with nothing behind it.
  aparteGlobalConfig.registerToolDisplay('delegate', {
    label: (s) => (s.status === 'resolved' ? 'Handed to three sub-agents' : 'Handing off to three sub-agents…'),
    details: false,
  });

  // What each call targets, so a line says what its sub-agent is doing: "read_file src/parser.ts".
  aparteGlobalConfig.registerToolSummary('read_file', (s) => String(s.toolCall.input.path));
  aparteGlobalConfig.registerToolSummary('search_docs', (s) => String(s.toolCall.input.query));
  aparteGlobalConfig.registerToolSummary('run_command', (s) => String(s.toolCall.input.cmd));
</script>
```

Three sub-agents side by side, each on its own line. The model here is scripted; the loop and the tools are real.

The line says who works and on what: its name, then its task. Under it, a second line says what it is on — *Starting…*, then its latest tool call — and once it is over what it did: `3 tools · 12s`. That second line is there from its start to its end, so the line keeps its height and nothing under it moves while it works. It reads one of five states: **Running**, **Waiting** (a call of its own waits for a person), **Done**, **Failed**, or **Stopped** (a Stop, or a reload while it worked). By default the line has nothing behind it; what it can open on is [yours to choose](#what-the-line-shows).

## Turn it on

[Section titled “Turn it on”](#turn-it-on)

```bash
npm install @aparte/plugin-subagents @aparte/core
```

```ts
import { setupSubagents } from '@aparte/plugin-subagents';

setupSubagents();
```

`setupSubagents()` works on the page’s config, or on the one you pass last, like every setup function, and returns the function that takes it off again. The words follow the chat’s language: the counts (`subagentsTools`), the word before its first call (`subagentsStarting`) and the name of an agent given none (`subagentsUnnamed`) ship with the plugin in the same ten languages as [`@aparte/locales`](/guides/localization/), and `extendLocale` replaces them.

## Four ways sub-agents reach the page

[Section titled “Four ways sub-agents reach the page”](#four-ways-sub-agents-reach-the-page)

### An AG-UI agent

[Section titled “An AG-UI agent”](#an-ag-ui-agent)

```ts
import { AparteClient } from '@aparte/core';
import { createAgUiRunner } from '@aparte/runner-ag-ui';
import { setupSubagents } from '@aparte/plugin-subagents';

setupSubagents();
new AparteClient({
  streamRunner: createAgUiRunner({ endpoint: 'https://agents.example.com/agui' }),
}).start();
```

The [AG-UI runner](/providers/agent/ag-ui/) reads AG-UI’s `SUBAGENT_STARTED`, `SUBAGENT_FINISHED` and `SUBAGENT_ERROR`, and the `subagentRunId` on everything a sub-agent streams. Several sub-agents can stream at once: their events interleave and each line follows its own. A sub-agent started by a tool call (`parentToolCallId`) is drawn on that call’s line; one started without a call gets a line of its own; a sub-agent of a sub-agent is a line in its parent’s conversation. Nothing is needed on the page beyond the plugin.

The agent’s side has to announce them, and the AG-UI integrations that can do it keep it off by default, because a client older than sub-agents fails on their events. What each one documents:

| Agent framework                                    | Its AG-UI integration announces sub-agents with                                                                              |
| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| LangGraph, Python (deep agents’ `task` sub-agents) | `subagent_visibility="attributed"`                                                                                           |
| Mastra                                             | `subagentVisibility: "attributed"` — its agents; workflows used as tools and `agent.network()` are not attributed            |
| Google ADK, JavaScript                             | `subagents: "attributed"`                                                                                                    |
| AWS Strands                                        | `subagent_visibility="attributed"`                                                                                           |
| [TanStack AI](/providers/agent/tanstack-ai/)       | `chat({ subagents })`: each sub-agent’s events carry its `subagentRunId`, between `SUBAGENT_STARTED` and `SUBAGENT_FINISHED` |

An integration that does not announce its sub-agents streams their work as the agent’s own, and the chat draws it as part of the reply.

### An n8n workflow

[Section titled “An n8n workflow”](#an-n8n-workflow)

```ts
import { AparteClient } from '@aparte/core';
import { createN8nRunner } from '@aparte/runner-n8n';
import { setupSubagents } from '@aparte/plugin-subagents';

setupSubagents();
new AparteClient({
  streamRunner: createN8nRunner({ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat' }),
}).start();
```

An **AI Agent Tool** — an agent another AI Agent calls as a tool — gets a line named after its node, with its text in it and out of the reply, once its caller streams again. Leave **Enable Streaming** on in the AI Agent Tool’s options: n8n sends nothing of one that does not stream. What n8n tells and does not tell is on [the n8n runner’s page](/providers/agent/n8n/#sub-agents).

### A tool of your own loop

[Section titled “A tool of your own loop”](#a-tool-of-your-own-loop)

A tool opens a sub-agent from the run it was called in, `context.run`, with `runSubAgent`. The sub-agent runs a loop of its own on the conversation you give it, with the run’s model connection and the run’s tools, and its events reach the page as its own:

```ts
import { AparteClient, aparteGlobalConfig, runSubAgent, type AparteTool, type AparteToolHandler } from '@aparte/core';
import { setupSubagents } from '@aparte/plugin-subagents';

declare function readProjectFile(path: string): Promise<string>; // yours

const readFile = {
  name: 'read_file',
  description: 'Read a file of the project.',
  inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
} satisfies AparteTool;

const research = {
  name: 'research',
  description: 'Hand one question to a researcher, who reads the files it needs and answers it.',
  inputSchema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },
} satisfies AparteTool;

const handleResearch: AparteToolHandler = async (call, signal, context) => {
  if (!context?.run) return { toolCallId: call.id, content: 'No researcher can run here.' };
  const question = String(call.input['question']);
  const answer = await runSubAgent(context.run, {
    name: 'Researcher',
    description: question,
    request: {
      modelId: 'gpt-4.1-mini',
      messages: [
        { role: 'system', content: 'Answer one question about the project. Read the files you need.' },
        { role: 'user', content: question },
      ],
      tools: [readFile],
    },
  }, signal);
  return {
    toolCallId: call.id,
    content: answer.status === 'done' ? answer.text : `The researcher did not finish (${answer.error ?? answer.status}).`,
  };
};

aparteGlobalConfig.registerTool(readFile, async (call) => ({
  toolCallId: call.id,
  content: await readProjectFile(String(call.input['path'])),
}));
aparteGlobalConfig.registerTool(research, handleResearch);
setupSubagents();
new AparteClient().start();
```

`name` is the line’s name and `description` its task. `request` is the sub-agent’s whole conversation — the parent’s is not handed on — and `request.tools` is what its model may call, run by the handlers registered on the config. `runSubAgent` resolves `{ status, text }`: `'done'`, `'partial'` with a `reason` when its own run stopped before it answered (its turn limit, a call it could not make: `text` is then what it found, and the line reads **Cut short**), `'failed'` with an `error`, or `'stopped'`, and `text`, what the sub-agent wrote last. It never rejects for a sub-agent that failed, so the tool decides what the model reads: what the handler returns as `content`, as for any tool. The model never reads the sub-agent’s conversation. A sub-agent ends with its tool: a handler that returns while one it opened still runs (a `runSubAgent` it did not await) ends it **Stopped**, one that throws ends it **Failed**, and nothing more of it is shown.

The same handler runs on [the server](/guides/server-loop/): pass it in `createAparteAgentHandler`’s `tools`, and its `context.run` is the server’s run. The sub-agent calls the model with the server’s provider and key, and its events go down the same stream as the run’s own:

```ts
import { createAparteAgentHandler } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';

export const POST = createAparteAgentHandler({
  providers: { openai: createOpenAICompatProvider(presets.OPENAI) },
  defaultModel: 'gpt-4.1-mini',
  resolveKey: () => process.env.OPENAI_API_KEY,
  authorize: (req) => isSignedIn(req),
  secret: process.env.AGENT_SECRET!,
  tools: [
    { tool: readFileTool, handler: readFileHandler },
    { tool: research, handler: handleResearch },   // opens its sub-agent with runSubAgent(context.run, …)
  ],
});
```

A sub-agent’s tools are found among the run’s: on the server, the tools the request offers. When the model delegates several times in one reply, the sub-agents run side by side only if the delegating tool says `parallel: true`; one that says nothing keeps its place, and each delegation waits for the one before it ([Several calls in one reply](/guides/engine/#several-calls-in-one-reply)):

```ts
import type { AparteTool } from '@aparte/core';

const research = {
  name: 'research',
  description: 'Hand one question to a researcher, who reads the files it needs and answers it.',
  inputSchema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },
  parallel: true,   // two research calls in one reply run side by side
} satisfies AparteTool;
```

One tool can also open several, with `Promise.all`, each with `detached: true`: one call’s line can stand for only one sub-agent, so each of them gets a line of its own.

#### While the chat goes on

[Section titled “While the chat goes on”](#while-the-chat-goes-on)

`runSubAgent` holds its call until the sub-agent is back, so the reply waits at the delegation. `startSubAgent` starts it in the background instead: the call answers at once, and the model goes on, writing and calling its own tools, while the sub-agent works on its line. The reply does not end before it is back: once the model has nothing more to say, the loop waits for the sub-agents still at work, tells the model how each ended in one message, and asks it again. That last answer is the reply’s end.

```ts
import { aparteGlobalConfig, startSubAgent, type AparteTool, type AparteToolHandler } from '@aparte/core';

const research: AparteTool = {
  name: 'research',
  description: 'Hand a question to a researcher and go on: its answer comes back to you.',
  inputSchema: { type: 'object', properties: { question: { type: 'string' } }, required: ['question'] },
};

const handleResearch: AparteToolHandler = async (call, _signal, context) => {
  startSubAgent(context!.run!, {
    name: 'Researcher',
    description: String(call.input['question']),
    request: { modelId: 'gpt-4.1-mini', messages: [{ role: 'user', content: String(call.input['question']) }] },
  });
  return { toolCallId: call.id, content: 'The researcher is on it. Go on; its answer comes back to you.' };
};

aparteGlobalConfig.registerTool(research, handleResearch);
```

Each one started this way gets a line of its own, and is stopped with the run: by Stop, by the turn limit, and by the tool time limit counted from its start. It cannot be started in a run that can pause (the [server loop](/guides/server-loop/), which would end at the pause without its answer): `startSubAgent` throws there, and `runSubAgent` is the one to use. The message the model reads when they are back is the loop’s (“The sub-agents you started are back.”), a user message in the run’s history, and it is not shown: the model’s answer to it is.

### A backend in any language

[Section titled “A backend in any language”](#a-backend-in-any-language)

A backend that is not JavaScript writes the [engine’s run events](/guides/engine/#events) as NDJSON, one per line, and the page reads them with `createAgentStreamRunner`:

```ts
import { AparteClient, createAgentStreamRunner } from '@aparte/core';
import { setupSubagents } from '@aparte/plugin-subagents';

setupSubagents();
new AparteClient({ streamRunner: createAgentStreamRunner({ endpoint: '/api/agent' }) }).start();
```

A sub-agent is opened with an `agent-start` line, its own events carry its `agentId`, and an `agent-end` line closes it, once. Put `toolCallId` on `agent-start` to draw it on the line of the call that opened it:

```json
{"type":"run-start"}
{"type":"turn-start"}
{"type":"text-delta","delta":"I will ask a researcher."}
{"type":"tool-start","toolCallId":"call_1","name":"research","input":{"question":"Why do quoted fields break?"}}
{"type":"agent-start","agentId":"r1","name":"Researcher","description":"Why do quoted fields break?","toolCallId":"call_1"}
{"type":"turn-start","agentId":"r1"}
{"type":"tool-start","toolCallId":"call_2","name":"read_file","input":{"path":"src/parser.ts"},"agentId":"r1"}
{"type":"tool-resolved","toolCallId":"call_2","result":"export function parse(line) { … }","agentId":"r1"}
{"type":"turn-start","agentId":"r1"}
{"type":"text-delta","delta":"It splits on commas and never looks for quotes.","agentId":"r1"}
{"type":"agent-end","agentId":"r1","status":"done","result":"It splits on commas and never looks for quotes."}
{"type":"tool-resolved","toolCallId":"call_1","result":"It splits on commas and never looks for quotes."}
{"type":"turn-start"}
{"type":"text-delta","delta":"A comma inside quotes splits the field: the parser needs a fix."}
{"type":"run-done"}
```

`agent-end`’s `status` is `done`, `partial` (with `result` and a `reason`, a `StreamAgentCutReason`: `turn-limit`, `timeout`, `no-handler`, `no-resolver`, `aborted` for a call that stopped itself while nobody stopped the run, or `context` for a host that cuts a sub-agent whose context is nearly full), `failed` (with `error`), `waiting` or `stopped`. The four run lines — `run-start`, `run-done`, `run-aborted`, `run-suspended` — belong to the run and never carry an `agentId`: a sub-agent never starts or ends it, and the runner drops such a line with a warning. A sub-agent of a sub-agent names its parent in `parentAgentId`. An `agentId` names one sub-agent for the whole reply, a pause and its resume included: an `agent-start` for an id already seen continues that sub-agent when it names the same `toolCallId`, or none, and opens a new line when it names another call. Mint ids that do not repeat across requests. The request the page sends is the one [the server loop’s wire](/guides/server-loop/#the-wire) describes.

## What the line shows

[Section titled “What the line shows”](#what-the-line-shows)

The line is the row of the call that opened the sub-agent, so everything you declare for that tool with [`registerToolDisplay`](/guides/tool-display/) applies, and wins over what the plugin says: `label`, `icon`, `summary`, `quiet`, `hidden`, `open` and `details`. A sub-agent no call opened, or a second one opened by the same call, gets a line of its own, named by the agent: reach it with the agent’s name, `registerToolDisplay('Researcher', …)`.

```ts
import { setupSubagents } from '@aparte/plugin-subagents';

setupSubagents({
  activity: true,          // a second line: what it is on, then what it did
  counts: true,            // "3 tools · 12s", once it is over
  details: 'transcript',   // its conversation under the line; false (the default) for nothing
  open: 'event',           // an Open button that shows it beside the chat; see below
  model: false,            // true: the model it runs on, quietly on its line
});
```

These are `SubagentsOptions`. `model` draws the model each sub-agent runs on, for an app whose sub-agents run on other models than the conversation: `agent-start` carries it as `model`, and `runSubAgent` names its request’s `modelId` (or the `model` you give it, a friendlier name). `open` is explained in [Open a sub-agent beside the chat](#open-a-sub-agent-beside-the-chat). `details` is `false` by default: the line opens on nothing. `'transcript'` puts the sub-agent’s conversation under it — the task it was given, its text, its reasoning, its own tool rows and its own sub-agents as lines, drawn by the reply’s renderers and kept up to date while it works — closed until the reader opens it. A function puts what it returns there, as a tool display’s `details` does. `subagentTranscript` is that conversation as such a function, for one tool’s line only, open by default here:

```ts
import { aparteGlobalConfig } from '@aparte/core';
import { setupSubagents, subagentTranscript } from '@aparte/plugin-subagents';

setupSubagents();
aparteGlobalConfig.registerToolDisplay('research', { details: subagentTranscript, open: true });
```

In a conversational chat, where the person should see the answer and not who worked on it, hide the tool that delegates. A sub-agent with a line of its own is hidden by its name:

```ts
import { aparteGlobalConfig } from '@aparte/core';

aparteGlobalConfig.registerToolDisplay('research', { hidden: true });
aparteGlobalConfig.registerToolDisplay('Researcher', { hidden: true });
```

A hidden line is still saved with the conversation, its sub-agent’s conversation with it.

With [a turn’s steps folded behind one line](/guides/tool-display/#fold-a-turn-behind-one-line), a sub-agent drawn on its call’s line folds with the turn’s other steps. One with a line of its own stays in view, as a step that waits or failed does.

## Where the sub-agents stand

[Section titled “Where the sub-agents stand”](#where-the-sub-agents-stand)

A reply that hands its work to several sub-agents can say where they stand above their lines: *3 sub-agents · 1 done, 2 running*. That line is the fold’s, written by `subagentsTurnLabel`:

```ts
import { aparteGlobalConfig } from '@aparte/core';
import { setupSubagents, subagentsTurnLabel } from '@aparte/plugin-subagents';

setupSubagents();
aparteGlobalConfig.setTurnSummary({ openWhileRunning: true, label: subagentsTurnLabel });
```

`openWhileRunning` keeps the fold open while they work, each line saying its own state under the count, and closes it once they are done. The line follows them as they end, in the chat’s language, and is a polite live region, so a change is heard. Under two sub-agents the fold keeps core’s line. A sub-agent that waits for the person, or that failed, stands out of the fold on its own line, where it has to be read, so the count is of the others.

The words are locale keys with their plural forms, like `subagentsTools`: `subagentsCount`, `subagentsDone`, `subagentsRunning`, `subagentsWaiting`, `subagentsFailed` and `subagentsStopped`. To count a state of your own, a sub-agent waiting for a free slot say, write the line yourself: `label` gets the fold’s steps, and `subagentOf` and `subagentStatus` read each one.

### Name the Stop button

[Section titled “Name the Stop button”](#name-the-stop-button)

The Stop button stops the whole reply, its sub-agents with it. While they work, the chat’s composer can say so, and the word goes back to “Stop” when the last of them ends (a Stop ends them all):

* Vanilla

  ```ts
  import '@aparte/plugin-subagents';

  const chat = document.getElementById('chat')!;
  let running = 0;

  chat.addEventListener('aparte-subagent-start', () => {
    running += 1;
    const composer = chat.querySelector('aparte-composer');
    if (composer) composer.stopLabel = 'Stop the sub-agents';
  });
  chat.addEventListener('aparte-subagent-end', () => {
    running = Math.max(0, running - 1);
    const composer = chat.querySelector('aparte-composer');
    if (composer && running === 0) composer.stopLabel = null;
  });
  ```

* React

  ```tsx
  import { useRef } from 'react';
  import { AparteChat, useAparteChat, useAparteEvent } from '@aparte/react';
  import '@aparte/plugin-subagents';   // its events join HTMLElementEventMap

  export function Chat() {
    const chat = useAparteChat();
    const running = useRef(0);

    useAparteEvent(chat.ref, 'aparte-subagent-start', () => {
      running.current += 1;
      const composer = chat.getComposer();
      if (composer) composer.stopLabel = 'Stop the sub-agents';
    });
    useAparteEvent(chat.ref, 'aparte-subagent-end', () => {
      running.current = Math.max(0, running.current - 1);
      const composer = chat.getComposer();
      if (composer && running.current === 0) composer.stopLabel = null;
    });

    return <AparteChat ref={chat.ref} messages={chat.messages} onMessagesChange={chat.setMessages} />;
  }
  ```

* Vue

  ```vue
  <script setup lang="ts">
  import { AparteChat, useAparteChat } from '@aparte/vue';
  import '@aparte/plugin-subagents';

  const chat = useAparteChat();
  let running = 0;

  function started() {
    running += 1;
    const composer = chat.getComposer();
    if (composer) composer.stopLabel = 'Stop the sub-agents';
  }
  function ended() {
    running = Math.max(0, running - 1);
    const composer = chat.getComposer();
    if (composer && running === 0) composer.stopLabel = null;
  }
  </script>

  <template>
    <AparteChat :ref="chat.chatRef" :messages="chat.messages.value" @messages-change="chat.onMessagesChange" @aparte-subagent-start="started" @aparte-subagent-end="ended" />
  </template>
  ```

* Svelte

  ```svelte
  <script lang="ts">
    import { AparteChat, type AparteChatImperativeApi } from '@aparte/svelte/runes';
    import '@aparte/plugin-subagents';

    let chat = $state<AparteChatImperativeApi>();
    let running = 0;

    function started() {
      running += 1;
      const composer = chat?.getComposer();
      if (composer) composer.stopLabel = 'Stop the sub-agents';
    }
    function ended() {
      running = Math.max(0, running - 1);
      const composer = chat?.getComposer();
      if (composer && running === 0) composer.stopLabel = null;
    }
  </script>

  <AparteChat bind:this={chat} onaparte-subagent-start={started} onaparte-subagent-end={ended} />
  ```

  On Svelte 4, listen on `chat.getElement()` in `onMount` ([Svelte](/frameworks/svelte/#control-it-from-code)).

* Angular

  ```ts
  import { Component, viewChild } from '@angular/core';
  import { AparteChatComponent } from '@aparte/angular';
  import '@aparte/plugin-subagents';

  @Component({
    selector: 'app-chat',
    standalone: true,
    imports: [AparteChatComponent],
    template: `<aparte-chat (aparte-subagent-start)="started()" (aparte-subagent-end)="ended()"></aparte-chat>`,
  })
  export class ChatComponent {
    readonly chat = viewChild.required(AparteChatComponent);
    private running = 0;

    started() {
      this.running += 1;
      const composer = this.chat().getComposer();
      if (composer) composer.stopLabel = 'Stop the sub-agents';
    }

    ended() {
      this.running = Math.max(0, this.running - 1);
      const composer = this.chat().getComposer();
      if (composer && this.running === 0) composer.stopLabel = null;
    }
  }
  ```

`stopLabel` is the composer’s, for this chat alone: `extendLocale({ stopButton })` would rename the Stop of every chat sharing the config.

## Steps

[Section titled “Steps”](#steps)

An agent can say what stage of its work it is in — *Searching the repository*, *Reading the parser* — with a step: a name, a start and an end. While the reply has nothing to show yet, or a call is done and the next has not begun, the waiting indicator says the agent’s step beside its dots. A sub-agent’s step shows on its line, as its second line, while none of its calls runs; a running call still wins. Steps may nest: the latest one open shows, and the one before it comes back when it ends.

A step shows while it lasts and nothing more. It is not kept in the reply, not saved with the conversation and not sent to the model. Once the reply has text, or ends, it is gone.

**A key in the person’s language:** a server often names a step with a stable key — `slot-wait`, `restore`, `reread` — while the page knows the language. `registerStepLabel` maps the key to the words, and the waiting indicator, what a screen reader hears in place of “Typing” and a sub-agent’s line all show them. A name without a label shows as it is. The label is text, or a function of the locale, asked again at every change of it, so a step that is open follows a language switch:

```ts
import { aparteGlobalConfig } from '@aparte/core';

aparteGlobalConfig.registerStepLabel('slot-wait', 'Waiting for a free slot…');

// A function is told the locale, and asked again when it changes.
const off = aparteGlobalConfig.registerStepLabel('reread', ({ locale }) =>
  locale.tag?.startsWith('fr') ? 'Relecture de la conversation…' : 'Re-reading the conversation…');

off(); // takes the label off: the name shows again
```

It is configuration, not a component, so it reads the same under every framework: register it on `aparteGlobalConfig`, or on the config you give one chat (a framework’s `config` prop), which then reads its own labels only. Only what is shown is labelled: `config.observeRunEvents` still hears `step-start` with `reread`, so a mark of the step that you keep holds the key, not the label.

**What the step is about:** a step can carry data for its words, its `detail` — who holds the engine, which file is read — and `step-update` changes it while the step stays open. The label function is handed it, with the reply’s `messageId` (two chats waiting, two answers), and asked again when it changes. The data is never shown as it is: the words stay the page’s.

```ts
// The server: { "type": "step-start", "name": "slot-wait", "detail": { "holder": "Login refactor" } }
//        then { "type": "step-update", "name": "slot-wait", "detail": { "holder": "Docs pass" } }
aparteGlobalConfig.registerStepLabel('slot-wait', ({ detail }) =>
  detail?.holder ? `Waiting for the engine: “${String(detail.holder)}” is running` : 'Waiting for the engine…');
```

A second `step-start` with the same name opens another step inside the first (AG-UI’s rule), so update a step with `step-update`, not with a new start. Registering a label again also redraws an open step at once, for words that change for a reason of the page’s own.

**An AG-UI agent:** nothing to do. `STEP_STARTED` and `STEP_FINISHED` are shown as they arrive, a sub-agent’s by its `subagentRunId`, and a step the agent leaves open closes when its run ends.

**Your own loop:** a sub-agent announces a step through the handle `startAgent` returns. Send `step-end` with the same name when the stage is over:

```ts
import { aparteGlobalConfig, type AparteToolHandler } from '@aparte/core';

declare function indexFiles(signal: AbortSignal): Promise<number>; // yours

const handleIndex: AparteToolHandler = async (call, _signal, context) => {
  const agent = context!.run!.startAgent({ name: 'Indexer', description: 'Index the project' });
  agent.emit({ type: 'step-start', name: 'Reading the files' });
  const count = await indexFiles(agent.signal);
  agent.emit({ type: 'step-end', name: 'Reading the files' });
  agent.end('done', { result: `${count} files indexed.` });
  return { toolCallId: call.id, content: `${count} files indexed.` };
};

aparteGlobalConfig.registerTool(
  { name: 'index', description: 'Index the project.', inputSchema: { type: 'object', properties: {} } },
  handleIndex,
);
```

A loop of your own (`streamRunner`) emits the same two events for the reply’s own steps, without an `agentId`, and a model’s stream can carry them too: `{ type: 'step-start', name }` among its events is passed on as is.

**A scripted model:** the [scenario provider](/providers/ai/scenario/#steps) has a step of its own, `{ step: 'Reading the parser' }`, ended by `{ endStep: 'Reading the parser' }`.

An app that wants to keep a mark of a step in the reply draws it from [`config.observeRunEvents`](/guides/engine/#events), which hears every `step-start` and `step-end`.

A sub-agent can also report its progress as an [activity](/guides/activity/) — “3 of 5 sources read” — which the renderer you register for its type draws in that sub-agent’s conversation, under its line and in `<aparte-subagent-view>`, updated in place as it changes. A sub-agent that reports its plan that way gets the [plan card](/components/plan-card/#from-an-activity) there with `setupPlanCard({ activity: 'plan' })`.

When a [TanStack AI](/providers/agent/tanstack-ai/) `subagents.router` picks the agents, it sends its plan with them: which agents run, in which order. That is the reply’s plan rather than one sub-agent’s, so the runner hands it on as a `plan` activity of the reply, one step per agent, in progress when the agent starts and done or failed when it ends. `setupPlanCard({ activity: 'plan' })` draws it.

## Show the conversation elsewhere

[Section titled “Show the conversation elsewhere”](#show-the-conversation-elsewhere)

`<aparte-subagent-view>` shows a sub-agent’s conversation where you put it: the other pane of a [split](/components/split/), a canvas, a dialog. Name the chat with `for`, the reply with `message-id` and the sub-agent with `agent-id`; `aparte-subagent-start`, which bubbles out of the chat as each sub-agent starts, carries the three:

[A sub-agent's conversation in a pane beside the chat](/preview/demo/subagent-view/?play=Why%20do%20quoted%20fields%20break%3F)

```html
<!-- The chat alone until a sub-agent starts; then its conversation opens in the other pane.
     The model here is scripted. In your app: import { setupSubagents } from '@aparte/plugin-subagents'. -->
<aparte-split position="50" breakpoint="30rem" single style="height: 28rem">
  <aparte-chat id="chat" placeholder="Ask the agent"></aparte-chat>
  <aparte-subagent-view for="chat"></aparte-subagent-view>
</aparte-split>

<script>
  const { aparteGlobalConfig } = window.aparte;
  const { createScenarioProvider, scenarioSubagentTool } = window.apartePlugins.scenario;
  const { setupSubagents } = window.apartePlugins.subagents;

  const model = createScenarioProvider({
    id: 'delegating',
    name: 'Delegating',
    models: [{ id: 'delegating', name: 'Delegating' }],
    turns: [
      [{ text: 'A researcher can read it for you.' }, { subagents: [
        { name: 'Researcher', task: 'Find why quoted fields break', turns: [
          [{ thinking: 'Start with the parser itself.' }, { wait: 800 }, { tool: 'read_file', input: { path: 'src/parser.ts' } }],
          [{ text: 'The parser splits each line on commas. ' }, { wait: 900 }, { tool: 'search_docs', input: { query: 'quoted fields' } }],
          [{ wait: 900 }, { text: 'It never looks for quotes, so a comma inside a quoted field splits it in two.' }],
        ] },
      ] }],
      'The researcher found it: a comma inside quotes splits the field. The fix belongs in the parser.',
    ],
  });
  aparteGlobalConfig.registerAIProvider(model);
  aparteGlobalConfig.setModelConfig({ defaultProvider: 'delegating', defaultModel: 'delegating' });
  const { tool, handler } = scenarioSubagentTool(model);
  aparteGlobalConfig.registerTool(tool, handler);
  setupSubagents();

  // The view follows the sub-agent the chat announces, and the pane opens for it.
  const split = document.querySelector('aparte-split');
  const view = document.querySelector('aparte-subagent-view');
  document.getElementById('chat').addEventListener('aparte-subagent-start', (e) => {
    view.setAttribute('message-id', e.detail.messageId);
    view.setAttribute('agent-id', e.detail.agentId);
    split.removeAttribute('single');
  });
</script>
```

The pane opens when the sub-agent starts, and follows it live.

```html
<aparte-split position="50" single>
  <aparte-chat id="chat"></aparte-chat>
  <aparte-subagent-view for="chat"></aparte-subagent-view>
</aparte-split>
```

* Vanilla

  ```ts
  import { setupSubagents } from '@aparte/plugin-subagents';

  setupSubagents();

  const split = document.querySelector('aparte-split')!;
  const view = document.querySelector('aparte-subagent-view')!;
  document.getElementById('chat')!.addEventListener('aparte-subagent-start', (event) => {
    view.setAttribute('message-id', event.detail.messageId);
    view.setAttribute('agent-id', event.detail.agentId);
    split.removeAttribute('single');
  });
  ```

* React

  ```tsx
  import { useState } from 'react';
  import { AparteChat, useAparteChat, useAparteEvent } from '@aparte/react';
  import { setupSubagents } from '@aparte/plugin-subagents';   // its events join HTMLElementEventMap

  setupSubagents();

  export function Workspace() {
    const chat = useAparteChat();
    const [shown, setShown] = useState<{ messageId: string; agentId: string }>();

    useAparteEvent(chat.ref, 'aparte-subagent-start', (event) =>
      setShown({ messageId: event.detail.messageId, agentId: event.detail.agentId }));

    return (
      <aparte-split position="50" single={shown ? undefined : ''}>
        <AparteChat id="chat" ref={chat.ref} messages={chat.messages} onMessagesChange={chat.setMessages} />
        {shown && <aparte-subagent-view for="chat" message-id={shown.messageId} agent-id={shown.agentId} />}
      </aparte-split>
    );
  }
  ```

* Vue

  ```vue
  <script setup lang="ts">
  import { ref } from 'vue';
  import { AparteChat } from '@aparte/vue';
  import { setupSubagents } from '@aparte/plugin-subagents';

  setupSubagents();

  const shown = ref<{ messageId: string; agentId: string }>();
  </script>

  <template>
    <aparte-split position="50" :single="shown ? undefined : ''">
      <AparteChat id="chat" @aparte-subagent-start="(event) => (shown = event.detail)" />
      <aparte-subagent-view v-if="shown" for="chat" :message-id="shown.messageId" :agent-id="shown.agentId" />
    </aparte-split>
  </template>
  ```

* Svelte

  ```svelte
  <script lang="ts">
    import { AparteChat } from '@aparte/svelte/runes';
    import { setupSubagents } from '@aparte/plugin-subagents';

    setupSubagents();

    let shown = $state<{ messageId: string; agentId: string }>();
  </script>

  <aparte-split position="50" single={shown ? undefined : ''}>
    <AparteChat id="chat" onaparte-subagent-start={(event) => (shown = event.detail)} />
    {#if shown}
      <aparte-subagent-view for="chat" message-id={shown.messageId} agent-id={shown.agentId}></aparte-subagent-view>
    {/if}
  </aparte-split>
  ```

  On Svelte 4, `bind:this` the chat and listen on `chat.getElement()` in `onMount` ([Svelte](/frameworks/svelte/#control-it-from-code)).

* Angular

  ```ts
  import { Component, CUSTOM_ELEMENTS_SCHEMA, signal } from '@angular/core';
  import { AparteChatComponent, AparteSplitDirective } from '@aparte/angular';
  import { setupSubagents } from '@aparte/plugin-subagents';
  import type { AparteSubagentStartEventDetail } from '@aparte/plugin-subagents';

  setupSubagents();

  @Component({
    selector: 'app-workspace',
    standalone: true,
    imports: [AparteChatComponent, AparteSplitDirective],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    template: `
      <aparte-split position="50" [single]="!shown()">
        <aparte-chat id="chat" (aparte-subagent-start)="shown.set($any($event).detail)"></aparte-chat>
        @if (shown(); as agent) {
          <aparte-subagent-view for="chat" [attr.message-id]="agent.messageId" [attr.agent-id]="agent.agentId"></aparte-subagent-view>
        }
      </aparte-split>
    `,
  })
  export class WorkspaceComponent {
    readonly shown = signal<AparteSubagentStartEventDetail | null>(null);
  }
  ```

It follows the sub-agent live, shows the saved conversation after a reload, and draws nothing until there is something to show. `aparte-subagent-end` says how each one ended. The [component page](/components/subagent-view/) has the rest.

### Open a sub-agent beside the chat

[Section titled “Open a sub-agent beside the chat”](#open-a-sub-agent-beside-the-chat)

To let the reader pick the sub-agent, give each line an Open button with `setupSubagents({ open: 'event' })`, and wire the view with `connectSubagentView`:

```html
<aparte-split position="55">
  <aparte-chat id="chat"></aparte-chat>
  <aparte-subagent-view for="chat"></aparte-subagent-view>
</aparte-split>
```

```ts
import { connectSubagentView, setupSubagents } from '@aparte/plugin-subagents';
import type { SubagentViewSplit } from '@aparte/plugin-subagents';

setupSubagents({ open: 'event' });

const disconnect = connectSubagentView({
  chat: document.getElementById('chat')!,
  view: document.querySelector('aparte-subagent-view')!,
  split: document.querySelector<SubagentViewSplit>('aparte-split')!,
});
```

The button sits at the end of each sub-agent’s line, named “Open Researcher” in the chat’s language. Pressing it (click, Enter or Space) dispatches `aparte-subagent-open` (`AparteSubagentOpenEventDetail`: `messageId`, `agentId`, `name`, and `toolCallId` when the line is that call’s row). `connectSubagentView` then:

* points the view at that sub-agent and opens the split’s second pane (on a phone, where the split shows one pane, it shows the view);
* marks the line: the row gets `data-current` and its button `aria-current="true"`, until another one is opened or the view closes;
* makes the view `closable`: the sub-agent’s name and a Close button above its conversation. Close, or Escape inside the view, folds the pane and puts the focus back on the button that opened it.

A line with nothing behind it also opens on a click anywhere on it. With `details: 'transcript'` too, the line keeps opening the conversation under itself and only the button opens it beside the chat, so one click never means two things. A sub-agent’s own sub-agents are lines inside the view, and they open in the same view. Without `open`, the line has no button and opens nothing.

Without a split, pass `onOpen` and `onClose` and show the view your own way (a tab, a drawer). `disconnect()` undoes all of it.

In a framework the element is a plain tag, and the plugin’s events reach the chat’s root like any other: each wrapper hears them by the event’s own name (`useAparteEvent`, `@aparte-…`, `onaparte-…`, `(aparte-…)`), as the tabs above do. A Vue or Svelte template accepts the tag as it is, and Angular with `CUSTOM_ELEMENTS_SCHEMA` on the component that hosts it (bind with `[attr.message-id]`). In a React `.tsx` file, declare the tag once:

```ts
import type { DetailedHTMLProps, HTMLAttributes } from 'react';

declare module 'react' {
  namespace JSX {
    interface IntrinsicElements {
      'aparte-subagent-view': DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> & {
        for?: string;
        'message-id'?: string;
        'agent-id'?: string;
      };
    }
  }
}
```

`connectSubagentView` takes elements, not tags: in a framework, pass `chat.getElement()` for the chat and a ref (`useRef`, `bind:this`, `viewChild`) for each of the other two, once they are mounted.

## Approvals

[Section titled “Approvals”](#approvals)

A sub-agent’s tool asks like any other: a `needsApproval` tool, or a call your [approval policy](/components/approval-mode/) answers `ask`, opens the [approval panel](/guides/tools/#require-approval-human-in-the-loop), and the question names the sub-agent: “Allow read\_file for Researcher?”, from the locale key `approvalAskBy` (`Allow {tool} for {agent}?`). Its line reads **Waiting** until the person answers. A sub-agent with no name is asked about with `approvalAsk`.

In the [server loop](/guides/server-loop/), a sub-agent’s call cannot ask: the run there pauses instead of waiting, and a sub-agent lives inside one tool call, which must answer. A call of a sub-agent that needs a decision is stopped (`tool-aborted`, cause `no-resolver`). Give the tools a sub-agent calls on the server no `needsApproval`, and let the approval sit on the tool that opens the sub-agent. Or, in a host that lives as long as the conversation, run the loop yourself with a resolver that waits: see [the server loop](/guides/server-loop/).

An [AG-UI agent](/providers/agent/ag-ui/) can pause on a call its own sub-agent made (an interrupt raised inside the sub-agent). That pause survives a reload: the call has no row in the reply, so the reply keeps it, in `deferredCalls`, with the name its sub-agent was announced with and the agent’s ticket. A conversation saved while it waits is asked again when it is loaded, under the sub-agent’s name, and the agent resumes with the answer:

```ts
import type { AparteDeferredCall } from '@aparte/core';

// What the saved reply carries while the sub-agent waits; removed once the pause is answered.
const waiting: AparteDeferredCall = {
  toolCallId: 'd1', name: 'delete_file', input: { path: '/x' }, reason: 'approval',
  agentId: 's1', agentName: 'cleaner', ticket: '…',
};
```

A Stop, or a new message, closes the wait like any other pause.

## What it does not do yet

[Section titled “What it does not do yet”](#what-it-does-not-do-yet)

* **What the model was told stays in the run.** The message saying the sub-agents started in the background are back is in that run’s history only: the next turn’s history is drawn from the reply, and reads the model’s answer to it, not the message.
* **A sub-agent waiting in the page does not survive a reload.** A sub-agent that the page’s own loop runs, waiting for an approval, reads **Stopped** after a reload and does not resume: the run it lived in was the page’s. A pause an agent elsewhere holds (above) does resume.
* **Without the plugin, a sub-agent is neither drawn nor kept.** Its text and its tool calls stay out of the reply either way; the call that opened it shows as an ordinary tool row, and the console says once that nothing draws sub-agents. `config.observeRunEvents` hears their events, once each and with their `agentId`, if you draw them yourself.

## Test it with no model

[Section titled “Test it with no model”](#test-it-with-no-model)

The [scenario provider](/providers/ai/scenario/#sub-agents) scripts a model that delegates: a `subagents` step calls one tool, `delegate`, and each sub-agent’s own model plays the turns you wrote, through the real loop and your registered tools. This is what drives the demo above. With `background: true` on the step, they are started in the background: the next turn you wrote plays while they work, and the one after it answers once they are back.

```ts
import { aparteGlobalConfig, AparteClient, AparteDirectTransport } from '@aparte/core';
import { createScenarioProvider, scenarioSubagentTool } from '@aparte/provider-scenario';
import { setupSubagents } from '@aparte/plugin-subagents';

const model = createScenarioProvider({
  turns: [
    [{ text: 'Two questions, two sub-agents.' }, { subagents: [
      { name: 'Reader', task: 'Read the parser', turns: ['It splits each line on commas.'] },
      { name: 'Tester', task: 'Run the tests', turns: [[{ wait: 1500 }, { text: '12 pass, 1 fails on a quoted field.' }]] },
    ] }],
    'Both are back: a comma inside quotes splits the field.',
  ],
});
aparteGlobalConfig.registerAIProvider(model);
const { tool, handler } = scenarioSubagentTool(model);
aparteGlobalConfig.registerTool(tool, handler);
aparteGlobalConfig.setTransport(new AparteDirectTransport({ byok: true }));
setupSubagents();
new AparteClient().start();
```

## Next

[Section titled “Next”](#next)

* [Sub-agent view A sub-agent's conversation, wherever you put it.](/components/subagent-view/)
* [Showing tool calls Every lever of the row a sub-agent's line is drawn on.](/guides/tool-display/)
* [AG-UI agents An agent on its own server, its sub-agents included.](/providers/agent/ag-ui/)
