> **⚠️ PRIVATE BETA — NOT FOR PRODUCTION USE**
>
> This package is in untested private beta. APIs will change without notice. Do not use in production.

# subagent

The third primitive in agent programming. System prompts define who an agent is. Tools define what it can do. Subagents define how it delegates.

```bash
npm install subagent
```

## Quick start

```typescript
import { createAgent } from "subagent"

const agent = await createAgent({
  model: "anthropic:claude-sonnet-4-6",
  subagents: [
    { name: "researcher", description: "Search and analyze code", permissions: "read-only" },
    { name: "editor", description: "Make code changes", budget: { maxTokens: 100000 } },
  ],
  warpGrep: true,
  fastApply: true,
  compact: true,
})

await agent.prompt("Find and fix the memory leak in the worker pool")
await agent.waitForIdle()
```

## What it does

`createAgent()` returns a fully configured agent with built-in tools (`ls`, `read_file`, `write_file`, `edit_file`, `glob`, `grep`, `execute`, `write_todos`) and optional capabilities:

**Subagent delegation** — Each subagent gets its own context window. The parent delegates, subagents process in isolation and return compressed results. Parallel execution, error isolation, budget enforcement, permission scoping (`"full"` | `"read-only"` | `"no-execute"` | `allowedTools`), and structured output via TypeBox schemas.

**WarpGrep** — Semantic codebase search via specialized model. No embeddings, no indexing. Plans a strategy, executes up to 24 parallel tool calls across 4 turns. `warpGrep: true`

**FastApply** — Code editing at 10,500 tok/s. The agent writes partial edits with `// ... existing code ...` markers, Morph expands them into complete files. `fastApply: true`

**Remote execution** — `SSHBackend` runs every tool call on a remote machine via SFTP + SSH exec. Auto-reconnects with exponential backoff.

**Agent teams** — Long-lived teammates with inbox messaging and shared task boards. Dependency tracking across tasks. The parent acts as team lead.

**Model Router** — Classifies each prompt and routes easy tasks to cheaper models. `modelRouter: true`

**Context compaction** — Compresses older messages so agents run indefinitely without context overflow. `compact: true`

## Subagents

A subagent consumes more context than it returns. It reads 50 files, analyzes patterns, and returns 3 findings. The parent never sees the noise.

```typescript
import { Type } from "@sinclair/typebox"

const agent = await createAgent({
  model: "anthropic:claude-sonnet-4-6",
  subagents: [
    {
      name: "analyzer",
      description: "Find security issues",
      permissions: "read-only",
      outputSchema: Type.Object({
        issues: Type.Array(Type.Object({
          file: Type.String(),
          line: Type.Number(),
          severity: Type.Union([Type.Literal("low"), Type.Literal("medium"), Type.Literal("high")]),
          message: Type.String(),
        })),
      }),
    },
  ],
})
```

The subagent calls an `output` tool with data matching the schema. The parent gets typed JSON, not freeform text.

## Remote execution

Point the agent at a remote machine. Every tool call runs there.

```typescript
import { createAgent, SSHBackend } from "subagent"

const agent = await createAgent({
  model: "anthropic:claude-sonnet-4-6",
  backend: new SSHBackend({
    host: "dev-server",
    username: "deploy",
    privateKeyPath: "~/.ssh/id_ed25519",
    cwd: "/app",
  }),
  warpGrep: true,
  fastApply: true,
})
```

| Backend | Use case |
|---------|----------|
| `LocalShellBackend` | Local filesystem + shell (default) |
| `SSHBackend` | Remote machines via SSH/SFTP |
| `FilesystemBackend` | File operations only, no shell |

Implement `Backend` or `SandboxBackend` for custom targets (containers, cloud APIs, etc).

## Teams

For longer projects, subagents are ephemeral. Teams are persistent agents that coordinate through inboxes.

```typescript
import { createAgent, SSHBackend } from "subagent"

const agent = await createAgent({
  model: "anthropic:claude-sonnet-4-6",
  team: {
    name: "full-stack",
    teammates: [
      {
        name: "backend",
        description: "Build API endpoints and migrations",
        backend: new SSHBackend({ host: "api-server", username: "deploy", cwd: "/app/api" }),
      },
      {
        name: "frontend",
        description: "Build React components and pages",
      },
      {
        name: "qa",
        description: "Run integration tests",
        permissions: "read-only",
      },
    ],
  },
})

await agent.prompt("Add user settings page with email preferences backed by a new API endpoint")
await agent.waitForIdle()
```

Each teammate runs as a long-lived agent with its own context window and backend. They coordinate through inbox messages and shared task boards with dependency tracking.

## Work subagents (DOCX, PDF)

Specialized subagents for document manipulation.

```typescript
import { DocxAgent } from "subagent/work/docx"

const docx = new DocxAgent({ apiKey: process.env.MORPH_API_KEY })
const result = await docx.chat("Add a confidentiality clause to section 3", { documentId })
```

DOCX support includes track changes, comments, and full OOXML manipulation. PDF support covers form field reading and filling.

## `createAgent` options

| Option | Type | Description |
|--------|------|-------------|
| `model` | `string` | Model shorthand, e.g. `"anthropic:claude-sonnet-4-6"` |
| `systemPrompt` | `string` | Appended to the base prompt |
| `subagents` | `SubAgentConfig[]` | Specialist definitions for delegation |
| `tools` | `AgentTool[]` | Custom tools alongside built-ins |
| `backend` | `Backend` | File/shell backend (default: `LocalShellBackend`) |
| `team` | `TeamConfig` | Spawn teammates with inbox messaging |
| `memory` | `string[]` | Context files loaded into system prompt |
| `skills` | `string[]` | Skill markdown files loaded into system prompt |
| `warpGrep` | `boolean \| config` | Semantic codebase search |
| `fastApply` | `boolean \| config` | Smart code editing at 10,500 tok/s |
| `modelRouter` | `boolean \| config` | Route prompts to cheaper models |
| `compact` | `boolean \| config` | Compress old messages to prevent overflow |
| `githubSearch` | `boolean` | Search public GitHub repos |
| `thinkingLevel` | `"off" \| "light" \| "full"` | Reasoning depth |
| `name` | `string` | Agent name (used in logs and team communication) |
| `debug` | `boolean` | Debug logging |

## Environment variables

```bash
ANTHROPIC_API_KEY=    # or OPENAI_API_KEY, GOOGLE_API_KEY
MORPH_API_KEY=        # for WarpGrep, FastApply, Model Router, Compact
```

[Docs](https://subagents.com/docs) · [GitHub](https://github.com/morphllm/subagents) · MIT
