# Subagents & Composition

`Agent.AsTool`, `Agent.AsToolWith`, and `agent.AsTypedTool` expose an `*agent.Agent` as a standard `tool.Tool` so a parent agent can delegate subtasks through ordinary tool calls. Gojent contains no sequential, parallel, or loop graph DSL—concurrent and multi-step orchestration uses goroutines, channels, and standard Go functions.

## Expose a subagent with AsTool

Calling `researcher.AsTool()` wraps `researcher` into a tool named after `researcher.Name()` (sanitized for tool-name rules) accepting `agent.SubagentInput{Prompt: "..."}`.

By default, `AsTool` and `AsToolWith` return `agent.SubagentResult` in `tool.Result.Data` alongside the child's final `resp.Text`—omitting the full child message transcript to avoid quadratic context growth across delegation chains—and wrap the tool with `agent.WithoutDefaultToolTimeout` so `DefaultToolTimeout` does not cut off multi-step child runs (enclosing `Budget.MaxDuration` and context cancellation still apply):

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ijaidev/gojent/core/agent"
	"github.com/ijaidev/gojent/core/llm"
	"github.com/ijaidev/gojent/core/tool"
	"github.com/ijaidev/gojent/providers/mockllm"
)

func main() {
	researcher, err := agent.New(agent.Config{
		Name:         "researcher",
		Description:  "Finds primary sources",
		Instructions: "Find and cite primary sources.",
		Model:        mockllm.New("Primary source confirmed."),
	})
	if err != nil {
		log.Fatal(err)
	}

	turn := 0
	writerModel := mockllm.New().ApplyOptions(
		mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) {
			turn++
			if turn == 1 {
				return llm.NewSliceStream(ctx, []llm.StreamEvent{
					llm.MessageStart{Model: "mock-llm"},
					llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{
						CallID: "c1",
						Name:   "researcher",
						Input:  []byte(`{"prompt":"Summarize Gojent's core packages."}`),
					})},
					llm.PartEnd{Index: 0},
					llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool},
				}), nil
			}
			return llm.NewSliceStream(ctx, []llm.StreamEvent{
				llm.MessageStart{Model: "mock-llm"},
				llm.PartStart{Index: 0, Part: llm.NewTextPart("")},
				llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Article drafted from primary sources."},
				llm.PartEnd{Index: 0},
				llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop},
			}), nil
		}),
	)

	writer, err := agent.New(agent.Config{
		Name:         "writer",
		Instructions: "Draft an article using the researcher's findings.",
		Model:        writerModel,
		Tools:        []tool.Tool{researcher.AsTool()},
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := writer.Generate(context.Background(), "Write a brief note on Gojent.")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Text)
}
```

## Customize behavior with AsToolConfig and AsTypedTool

Use `Agent.AsToolWith(agent.AsToolConfig{...})` to override tool metadata, set child `RunOptions`, supply a custom `FormatResult`, cap nesting with `MaxDepth`, or opt out of shared budgets (`IsolateBudget`), policy inheritance (`DisablePolicyInheritance`), or event forwarding (`DisableEventForwarding`).

For structured contracts, `agent.AsTypedTool[In, Out]` validates `In` against its generated schema (and `tool.Validator`), constrains the child with `WithOutputSchema[Out]`, validates and decodes the child's JSON into `Out`, and returns `Out` in `tool.Result.Data`:

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ijaidev/gojent/core/agent"
	"github.com/ijaidev/gojent/core/llm"
	"github.com/ijaidev/gojent/core/tool"
	"github.com/ijaidev/gojent/providers/mockllm"
)

type ReviewInput struct {
	Target string `json:"target" description:"Package or file to review"`
}

type ReviewOutput struct {
	Approved bool   `json:"approved"`
	Summary  string `json:"summary"`
}

func main() {
	reviewer, err := agent.New(agent.Config{
		Name:         "reviewer",
		Instructions: "Return a structured review verdict.",
		Model:        mockllm.New(`{"approved":true,"summary":"Checks pass."}`),
	})
	if err != nil {
		log.Fatal(err)
	}

	// Custom formatting on AsToolWith when you want to inspect the full *agent.Response.
	compactTool := reviewer.AsToolWith(agent.AsToolConfig{
		Name:        "review_summary",
		Description: "Review a change and return a one-line summary.",
		MaxDepth:    2,
		Options:     agent.RunOptions{Budget: agent.Budget{MaxSteps: 6}},
		FormatResult: func(_ context.Context, _ *agent.Response, summary agent.SubagentResult) (tool.Result, error) {
			return tool.Result{
				Data:    summary,
				Content: []llm.Part{llm.NewTextPart(fmt.Sprintf("%s (%d steps)", summary.Text, summary.Steps))},
			}, nil
		},
	})

	// Typed schema-enforced delegation with AsTypedTool.
	typedTool, err := agent.AsTypedTool(reviewer, agent.TypedSubagentConfig[ReviewInput, ReviewOutput]{
		Name:        "typed_review",
		Description: "Run a structured review and return ReviewOutput.",
		Prompt: func(in ReviewInput) (string, error) {
			return "Review " + in.Target, nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	turn := 0
	leadModel := mockllm.New().ApplyOptions(
		mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) {
			turn++
			if turn == 1 {
				return llm.NewSliceStream(ctx, []llm.StreamEvent{
					llm.MessageStart{Model: "mock-llm"},
					llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{
						CallID: "c1",
						Name:   "typed_review",
						Input:  []byte(`{"target":"core/agent"}`),
					})},
					llm.PartEnd{Index: 0},
					llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool},
				}), nil
			}
			return llm.NewSliceStream(ctx, []llm.StreamEvent{
				llm.MessageStart{Model: "mock-llm"},
				llm.PartStart{Index: 0, Part: llm.NewTextPart("")},
				llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Review approved."},
				llm.PartEnd{Index: 0},
				llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop},
			}), nil
		}),
	)

	lead, err := agent.New(agent.Config{
		Name:  "lead",
		Model: leadModel,
		Tools: []tool.Tool{compactTool, typedTool},
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := lead.Generate(context.Background(), "Review core/agent.")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Text)
}
```

