diff --git a/README.md b/README.md index 330376095..67a55ec52 100644 --- a/README.md +++ b/README.md @@ -377,6 +377,8 @@ mcpServers: --json Output response as JSON (non-interactive only) --no-exit Enter interactive mode after prompt completes --max-steps Maximum agent steps (0 for unlimited) +--max-subagents Maximum subagents the agent can spawn (default: 10, -1 for unlimited, 0 to disable) +--max-nested-subagents Maximum nested subagents a subagent can spawn (default: 3, -1 for unlimited, 0 to disable) --stream Enable streaming output (default: true) --compact Enable compact output mode --auto-compact Auto-compact conversation near context limit (reactive compact-and-retry on provider context-overflow errors is always on) diff --git a/cmd/root.go b/cmd/root.go index 7cb16335e..1a16ed0f2 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -39,12 +39,14 @@ var ( positionalPrompt string // set by processPositionalArgs from CLI positional args positionalFiles []ui.FilePart // binary @file parts from processPositionalArgs - quietFlag bool - jsonFlag bool - noExitFlag bool - maxSteps int - streamFlag bool // Enable streaming output - autoCompactFlag bool // Enable auto-compaction near context limit + quietFlag bool + jsonFlag bool + noExitFlag bool + maxSteps int + maxSubagents int + maxNestedSubagents int + streamFlag bool // Enable streaming output + autoCompactFlag bool // Enable auto-compaction near context limit // Session management sessionPath string @@ -417,6 +419,10 @@ func init() { BoolVar(&noExitFlag, "no-exit", false, "enter interactive mode after non-interactive prompt completes") rootCmd.PersistentFlags(). IntVar(&maxSteps, "max-steps", 0, "maximum number of agent steps (0 for unlimited)") + rootCmd.PersistentFlags(). + IntVar(&maxSubagents, "max-subagents", 10, "maximum concurrent subagents the agent can run (use -1 for unlimited, 0 to disable)") + rootCmd.PersistentFlags(). + IntVar(&maxNestedSubagents, "max-nested-subagents", 3, "maximum concurrent nested subagents a subagent can run (use -1 for unlimited, 0 to disable)") rootCmd.PersistentFlags(). BoolVar(&streamFlag, "stream", true, "enable streaming output for faster response display") rootCmd.PersistentFlags(). @@ -510,6 +516,8 @@ func init() { _ = viper.BindPFlag("decision-model", rootCmd.PersistentFlags().Lookup("decision-model")) _ = viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) _ = viper.BindPFlag("max-steps", rootCmd.PersistentFlags().Lookup("max-steps")) + _ = viper.BindPFlag("max-subagents", rootCmd.PersistentFlags().Lookup("max-subagents")) + _ = viper.BindPFlag("max-nested-subagents", rootCmd.PersistentFlags().Lookup("max-nested-subagents")) _ = viper.BindPFlag("stream", rootCmd.PersistentFlags().Lookup("stream")) _ = viper.BindPFlag("auto-compact", rootCmd.PersistentFlags().Lookup("auto-compact")) diff --git a/cmd/run_mode.go b/cmd/run_mode.go index d200b05e4..9494e2d00 100644 --- a/cmd/run_mode.go +++ b/cmd/run_mode.go @@ -221,6 +221,15 @@ func buildKitOptions(mcpConfig *config.Config, authHandler *kit.CLIMCPAuthHandle } } + if viper.IsSet("max-subagents") { + v := viper.GetInt("max-subagents") + opts.MaxSubagents = &v + } + if viper.IsSet("max-nested-subagents") { + v := viper.GetInt("max-nested-subagents") + opts.MaxNestedSubagents = &v + } + return opts, nil } diff --git a/cmd/setup.go b/cmd/setup.go index 95b40f015..dc470024e 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -52,14 +52,16 @@ func DisplayDebugConfig(cli *ui.CLI, k *kit.Kit, mcpConfig *config.Config, provi } debugConfig := map[string]any{ - "model": viper.GetString("model"), - "max-steps": viper.GetInt("max-steps"), - "max-tokens": viper.GetInt("max-tokens"), - "temperature": viper.GetFloat64("temperature"), - "top-p": viper.GetFloat64("top-p"), - "top-k": viper.GetInt("top-k"), - "provider-url": viper.GetString("provider-url"), - "system-prompt": viper.GetString("system-prompt"), + "model": viper.GetString("model"), + "max-steps": viper.GetInt("max-steps"), + "max-subagents": viper.GetInt("max-subagents"), + "max-nested-subagents": viper.GetInt("max-nested-subagents"), + "max-tokens": viper.GetInt("max-tokens"), + "temperature": viper.GetFloat64("temperature"), + "top-p": viper.GetFloat64("top-p"), + "top-k": viper.GetInt("top-k"), + "provider-url": viper.GetString("provider-url"), + "system-prompt": viper.GetString("system-prompt"), } if viper.GetBool("tls-skip-verify") { diff --git a/internal/config/config.go b/internal/config/config.go index 03d1e6d9c..08faebc07 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -269,15 +269,17 @@ type LimitConfig struct { // model settings, UI preferences, and API credentials. It supports both command-line // flags and configuration file settings. type Config struct { - MCPServers map[string]MCPServerConfig `json:"mcpServers" yaml:"mcpServers"` - Model string `json:"model,omitempty" yaml:"model,omitempty"` - MaxSteps int `json:"max-steps,omitempty" yaml:"max-steps,omitempty"` - Debug bool `json:"debug,omitempty" yaml:"debug,omitempty"` - SystemPrompt string `json:"system-prompt,omitempty" yaml:"system-prompt,omitempty"` - ProviderAPIKey string `json:"provider-api-key,omitempty" yaml:"provider-api-key,omitempty"` - ProviderURL string `json:"provider-url,omitempty" yaml:"provider-url,omitempty"` - Stream *bool `json:"stream,omitempty" yaml:"stream,omitempty"` - Theme any `json:"theme" yaml:"theme"` + MCPServers map[string]MCPServerConfig `json:"mcpServers" yaml:"mcpServers"` + Model string `json:"model,omitempty" yaml:"model,omitempty"` + MaxSteps int `json:"max-steps,omitempty" yaml:"max-steps,omitempty"` + MaxSubagents int `json:"max-subagents,omitempty" yaml:"max-subagents,omitempty"` + MaxNestedSubagents int `json:"max-nested-subagents,omitempty" yaml:"max-nested-subagents,omitempty"` + Debug bool `json:"debug,omitempty" yaml:"debug,omitempty"` + SystemPrompt string `json:"system-prompt,omitempty" yaml:"system-prompt,omitempty"` + ProviderAPIKey string `json:"provider-api-key,omitempty" yaml:"provider-api-key,omitempty"` + ProviderURL string `json:"provider-url,omitempty" yaml:"provider-url,omitempty"` + Stream *bool `json:"stream,omitempty" yaml:"stream,omitempty"` + Theme any `json:"theme" yaml:"theme"` // Model generation parameters MaxTokens int `json:"max-tokens,omitempty" yaml:"max-tokens,omitempty"` Temperature *float32 `json:"temperature,omitempty" yaml:"temperature,omitempty"` @@ -513,6 +515,8 @@ mcpServers: # model: "anthropic/claude-sonnet-4-5-20250929" # Default model to use # decision-model: "openrouter/typesafe/jev-1.14" # Default model for extension Decide calls # max-steps: 10 # Maximum agent steps (0 for unlimited) +# max-subagents: 10 # Maximum concurrent subagents the agent can run (-1 for unlimited, 0 to disable) +# max-nested-subagents: 3 # Maximum concurrent nested subagents a subagent can run (-1 for unlimited, 0 to disable) # debug: false # Enable debug logging # system-prompt: "/path/to/system-prompt.txt" # System prompt text file diff --git a/internal/core/subagent.go b/internal/core/subagent.go index 76167badc..c70a1e24c 100644 --- a/internal/core/subagent.go +++ b/internal/core/subagent.go @@ -107,7 +107,7 @@ type NamedAgentSpec struct { const subagentBaseDescription = `Spawn a subagent to perform a task autonomously. The subagent runs as a separate in-process Kit instance with full tool access -(except spawning further subagents). Use this to: +(with configured limits on spawning nested subagents). Use this to: - Delegate independent subtasks that can run in parallel - Perform research or analysis without blocking your main work - Execute tasks that benefit from a fresh context window @@ -190,6 +190,8 @@ func NewSubagentTool(opts ...ToolOption) fantasy.AgentTool { } func executeSubagent(ctx context.Context, call fantasy.ToolCall) (fantasy.ToolResponse, error) { + callerActive := ctx.Err() == nil + var args subagentArgs if err := parseArgs(call.Input, &args); err != nil { return fantasy.NewTextErrorResponse("task parameter is required"), nil @@ -240,6 +242,19 @@ func executeSubagent(ctx context.Context, call fantasy.ToolCall) (fantasy.ToolRe spawnCtx := ctx if background, _ := ctx.Value(backgroundJobKey{}).(bool); !background { spawnCtx = context.WithoutCancel(valuesContext{parent: ctx}) + // If the caller context was active at handler entry, propagate cancellation + // to the spawned subagent so a killed or timed-out parent promptly + // cancels in-flight nested delegation instead of leaving it running + // and blocking concurrency slots until its independent timeout expires. + // If the caller context was already canceled when the handler began, + // keep the detached context without cancellation propagation so the + // subagent can start cleanly with its own timeout. + if callerActive { + var cancel context.CancelFunc + spawnCtx, cancel = context.WithCancel(spawnCtx) + stop := context.AfterFunc(ctx, func() { cancel() }) + defer stop() + } } // Spawn in-process subagent. diff --git a/internal/core/subagent_test.go b/internal/core/subagent_test.go index c79e7deba..6e5cc393a 100644 --- a/internal/core/subagent_test.go +++ b/internal/core/subagent_test.go @@ -118,6 +118,65 @@ func TestSpawnContext_PreservesSpawnerValue(t *testing.T) { } } +func TestSpawnContext_PropagatesCancellationWhileRunning(t *testing.T) { + // Verify that if the parent context is alive on entry but is cancelled + // WHILE the subagent is executing, the detached context is cancelled + // promptly so the nested subagent doesn't block concurrency slots. + parent, cancel := context.WithCancel(context.Background()) + defer cancel() // fallback + + stop := make(chan struct{}) + defer close(stop) + + childCtxCh := make(chan context.Context, 1) + spawner := SubagentSpawnFunc(func(ctx context.Context, req SubagentSpawnRequest) (*SubagentSpawnResult, error) { + childCtxCh <- ctx + select { + case <-ctx.Done(): + case <-stop: + } + return &SubagentSpawnResult{Response: "cancelled"}, ctx.Err() + }) + + ctx := WithSubagentSpawner(parent, spawner) + + errCh := make(chan error, 1) + go func() { + _, err := executeSubagent(ctx, fantasy.ToolCall{ID: "tc1", Input: `{"task":"test"}`}) + errCh <- err + }() + + // Wait for the subagent tool to begin execution and extract its context. + var childCtx context.Context + select { + case childCtx = <-childCtxCh: + case <-time.After(1 * time.Second): + t.Fatal("subagent did not start in time") + } + + // Prove it is alive. + if childCtx.Err() != nil { + t.Fatalf("child context should be alive, got: %v", childCtx.Err()) + } + + // Cancel the parent context. + cancel() + + // Prove the child context cancels promptly. + select { + case <-childCtx.Done(): + case <-time.After(500 * time.Millisecond): + t.Fatal("child context did not propagate cancellation promptly") + } + + // Prove the execute function unblocks. + select { + case <-errCh: + case <-time.After(500 * time.Millisecond): + t.Fatal("executeSubagent did not unblock after cancellation") + } +} + func TestExecuteSubagent_ForwardsSessionID(t *testing.T) { // Issue #87: the optional session_id argument must reach the spawner so // the parent Kit can resume the existing subagent session. diff --git a/pkg/kit/config.go b/pkg/kit/config.go index f028b41db..9c82c56ca 100644 --- a/pkg/kit/config.go +++ b/pkg/kit/config.go @@ -72,6 +72,8 @@ func setSDKDefaults(v *viper.Viper) { v.SetDefault("model", "anthropic/claude-sonnet-4-5-20250929") v.SetDefault("system-prompt", defaultSystemPrompt) v.SetDefault("stream", true) + v.SetDefault("max-subagents", 10) + v.SetDefault("max-nested-subagents", 3) } // InitConfig initializes the process-global configuration store. diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index cf47ee9e0..98a59ad54 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -165,6 +165,13 @@ type Kit struct { // listed and killed (see RunningSubagents and KillSubagent). subagents subagentRegistry + subagentDepth int + maxSubagents int + maxNestedSubagents int + subagentSemMu sync.Mutex + subagentSem chan struct{} + onSubagentSlotWait func() + // skillCache holds skills discovered for this Kit instance. // Using a per-instance cache avoids cross-contamination when multiple // Kit instances exist in the same process. @@ -228,13 +235,64 @@ func (m *Kit) GetToolNames() []string { return names } -// GetToolsForSubagent like GetTools but eliminates subagent tool -// to avoid infinite recursion. +func (m *Kit) effectiveMaxSubagents() int { + if m.v == nil && m.maxSubagents == 0 && (m.opts == nil || m.opts.MaxSubagents == nil) { + return 10 + } + return m.maxSubagents +} + +func (m *Kit) effectiveMaxNestedSubagents() int { + if m.v == nil && m.maxNestedSubagents == 0 && (m.opts == nil || m.opts.MaxNestedSubagents == nil) { + return 3 + } + return m.maxNestedSubagents +} + +func (m *Kit) acquireSubagentSlot(ctx context.Context) (func(), error) { + limit := m.effectiveMaxSubagents() + if m.subagentDepth == 1 { + limit = m.effectiveMaxNestedSubagents() + } + if limit < 0 { + return func() {}, nil + } + + m.subagentSemMu.Lock() + if m.subagentSem == nil { + m.subagentSem = make(chan struct{}, limit) + } + sem := m.subagentSem + onWait := m.onSubagentSlotWait + m.subagentSemMu.Unlock() + + select { + case sem <- struct{}{}: + return func() { <-sem }, nil + default: + if onWait != nil { + onWait() + } + select { + case sem <- struct{}{}: + return func() { <-sem }, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } +} + +// GetToolsForSubagent returns the tool set passed to a child subagent. +// When nested subagents are enabled (subagentDepth == 0 and maxNestedSubagents != 0), +// the "subagent" tool is retained so the child subagent can spawn nested subagents. +// For depth >= 1, the "subagent" tool is excluded so nested subagents cannot spawn further. func (m *Kit) GetToolsForSubagent() []Tool { var tools []Tool for _, t := range m.agent.GetTools() { if t.Info().Name == "subagent" { - continue + if m.subagentDepth >= 1 || m.effectiveMaxNestedSubagents() == 0 { + continue + } } tools = append(tools, t) } @@ -1306,11 +1364,15 @@ type Options struct { // The wrapper must return a non-nil transport and be safe for concurrent use. HTTPTransport func(base http.RoundTripper) http.RoundTripper - Model string // Override model (e.g., "anthropic/claude-sonnet-4-5-20250929") - SystemPrompt string // Override system prompt - ConfigFile string // Override config file path - MaxSteps int // Override max steps (0 = use default) - ModelMode string // Model mode to select (empty selects the model default) + Model string // Override model (e.g., "anthropic/claude-sonnet-4-5-20250929") + SystemPrompt string // Override system prompt + ConfigFile string // Override config file path + MaxSteps int // Override max steps (0 = use default) + MaxSubagents *int // Override max subagents (default: 10, -1 = unlimited, 0 = disabled) + MaxNestedSubagents *int // Override max nested subagents (default: 3, -1 = unlimited, 0 = disabled) + SubagentDepth int // Nesting depth of this instance (0 = root, 1 = subagent, 2 = nested subagent) + onSubagentSlotWait func() // Internal callback fired when a subagent is about to wait for a concurrency slot + ModelMode string // Model mode to select (empty selects the model default) // DecisionModel is the default decision model in "provider/model" // format. Kit.Decide and extensions use it when a request names no @@ -1911,6 +1973,10 @@ func New(ctx context.Context, opts *Options) (*Kit, error) { prepareStep: hooks.prepareStep, stepContext: hooks.stepContext, runtimeExtraTools: append([]Tool(nil), extraTools...), + subagentDepth: opts.SubagentDepth, + maxSubagents: rc.maxSubagents, + maxNestedSubagents: rc.maxNestedSubagents, + onSubagentSlotWait: opts.onSubagentSlotWait, } // The agent setup above built the model with the same factory lookup. k.activeModelFromFactory = k.factoryBacked(rc.modelString) @@ -2433,12 +2499,16 @@ func toolsIncludeMCP(tools []Tool, mcpNames []string) bool { // parent replaced its core tools with Options.Tools, the child gets those // same tools (minus subagent), not the built-in ones. func (m *Kit) subagentDefaultTools() []Tool { + includeSubagent := m.subagentDepth < 1 && m.effectiveMaxNestedSubagents() != 0 if len(m.customTools) > 0 { tools := make([]Tool, 0, len(m.customTools)) for _, t := range m.customTools { // A subagent never gets the parent's code mode tool: that // instance tracks the parent's tool set. - if name := t.Info().Name; name != "subagent" && name != CodeModeToolName { + if name := t.Info().Name; name != CodeModeToolName { + if name == "subagent" && !includeSubagent { + continue + } tools = append(tools, t) } } @@ -2449,7 +2519,12 @@ func (m *Kit) subagentDefaultTools() []Tool { toolOpts = append(toolOpts, WithWorkDir(m.workDir)) } toolOpts = append(toolOpts, m.coreToolOptions...) - tools := SubagentTools(toolOpts...) + var tools []Tool + if includeSubagent { + tools = AllTools(toolOpts...) + } else { + tools = SubagentTools(toolOpts...) + } if m.coreToolList == nil { return tools } @@ -2472,6 +2547,20 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult return nil, fmt.Errorf("cannot resume subagent session: the parent uses an in-memory session (NoSession), so its subagents do too") } + // Enforce subagent spawn configuration: + // - Depth >= 2: nested subagents cannot spawn further subagents. + // - Depth 0: check if subagents are disabled (maxSubagents == 0). + // - Depth 1: check if nested subagents are disabled (maxNestedSubagents == 0). + if m.subagentDepth >= 2 { + return nil, fmt.Errorf("nested subagents cannot spawn further subagents (maximum depth reached)") + } + if m.subagentDepth == 0 && m.effectiveMaxSubagents() == 0 { + return nil, fmt.Errorf("subagents are disabled (max-subagents = 0)") + } + if m.subagentDepth == 1 && m.effectiveMaxNestedSubagents() == 0 { + return nil, fmt.Errorf("nested subagents are disabled (max-nested-subagents = 0)") + } + start := time.Now() // Resolve a resumable session up front: map the session UUID to its @@ -2603,18 +2692,22 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult // extended thinking). The child gets its own config store, so this does not // affect any other concurrent caller. streamOn := true + maxSubs := m.effectiveMaxSubagents() + maxNested := m.effectiveMaxNestedSubagents() childOpts := &Options{ - Model: model, - SystemPrompt: systemPrompt, - Tools: tools, - NoSession: cfg.NoSession, - SessionPath: resumePath, - Quiet: true, - Streaming: &streamOn, - MCPConfig: childMCPConfig, - // An empty tool set means no core tools. Without this the child - // would fall back to its own default (every core tool). - DisableCoreTools: len(tools) == 0, + Model: model, + SystemPrompt: systemPrompt, + Tools: tools, + NoSession: cfg.NoSession, + SessionPath: resumePath, + Quiet: true, + Streaming: &streamOn, + MCPConfig: childMCPConfig, + DisableCoreTools: len(tools) == 0, + SubagentDepth: m.subagentDepth + 1, + MaxSubagents: &maxSubs, + MaxNestedSubagents: &maxNested, + onSubagentSlotWait: m.onSubagentSlotWait, } // Inherit the parent's effective provider/runtime configuration. Since #40 @@ -2669,6 +2762,28 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult } m.subagents.update(runID, func(s *SubagentRun) { s.ParentSessionID = parentSessionID }) + // Acquire concurrency slot (queues if max-subagents or max-nested-subagents is reached). + release, err := m.acquireSubagentSlot(ctx) + if err != nil { + finalErr := err + if kerr := killedErr(err); kerr != err { + finalErr = kerr + } + status := "failed" + if errors.Is(finalErr, ErrSubagentKilled) { + status = "stopped" + } else if errors.Is(ctx.Err(), context.DeadlineExceeded) { + status = "timed_out" + } + m.subagents.update(runID, func(s *SubagentRun) { s.Status = status; s.Error = finalErr.Error(); s.FinishedAt = time.Now() }) + if errors.Is(finalErr, ErrSubagentKilled) { + return &SubagentResult{Elapsed: time.Since(start)}, finalErr + } + return &SubagentResult{Elapsed: time.Since(start)}, fmt.Errorf("failed to acquire subagent slot: %w", finalErr) + } + defer release() + m.subagents.update(runID, func(s *SubagentRun) { s.Status = "running" }) + child, err := New(ctx, childOpts) if err != nil { finalErr := err diff --git a/pkg/kit/kit_test.go b/pkg/kit/kit_test.go index 7b465f2e9..88ee64117 100644 --- a/pkg/kit/kit_test.go +++ b/pkg/kit/kit_test.go @@ -681,25 +681,75 @@ func TestGetToolsForSubagent(t *testing.T) { t.Fatalf("Failed to create Kit: %v", err) } defer func() { _ = host.Close() }() - toolsForSubagent := host.GetToolsForSubagent() - if len(toolsForSubagent) != 2 { - t.Fatalf("`GetToolsForSubagent()` should return 2 tools but has: %d", len(toolsForSubagent)) - } - hasTool := func(name string) bool { - for _, tool := range toolsForSubagent { + + hasTool := func(tools []kit.Tool, name string) bool { + for _, tool := range tools { if tool.Info().Name == name { return true } } return false } - if hasTool("subagent") { - t.Errorf("`GetToolsForSubagent()` unexpectedly includes the `subagent` tool") + + // 1. By default, nested subagents are enabled (default 3), so depth 0 includes subagent. + toolsDefault := host.GetToolsForSubagent() + if len(toolsDefault) != 3 { + t.Fatalf("`GetToolsForSubagent()` with nested subagents should return 3 tools but has: %d", len(toolsDefault)) } - if !hasTool("hello") { + if !hasTool(toolsDefault, "subagent") { + t.Errorf("`GetToolsForSubagent()` should include `subagent` by default") + } + if !hasTool(toolsDefault, "hello") { t.Errorf("`GetToolsForSubagent()` is missing the `hello` tool") } - if !hasTool("shell") { + if !hasTool(toolsDefault, "shell") { t.Errorf("`GetToolsForSubagent()` is missing the `shell` tool") } + + // 2. When max-nested-subagents is 0 (disabled), subagent is excluded. + zeroNested := 0 + hostNoNested, err := kit.New(ctx, &kit.Options{ + Model: "anthropic/claude-sonnet-4-5-20250929", + Quiet: true, + NoSession: true, + NoSkills: true, + NoExtensions: true, + CoreToolList: []string{"subagent", "bash"}, + ExtraTools: []kit.Tool{helloTool}, + MaxNestedSubagents: &zeroNested, + }) + if err != nil { + t.Fatalf("Failed to create Kit with zero nested: %v", err) + } + defer func() { _ = hostNoNested.Close() }() + toolsNoNested := hostNoNested.GetToolsForSubagent() + if len(toolsNoNested) != 2 { + t.Fatalf("`GetToolsForSubagent()` with 0 nested should return 2 tools but has: %d", len(toolsNoNested)) + } + if hasTool(toolsNoNested, "subagent") { + t.Errorf("`GetToolsForSubagent()` unexpectedly includes `subagent` when max-nested-subagents=0") + } + + // 3. When depth >= 1, subagent is excluded to prevent recursion beyond depth 2. + hostDepth1, err := kit.New(ctx, &kit.Options{ + Model: "anthropic/claude-sonnet-4-5-20250929", + Quiet: true, + NoSession: true, + NoSkills: true, + NoExtensions: true, + CoreToolList: []string{"subagent", "bash"}, + ExtraTools: []kit.Tool{helloTool}, + SubagentDepth: 1, + }) + if err != nil { + t.Fatalf("Failed to create Kit with depth 1: %v", err) + } + defer func() { _ = hostDepth1.Close() }() + toolsDepth1 := hostDepth1.GetToolsForSubagent() + if len(toolsDepth1) != 2 { + t.Fatalf("`GetToolsForSubagent()` for depth 1 should return 2 tools but has: %d", len(toolsDepth1)) + } + if hasTool(toolsDepth1, "subagent") { + t.Errorf("`GetToolsForSubagent()` unexpectedly includes `subagent` for depth >= 1") + } } diff --git a/pkg/kit/new.go b/pkg/kit/new.go index a0a0d8baa..e21335758 100644 --- a/pkg/kit/new.go +++ b/pkg/kit/new.go @@ -46,18 +46,20 @@ type resolvedConfig struct { loadedSkills []*Skill namedAgents []*AgentDefinition - debug bool - noExtensions bool - toolList []string - maxSteps int - streaming bool - shellTimeout int - shellMaxTimeout int - shell []string - imageMaxEdge int - imageMaxBytes int - imageNoResize bool - codeMode core.CodeModeConfig + debug bool + noExtensions bool + toolList []string + maxSteps int + maxSubagents int + maxNestedSubagents int + streaming bool + shellTimeout int + shellMaxTimeout int + shell []string + imageMaxEdge int + imageMaxBytes int + imageNoResize bool + codeMode core.CodeModeConfig hasCustomSystemPrompt bool systemPromptSource string @@ -151,6 +153,12 @@ func applyOptionOverrides(v *viper.Viper, opts *Options) { if opts.MaxSteps > 0 { v.Set("max-steps", opts.MaxSteps) } + if opts.MaxSubagents != nil { + v.Set("max-subagents", *opts.MaxSubagents) + } + if opts.MaxNestedSubagents != nil { + v.Set("max-nested-subagents", *opts.MaxNestedSubagents) + } // Only override streaming when the caller explicitly set it. Otherwise // leave the precedence chain (env → config → default true) untouched so a // zero-valued Options does not silently force stream=false. @@ -459,6 +467,8 @@ func resolveModelConfig(v *viper.Viper, opts *Options, providers map[string]Prov } rc.maxSteps = v.GetInt("max-steps") + rc.maxSubagents = v.GetInt("max-subagents") + rc.maxNestedSubagents = v.GetInt("max-nested-subagents") rc.streaming = v.GetBool("stream") // Each of the two timeouts has a shell-named form and the bash-named // form it had before the tool's shell became configurable; see diff --git a/pkg/kit/options.go b/pkg/kit/options.go index 2a66e170c..00f4b2ce7 100644 --- a/pkg/kit/options.go +++ b/pkg/kit/options.go @@ -69,6 +69,14 @@ func WithStreaming(b bool) Option { // value; a non-zero value pins it and suppresses automatic right-sizing. func WithMaxTokens(n int) Option { return func(o *Options) { o.MaxTokens = n } } +// WithMaxSubagents sets the maximum number of concurrent subagents the agent can run. +// Default is 10 (-1 for unlimited, 0 to disable). +func WithMaxSubagents(n int) Option { return func(o *Options) { o.MaxSubagents = &n } } + +// WithMaxNestedSubagents sets the maximum number of concurrent nested subagents a subagent can run. +// Default is 3 (-1 for unlimited, 0 to disable). +func WithMaxNestedSubagents(n int) Option { return func(o *Options) { o.MaxNestedSubagents = &n } } + // WithModelMode selects a named mode for the selected model. Empty selects its default. func WithModelMode(mode string) Option { return func(o *Options) { o.ModelMode = mode } } diff --git a/pkg/kit/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go new file mode 100644 index 000000000..803446d22 --- /dev/null +++ b/pkg/kit/subagent_limits_test.go @@ -0,0 +1,427 @@ +package kit + +import ( + "context" + "strings" + "sync" + "testing" + "time" + + "github.com/mark3labs/kit/internal/core" +) + +type blockingModel struct { + *echoModel + started chan struct{} + release chan struct{} +} + +func (m *blockingModel) Generate(ctx context.Context, call LLMCall) (*LLMResponse, error) { + select { + case m.started <- struct{}{}: + default: + } + select { + case <-m.release: + return m.echoModel.Generate(ctx, call) + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (m *blockingModel) Stream(ctx context.Context, call LLMCall) (LLMStreamResponse, error) { + select { + case m.started <- struct{}{}: + default: + } + select { + case <-m.release: + return m.echoModel.Stream(ctx, call) + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func TestSubagent_MaxSubagentsLimit(t *testing.T) { + started := make(chan struct{}, 10) + release := make(chan struct{}) + slotWaiting := make(chan struct{}, 10) + + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &blockingModel{echoModel: &echoModel{provider: "mock", model: name}, started: started, release: release}}, nil + } + maxSubs := 2 + otherNested := 3 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + MaxSubagents: &maxSubs, + MaxNestedSubagents: &otherNested, + onSubagentSlotWait: func() { slotWaiting <- struct{}{} }, + }) + + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + var releaseOnce sync.Once + t.Cleanup(func() { + releaseOnce.Do(func() { close(release) }) + cancel() + wg.Wait() + }) + + errCh := make(chan error, 3) + + for i := range 3 { + wg.Add(1) + go func(id int) { + defer wg.Done() + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "test", NoSession: true, Tools: []Tool{}}) + errCh <- err + }(i) + } + + // 1. Verify that exactly maxSubs (2) subagents become active. + for i := range maxSubs { + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("expected subagent %d to become active, but it blocked", i+1) + } + } + + // 2. Verify the 3rd request reaches the limiter's wait point while both model calls remain blocked. + select { + case <-slotWaiting: + case <-time.After(1 * time.Second): + t.Fatal("timed out waiting for 3rd subagent to reach the limiter's wait point") + } + + finished := 0 + sendRelease := func() { + t.Helper() + for { + select { + case release <- struct{}{}: + return + case err := <-errCh: + finished++ + if err != nil { + t.Fatalf("worker failed: %v", err) + } + case <-time.After(1 * time.Second): + t.Fatal("timed out sending to release channel") + } + } + } + + // 3. Release one active subagent. + sendRelease() + + // 4. Verify the 3rd subagent now unblocks and becomes active. + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("3rd subagent did not become active after a slot was released") + } + + // Release the remaining two. + sendRelease() + sendRelease() + + // Ensure all finished without error. + for finished < 3 { + select { + case err := <-errCh: + finished++ + if err != nil { + t.Fatalf("subagent spawn failed (queueing failed): %v", err) + } + case <-time.After(1 * time.Second): + t.Fatalf("subagent did not return") + } + } +} + +func TestSubagent_MaxSubagentsDisabled(t *testing.T) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + maxSubs := 0 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + MaxSubagents: &maxSubs, + }) + + ctx := context.Background() + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "test 1", NoSession: true, Tools: []Tool{}}) + if err == nil { + t.Fatal("expected error when subagents are disabled, got nil") + } + if !strings.Contains(err.Error(), "subagents are disabled") { + t.Fatalf("unexpected error message: %v", err) + } +} + +func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { + started := make(chan struct{}, 10) + release := make(chan struct{}) + slotWaiting := make(chan struct{}, 10) + + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &blockingModel{echoModel: &echoModel{provider: "mock", model: name}, started: started, release: release}}, nil + } + otherSubs := 3 + maxNested := 2 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + SubagentDepth: 1, + MaxSubagents: &otherSubs, + MaxNestedSubagents: &maxNested, + onSubagentSlotWait: func() { slotWaiting <- struct{}{} }, + }) + + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + var releaseOnce sync.Once + t.Cleanup(func() { + releaseOnce.Do(func() { close(release) }) + cancel() + wg.Wait() + }) + + errCh := make(chan error, 3) + + for i := range 3 { + wg.Add(1) + go func(id int) { + defer wg.Done() + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "nested", NoSession: true, Tools: []Tool{}}) + errCh <- err + }(i) + } + + for i := range maxNested { + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("expected nested subagent %d to become active, but it blocked", i+1) + } + } + + // Verify the 3rd request reaches the limiter's wait point while both model calls remain blocked. + select { + case <-slotWaiting: + case <-time.After(1 * time.Second): + t.Fatal("timed out waiting for 3rd nested subagent to reach the limiter's wait point") + } + + finished := 0 + sendRelease := func() { + t.Helper() + for { + select { + case release <- struct{}{}: + return + case err := <-errCh: + finished++ + if err != nil { + t.Fatalf("worker failed: %v", err) + } + case <-time.After(1 * time.Second): + t.Fatal("timed out sending to release channel") + } + } + } + + sendRelease() + + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("3rd nested subagent did not become active after a slot was released") + } + + sendRelease() + sendRelease() + + for finished < 3 { + select { + case err := <-errCh: + finished++ + if err != nil { + t.Fatalf("nested subagent spawn failed (queueing failed): %v", err) + } + case <-time.After(1 * time.Second): + t.Fatalf("nested subagent did not return") + } + } +} + +func TestSubagent_NestedSubagentsDisabled(t *testing.T) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + zeroNested := 0 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + SubagentDepth: 1, + MaxNestedSubagents: &zeroNested, + }) + + ctx := context.Background() + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "nested 1", NoSession: true, Tools: []Tool{}}) + if err == nil { + t.Fatal("expected error when nested subagents are disabled, got nil") + } + if !strings.Contains(err.Error(), "nested subagents are disabled") { + t.Fatalf("unexpected error message: %v", err) + } +} + +func TestSubagent_Depth2CannotSpawn(t *testing.T) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + SubagentDepth: 2, + }) + + ctx := context.Background() + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "sub-nested", NoSession: true, Tools: []Tool{}}) + if err == nil { + t.Fatal("expected error for depth >= 2 subagent spawn, got nil") + } + if !strings.Contains(err.Error(), "cannot spawn further subagents") { + t.Fatalf("unexpected error message: %v", err) + } +} + +func TestSubagent_UnlimitedSubagents(t *testing.T) { + started := make(chan struct{}, 15) + release := make(chan struct{}) + + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &blockingModel{echoModel: &echoModel{provider: "mock", model: name}, started: started, release: release}}, nil + } + unlimited := -1 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + MaxSubagents: &unlimited, + }) + + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + var releaseOnce sync.Once + openRelease := func() { + releaseOnce.Do(func() { close(release) }) + } + t.Cleanup(func() { + openRelease() + cancel() + wg.Wait() + }) + + errCh := make(chan error, 15) + + for i := range 15 { + wg.Add(1) + go func(id int) { + defer wg.Done() + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "unlimited", NoSession: true, Tools: []Tool{}}) + errCh <- err + }(i) + } + + // Verify all 15 become active immediately because limits are unbounded + for i := range 15 { + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("expected subagent %d to become active, but it blocked", i+1) + } + } + + openRelease() + + for range 15 { + select { + case err := <-errCh: + if err != nil { + t.Fatalf("subagent spawn failed: %v", err) + } + case <-time.After(1 * time.Second): + t.Fatalf("subagent did not return") + } + } +} + +func TestGetToolsForSubagent_Limits(t *testing.T) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + + subTool := core.NewSubagentTool() + dummyTool := NewTool("dummy", "A dummy tool", func(ctx context.Context, input struct{}) (ToolOutput, error) { + return TextResult("dummy"), nil + }) + + hasTool := func(tools []Tool, name string) bool { + for _, tool := range tools { + if tool.Info().Name == name { + return true + } + } + return false + } + + // 1. By default, nested subagents are enabled (default 3), so depth 0 includes subagent. + kDefault := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + Tools: []Tool{subTool, dummyTool}, + }) + toolsDefault := kDefault.GetToolsForSubagent() + if !hasTool(toolsDefault, "subagent") { + t.Errorf("expected GetToolsForSubagent() to include subagent by default") + } + if !hasTool(toolsDefault, "dummy") { + t.Errorf("expected GetToolsForSubagent() to include dummy tool") + } + + // 2. When max-nested-subagents is 0 (disabled), subagent is excluded. + zeroNested := 0 + kNoNested := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + Tools: []Tool{subTool, dummyTool}, + MaxNestedSubagents: &zeroNested, + }) + toolsNoNested := kNoNested.GetToolsForSubagent() + if hasTool(toolsNoNested, "subagent") { + t.Errorf("expected GetToolsForSubagent() to exclude subagent when max-nested-subagents=0") + } + if !hasTool(toolsNoNested, "dummy") { + t.Errorf("expected GetToolsForSubagent() to include dummy tool") + } + + // 3. When depth >= 1, subagent is excluded to prevent recursion beyond depth 2. + kDepth1 := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + Tools: []Tool{subTool, dummyTool}, + SubagentDepth: 1, + }) + toolsDepth1 := kDepth1.GetToolsForSubagent() + if hasTool(toolsDepth1, "subagent") { + t.Errorf("expected GetToolsForSubagent() to exclude subagent for depth >= 1") + } + if !hasTool(toolsDepth1, "dummy") { + t.Errorf("expected GetToolsForSubagent() to include dummy tool") + } +} diff --git a/skills/kit-sdk/references/options.md b/skills/kit-sdk/references/options.md index 7da46abf2..42ce8fde9 100644 --- a/skills/kit-sdk/references/options.md +++ b/skills/kit-sdk/references/options.md @@ -227,6 +227,9 @@ This inventory links configuration to the [authoritative Go contract](https://pk | `MCPTaskTimeout` | MCPTaskTimeout is the maximum wall-clock duration to wait for a task-augmented tool call to reach a terminal state. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `MCPTokenStoreFactory` | MCPTokenStoreFactory, if non-nil, is called to create a token store for each remote MCP server that requires OAuth. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `MaxSteps` | Override max steps (0 = use default). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | +| `MaxSubagents` | MaxSubagents limits how many concurrent subagents this Kit instance can run (default: 10, -1 = unlimited, 0 = disabled). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | +| `MaxNestedSubagents` | MaxNestedSubagents limits how many concurrent nested subagents a subagent can run (default: 3, -1 = unlimited, 0 = disabled). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | +| `SubagentDepth` | SubagentDepth tracks the nesting depth of this Kit instance (0 = root, 1 = subagent, 2 = nested subagent). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `MaxTokens` | MaxTokens overrides the maximum output tokens per LLM response. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `ModelMode` | Model mode to select (empty selects the model default). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `Model` | Override model (e.g., "anthropic/claude-sonnet-4-5-20250929"). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | @@ -279,6 +282,8 @@ This inventory links configuration to the [authoritative Go contract](https://pk | `WithExtraTools` | WithExtraTools adds tools alongside the core/MCP/extension tools rather than replacing them. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithExtraTools) | | `WithHTTPTransport` | WithHTTPTransport wraps the base HTTP transport of built-in providers. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithHTTPTransport) | | `WithMaxTokens` | WithMaxTokens sets the maximum output tokens per LLM response. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxTokens) | +| `WithMaxSubagents` | WithMaxSubagents sets the maximum number of concurrent subagents the agent can run. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxSubagents) | +| `WithMaxNestedSubagents` | WithMaxNestedSubagents sets the maximum number of concurrent nested subagents a subagent can run. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxNestedSubagents) | | `WithModelMode` | WithModelMode selects a named mode for the selected model. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithModelMode) | | `WithModel` | WithModel sets the model in "provider/model" format (for example openai/gpt-4.1). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithModel) | | `WithDecisionModel` | WithDecisionModel sets the default decision model in "provider/model" format (e.g. openrouter/typesafe/jev-1.14). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithDecisionModel) | diff --git a/www/pages/advanced/subagents.md b/www/pages/advanced/subagents.md index 504de8dab..4b219c56a 100644 --- a/www/pages/advanced/subagents.md +++ b/www/pages/advanced/subagents.md @@ -48,7 +48,15 @@ subagent( ) ``` -Subagents run as separate in-process Kit instances and inherit the parent's active tools minus `subagent` (to prevent recursion); named-agent presets and tool allowlists can narrow that set further. They can run in parallel. +Subagents run as separate in-process Kit instances and inherit the parent's active tools; named-agent presets and tool allowlists can narrow that set further. They can run in parallel. + +### Spawning limits and nested subagents + +Kit provides control over subagent concurrency via CLI flags and configuration. When the LLM requests to spawn more subagents than the configured limit, the extra requests are **queued** and will automatically run as active subagents finish their tasks. + +- **Root subagents (`--max-subagents`, default `10`):** Limits how many concurrent subagents the host agent can run (`-1` for unlimited, `0` to disable). +- **Nested subagents (`--max-nested-subagents`, default `3`):** Allows subagents to run nested child subagents concurrently up to the configured limit (`-1` for unlimited, `0` to disable nested delegation). +- **Strict recursion cap:** Nested subagents (depth ≥ 2) have the `subagent` tool stripped from their toolset and cannot spawn further subagents. ### Subagent status bar @@ -167,7 +175,7 @@ Two built-in agents ship with Kit: ### Tool allowlists -An agent without a `tools:` list gets the default subagent tool set (everything except `subagent`, preventing recursion). With a `tools:` allowlist, the subagent is restricted to exactly those tools — a read-only `explore`-style agent cannot edit files or run commands. Explicit `model` / `system_prompt` / `timeout_seconds` arguments in the tool call override the agent's presets. +An agent without a `tools:` list gets the default subagent tool set (including `subagent` if nested subagents are enabled and depth < 2). With a `tools:` allowlist, the subagent is restricted to exactly those tools — a read-only `explore`-style agent cannot edit files or run commands. Explicit `model` / `system_prompt` / `timeout_seconds` arguments in the tool call override the agent's presets. Disable named-agent discovery entirely with `--no-agents`, the `no-agents` config key, or `KIT_NO_AGENTS=true`. diff --git a/www/pages/cli/flags.md b/www/pages/cli/flags.md index 41a8d9b9a..4ecf74893 100644 --- a/www/pages/cli/flags.md +++ b/www/pages/cli/flags.md @@ -38,6 +38,8 @@ These flags control Kit's behavior. When a prompt is passed as a positional argu | `--json` | — | `false` | Output response as JSON (non-interactive only) | | `--no-exit` | — | `false` | Enter interactive mode after prompt completes | | `--max-steps` | — | `0` | Maximum agent steps (0 for unlimited) | +| `--max-subagents` | — | `10` | Maximum concurrent subagents the agent can run (-1 for unlimited, 0 to disable) | +| `--max-nested-subagents` | — | `3` | Maximum concurrent nested subagents a subagent can run (-1 for unlimited, 0 to disable) | | `--stream` | — | `true` | Enable streaming output | | `--compact` | — | `false` | Enable compact output mode | | `--pick-dir` | — | `false` | Choose a working directory with a picker before starting. The daemon uses this flag for any [detachable session](/cli/commands#detachable-sessions) that has no directory of its own — `kit attach --new`, or a remote client | diff --git a/www/pages/configuration.md b/www/pages/configuration.md index fd6d2f19e..62ee8d3df 100644 --- a/www/pages/configuration.md +++ b/www/pages/configuration.md @@ -39,6 +39,8 @@ stream: true | `compact` | bool | `false` | Enable compact output mode | | `system-prompt` | string | — | System prompt text or file path | | `max-steps` | int | `0` | Maximum agent steps (0 = unlimited) | +| `max-subagents` | int | `10` | Maximum concurrent subagents the agent can run (-1 for unlimited, 0 to disable) | +| `max-nested-subagents` | int | `3` | Maximum concurrent nested subagents a subagent can run (-1 for unlimited, 0 to disable) | | `thinking-level` | string | `off` | Model-specific reasoning effort. `/thinking` lists catalog choices; explicit unsupported CLI/SDK values return an error. `off` omits effort; `none` is literal. | | `provider-api-key` | string | — | API key for the provider | | `provider-url` | string | — | Base URL for provider API | diff --git a/www/pages/sdk/api-reference.md b/www/pages/sdk/api-reference.md index e2a341e00..f6469070f 100644 --- a/www/pages/sdk/api-reference.md +++ b/www/pages/sdk/api-reference.md @@ -176,6 +176,8 @@ Guides: [overview](/sdk/overview), [options](/sdk/options), [decisions](/sdk/dec - [`WithExtraTools`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithExtraTools) — WithExtraTools adds tools alongside the core/MCP/extension tools rather than replacing them. - [`WithHTTPTransport`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithHTTPTransport) — WithHTTPTransport wraps the base HTTP transport of built-in providers. - [`WithMaxTokens`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxTokens) — WithMaxTokens sets the maximum output tokens per LLM response. +- [`WithMaxSubagents`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxSubagents) — WithMaxSubagents sets the maximum number of concurrent subagents the agent can run. +- [`WithMaxNestedSubagents`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxNestedSubagents) — WithMaxNestedSubagents sets the maximum number of concurrent nested subagents a subagent can run. - [`WithModelMode`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithModelMode) — WithModelMode selects a named mode for the selected model. - [`WithModel`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithModel) — WithModel sets the model in "provider/model" format. - [`WithDecisionModel`](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithDecisionModel) — WithDecisionModel sets the default decision model in "provider/model" format. diff --git a/www/pages/sdk/options.md b/www/pages/sdk/options.md index ef34b610a..c10424871 100644 --- a/www/pages/sdk/options.md +++ b/www/pages/sdk/options.md @@ -651,6 +651,9 @@ This inventory links configuration to the [authoritative Go contract](https://pk | `MCPTaskTimeout` | MCPTaskTimeout is the maximum wall-clock duration to wait for a task-augmented tool call to reach a terminal state. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `MCPTokenStoreFactory` | MCPTokenStoreFactory, if non-nil, is called to create a token store for each remote MCP server that requires OAuth. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `MaxSteps` | Override max steps (0 = use default). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | +| `MaxSubagents` | MaxSubagents limits how many concurrent subagents this Kit instance can run (default: 10, -1 = unlimited, 0 = disabled). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | +| `MaxNestedSubagents` | MaxNestedSubagents limits how many concurrent nested subagents a subagent can run (default: 3, -1 = unlimited, 0 = disabled). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | +| `SubagentDepth` | SubagentDepth tracks the nesting depth of this Kit instance (0 = root, 1 = subagent, 2 = nested subagent). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `MaxTokens` | MaxTokens overrides the maximum output tokens per LLM response. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `ModelMode` | Model mode to select (empty selects the model default). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | | `Model` | Override model (e.g., "anthropic/claude-sonnet-4-5-20250929"). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#Options) | @@ -703,6 +706,8 @@ This inventory links configuration to the [authoritative Go contract](https://pk | `WithExtraTools` | WithExtraTools adds tools alongside the core/MCP/extension tools rather than replacing them. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithExtraTools) | | `WithHTTPTransport` | WithHTTPTransport wraps the base HTTP transport of built-in providers. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithHTTPTransport) | | `WithMaxTokens` | WithMaxTokens sets the maximum output tokens per LLM response. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxTokens) | +| `WithMaxSubagents` | WithMaxSubagents sets the maximum number of concurrent subagents the agent can run. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxSubagents) | +| `WithMaxNestedSubagents` | WithMaxNestedSubagents sets the maximum number of concurrent nested subagents a subagent can run. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithMaxNestedSubagents) | | `WithModelMode` | WithModelMode selects a named mode for the selected model. [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithModelMode) | | `WithModel` | WithModel sets the model in "provider/model" format (for example openai/gpt-4.1). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithModel) | | `WithDecisionModel` | WithDecisionModel sets the default decision model in "provider/model" format (e.g. openrouter/typesafe/jev-1.14). [Go reference](https://pkg.go.dev/github.com/mark3labs/kit/pkg/kit#WithDecisionModel) |