## Delegation guarantees: ancestry, budgets, policies, and events

When a subagent runs inside an enclosing parent run's `context.Context` (whether via `AsTool`, `AsTypedTool`, or `(*agent.Agent).Generate`/`Stream`), the runner enforces four cross-run guarantees by default:

- **Ancestry and depth bounds:** Every run derives a `agent.RunAncestry` (`RunID`, `ParentRunID`, `ParentCallID`, `ParentSessionID`, `AgentPath`, `Depth`) retrievable via `agent.AncestryFromContext(ctx)`. Nesting depth is bounded by `agent.DefaultMaxSubagentDepth` (`4`) or the tightest ancestor `MaxSubagentDepth` ceiling; exceeding it fails immediately with `agent.ErrMaxDepthExceeded`.
- **Shared budgets and usage roll-up:** Child runs share `MaxToolCalls` and `MaxTotalTokens` budgets with their parent chain, and child model usage rolls up into parent `Response.Usage` and `SubagentResult.Usage`. Set `AsToolConfig.IsolateBudget` (or `agent.WithIsolateBudget(true)`) to give a child an independent budget and usage counter.
- **Fail-closed policy and approver inheritance:** Unless `DisablePolicyInheritance` (or `agent.WithDisablePolicyInheritance(true)`) is set, a child inherits the parent's `Policy` and `Approver`. If the child also defines its own `Policy`, both execute with fail-closed precedence (`Terminate` > `Deny`/`DecisionUnknown` > `Ask` > `Allow`) so a child policy can narrow permissions but never relax a parent's denial.
- **Live event forwarding:** Child events wrap into `agent.SubagentEvent` (carrying `ParentRunID`, `ParentCallID`, `RunID`, `Agent`, `AgentPath`, `Depth`, `Session`, and the inner `Event`) and forward to the parent's `Sink` unless `DisableEventForwarding` (or `agent.WithDisableEventForwarding(true)`) is set.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ijaidev/gojent/core/agent"
	"github.com/ijaidev/gojent/core/llm"
	"github.com/ijaidev/gojent/core/tool"
	"github.com/ijaidev/gojent/providers/mockllm"
)

func main() {
	inspect := tool.MustNew(tool.Config[struct{}, string]{
		ID:          "inspect",
		Description: "Return ancestry depth.",
		Annotations: tool.Annotations{ReadOnly: true},
		Execute: func(ctx context.Context, _ struct{}) (string, error) {
			ancestry, ok := agent.AncestryFromContext(ctx)
			if !ok {
				return "no ancestry", nil
			}
			return fmt.Sprintf("depth=%d path=%v", ancestry.Depth, ancestry.AgentPath), nil
		},
	})

	childTurn := 0
	childModel := mockllm.New().ApplyOptions(
		mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) {
			childTurn++
			if childTurn == 1 {
				return llm.NewSliceStream(ctx, []llm.StreamEvent{
					llm.MessageStart{Model: "mock-llm"},
					llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{
						CallID: "c_leaf",
						Name:   "inspect",
						Input:  []byte(`{}`),
					})},
					llm.PartEnd{Index: 0},
					llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool},
				}), nil
			}
			return llm.NewSliceStream(ctx, []llm.StreamEvent{
				llm.MessageStart{Model: "mock-llm"},
				llm.PartStart{Index: 0, Part: llm.NewTextPart("")},
				llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Child inspected."},
				llm.PartEnd{Index: 0},
				llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop},
			}), nil
		}),
	)

	child, err := agent.New(agent.Config{
		Name:  "inspector",
		Model: childModel,
		Tools: []tool.Tool{inspect},
	})
	if err != nil {
		log.Fatal(err)
	}

	parentTurn := 0
	parentModel := mockllm.New().ApplyOptions(
		mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) {
			parentTurn++
			if parentTurn == 1 {
				return llm.NewSliceStream(ctx, []llm.StreamEvent{
					llm.MessageStart{Model: "mock-llm"},
					llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{
						CallID: "c_sub",
						Name:   "inspector",
						Input:  []byte(`{"prompt":"check ancestry"}`),
					})},
					llm.PartEnd{Index: 0},
					llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool},
				}), nil
			}
			return llm.NewSliceStream(ctx, []llm.StreamEvent{
				llm.MessageStart{Model: "mock-llm"},
				llm.PartStart{Index: 0, Part: llm.NewTextPart("")},
				llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Done."},
				llm.PartEnd{Index: 0},
				llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop},
			}), nil
		}),
	)

	parent, err := agent.New(agent.Config{
		Name:  "orchestrator",
		Model: parentModel,
		Tools: []tool.Tool{child.AsTool()},
	})
	if err != nil {
		log.Fatal(err)
	}

	forwarded := 0
	resp, err := parent.Generate(
		context.Background(),
		"Run inspector.",
		agent.WithSink(agent.SinkFunc(func(ev agent.Event) {
			if _, ok := ev.(agent.SubagentEvent); ok {
				forwarded++
			}
		})),
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Text, "forwarded:", forwarded > 0)
}
```

## Ordinary Go composition

Because an `*agent.Agent` is immutable and safe for concurrent runs, fan-out, pipelines, and conditional branching require no framework primitives—call `Generate` or `Stream` inside standard goroutines, `sync.WaitGroup`, or `errgroup`, and pass the parent `ctx` so cancellation propagates cleanly. For managed background subagents, multi-turn resume, and git-worktree isolation, see [Ready-Made Tools](/docs/modules/tools). See [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Agent.AsTool) for full signatures.
