From 45a4684a8e84abf5618d58488cbc7c2fdb89ef17 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Tue, 17 Nov 2026 23:03:25 +0530 Subject: [PATCH 01/10] feat(subagent): support nested subagents and concurrency queuing Add support for nested subagents up to depth 2 and introduce configurable concurrency limits via --max-subagents (default: 10) and --max-nested-subagents (default: 3). When the LLM requests more subagents than the configured concurrency limit, subagent requests are queued via an internal semaphore and executed as active subagent slots become available, rather than failing with an error. - Add --max-subagents and --max-nested-subagents CLI flags and config keys. - Add WithMaxSubagents and WithMaxNestedSubagents SDK options. - Retain the subagent tool for depth 1 subagents when nested subagents are enabled, allowing them to spawn child subagents. - Strip the subagent tool from depth 2 nested subagents to strictly cap recursion. - Manage concurrency using per-instance buffered channel semaphores with context cancellation. - Add unit tests verifying concurrency queueing and depth enforcement. - Update documentation in www/, SDK references, and README. --- README.md | 2 + cmd/root.go | 12 +- cmd/run_mode.go | 9 ++ cmd/setup.go | 18 ++- internal/config/config.go | 8 +- internal/core/subagent.go | 2 +- pkg/kit/config.go | 2 + pkg/kit/kit.go | 138 ++++++++++++++--- pkg/kit/kit_test.go | 70 +++++++-- pkg/kit/new.go | 16 +- pkg/kit/options.go | 8 + pkg/kit/subagent_limits_test.go | 215 +++++++++++++++++++++++++++ skills/kit-sdk/references/options.md | 5 + www/pages/advanced/subagents.md | 12 +- www/pages/cli/flags.md | 2 + www/pages/configuration.md | 2 + www/pages/sdk/api-reference.md | 2 + www/pages/sdk/options.md | 5 + 18 files changed, 482 insertions(+), 46 deletions(-) create mode 100644 pkg/kit/subagent_limits_test.go 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..bc16e7ca6 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -42,8 +42,10 @@ var ( quietFlag bool jsonFlag bool noExitFlag bool - maxSteps int - streamFlag bool // Enable streaming output + maxSteps int + maxSubagents int + maxNestedSubagents int + streamFlag bool // Enable streaming output autoCompactFlag bool // Enable auto-compaction near context limit // Session management @@ -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..95e328111 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -271,8 +271,10 @@ type LimitConfig struct { 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"` + 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"` @@ -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..19c8d713d 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 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..593f1019d 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -165,6 +165,12 @@ type Kit struct { // listed and killed (see RunningSubagents and KillSubagent). subagents subagentRegistry + subagentDepth int + maxSubagents int + maxNestedSubagents int + subagentSemMu sync.Mutex + subagentSem chan struct{} + // 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 +234,55 @@ 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 + m.subagentSemMu.Unlock() + + 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) } @@ -1309,8 +1357,11 @@ type Options struct { 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) + 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) + 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 +1962,9 @@ 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, } // The agent setup above built the model with the same factory lookup. k.activeModelFromFactory = k.factoryBacked(rc.modelString) @@ -2433,12 +2487,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 +2507,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 +2535,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 +2680,21 @@ 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, } // Inherit the parent's effective provider/runtime configuration. Since #40 @@ -2669,6 +2749,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..027bc8c42 100644 --- a/pkg/kit/new.go +++ b/pkg/kit/new.go @@ -48,9 +48,11 @@ type resolvedConfig struct { debug bool noExtensions bool - toolList []string - maxSteps int - streaming bool + toolList []string + maxSteps int + maxSubagents int + maxNestedSubagents int + streaming bool shellTimeout int shellMaxTimeout int shell []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..cdddd69ae --- /dev/null +++ b/pkg/kit/subagent_limits_test.go @@ -0,0 +1,215 @@ +package kit + +import ( + "context" + "strings" + "testing" + + "github.com/mark3labs/kit/internal/core" +) + +func TestSubagent_MaxSubagentsLimit(t *testing.T) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + maxSubs := 2 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + MaxSubagents: &maxSubs, + }) + + ctx := context.Background() + // Since maxSubs is 2, running 3 concurrently should not fail but simply queue. + // We verify they all finish without the "limit reached" error. + errCh := make(chan error, 3) + for i := range 3 { + go func(id int) { + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "test", NoSession: true, Tools: []Tool{}}) + errCh <- err + }(i) + } + + for range 3 { + if err := <-errCh; err != nil { + t.Fatalf("subagent spawn failed (queueing failed): %v", err) + } + } +} + +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) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + maxNested := 2 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + SubagentDepth: 1, + MaxNestedSubagents: &maxNested, + }) + + ctx := context.Background() + // Since maxNested is 2, running 3 concurrently should not fail but simply queue. + errCh := make(chan error, 3) + for i := range 3 { + go func(id int) { + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "nested", NoSession: true, Tools: []Tool{}}) + errCh <- err + }(i) + } + + for range 3 { + if err := <-errCh; err != nil { + t.Fatalf("nested subagent spawn failed (queueing failed): %v", err) + } + } +} + +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) { + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { + return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + } + unlimited := -1 + k := newProviderTestKit(t, &Options{ + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + MaxSubagents: &unlimited, + }) + + ctx := context.Background() + for i := range 15 { + _, err := k.Subagent(ctx, SubagentConfig{Prompt: "unlimited", NoSession: true, Tools: []Tool{}}) + if err != nil { + t.Fatalf("subagent spawn %d failed: %v", i+1, err) + } + } +} + +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) | From ab844ba87700fe3eb012138c8908f0c854451825 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Tue, 17 Nov 2026 23:11:16 +0530 Subject: [PATCH 02/10] style: format Go files with gofmt --- cmd/root.go | 8 ++++---- internal/config/config.go | 14 +++++++------- pkg/kit/kit.go | 6 +++--- pkg/kit/new.go | 18 +++++++++--------- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index bc16e7ca6..1a16ed0f2 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -39,14 +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 + 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 + autoCompactFlag bool // Enable auto-compaction near context limit // Session management sessionPath string diff --git a/internal/config/config.go b/internal/config/config.go index 95e328111..08faebc07 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -269,17 +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"` + 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"` + 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"` diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 593f1019d..4ec13bea8 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -1354,9 +1354,9 @@ 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 + 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) diff --git a/pkg/kit/new.go b/pkg/kit/new.go index 027bc8c42..e21335758 100644 --- a/pkg/kit/new.go +++ b/pkg/kit/new.go @@ -46,20 +46,20 @@ type resolvedConfig struct { loadedSkills []*Skill namedAgents []*AgentDefinition - debug bool - noExtensions bool + 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 + shellTimeout int + shellMaxTimeout int + shell []string + imageMaxEdge int + imageMaxBytes int + imageNoResize bool + codeMode core.CodeModeConfig hasCustomSystemPrompt bool systemPromptSource string From 421d8234e6e9672603410aec780b751dfeaddbbe Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 14:37:42 +0530 Subject: [PATCH 03/10] fix(subagent): propagate parent cancellation to in-flight child and strengthen tests This addresses the code review feedback: 1. Nested subagent tool execution now correctly propagates parent cancellation when the parent times out or is killed, instantly freeing concurrency slots rather than stranding them until child timeouts expire. 2. Subagent concurrency limits tests now use rigorous blocking mock models with channel-based synchronization to prove slots successfully block and unblock dynamically. --- internal/core/subagent.go | 10 ++ internal/core/subagent_test.go | 53 +++++++++++ pkg/kit/subagent_limits_test.go | 160 +++++++++++++++++++++++++++++--- 3 files changed, 210 insertions(+), 13 deletions(-) diff --git a/internal/core/subagent.go b/internal/core/subagent.go index 19c8d713d..8a7364b95 100644 --- a/internal/core/subagent.go +++ b/internal/core/subagent.go @@ -240,6 +240,16 @@ 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 alive on 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 ctx.Err() == nil { + 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..18f1f709f 100644 --- a/internal/core/subagent_test.go +++ b/internal/core/subagent_test.go @@ -118,6 +118,59 @@ 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 + + childCtxCh := make(chan context.Context, 1) + spawner := SubagentSpawnFunc(func(ctx context.Context, req SubagentSpawnRequest) (*SubagentSpawnResult, error) { + childCtxCh <- ctx + <-ctx.Done() // Block until cancelled + 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/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go index cdddd69ae..03bab1ab3 100644 --- a/pkg/kit/subagent_limits_test.go +++ b/pkg/kit/subagent_limits_test.go @@ -4,13 +4,49 @@ import ( "context" "strings" "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{}) + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { - return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + return &ProviderResult{Model: &blockingModel{echoModel: &echoModel{provider: "mock", model: name}, started: started, release: release}}, nil } maxSubs := 2 k := newProviderTestKit(t, &Options{ @@ -20,9 +56,8 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { }) ctx := context.Background() - // Since maxSubs is 2, running 3 concurrently should not fail but simply queue. - // We verify they all finish without the "limit reached" error. errCh := make(chan error, 3) + for i := range 3 { go func(id int) { _, err := k.Subagent(ctx, SubagentConfig{Prompt: "test", NoSession: true, Tools: []Tool{}}) @@ -30,9 +65,46 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { }(i) } + // 1. Verify that exactly maxSubs (2) subagents become active. + for i := 0; i < maxSubs; i++ { + 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 subagent is blocked in the queue. + select { + case <-started: + t.Fatalf("3rd subagent became active, but limit is 2") + case <-time.After(50 * time.Millisecond): + // correctly blocked + } + + // 3. Release one active subagent. + release <- struct{}{} + + // 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. + release <- struct{}{} + release <- struct{}{} + + // Ensure all finished without error. for range 3 { - if err := <-errCh; err != nil { - t.Fatalf("subagent spawn failed (queueing failed): %v", err) + select { + case err := <-errCh: + if err != nil { + t.Fatalf("subagent spawn failed (queueing failed): %v", err) + } + case <-time.After(1 * time.Second): + t.Fatalf("subagent did not return") } } } @@ -59,8 +131,11 @@ func TestSubagent_MaxSubagentsDisabled(t *testing.T) { } func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { + started := make(chan struct{}, 10) + release := make(chan struct{}) + factory := func(_ context.Context, _ *ProviderConfig, name string) (*ProviderResult, error) { - return &ProviderResult{Model: &echoModel{provider: "mock", model: name}}, nil + return &ProviderResult{Model: &blockingModel{echoModel: &echoModel{provider: "mock", model: name}, started: started, release: release}}, nil } maxNested := 2 k := newProviderTestKit(t, &Options{ @@ -71,8 +146,8 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { }) ctx := context.Background() - // Since maxNested is 2, running 3 concurrently should not fail but simply queue. errCh := make(chan error, 3) + for i := range 3 { go func(id int) { _, err := k.Subagent(ctx, SubagentConfig{Prompt: "nested", NoSession: true, Tools: []Tool{}}) @@ -80,9 +155,39 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { }(i) } + for i := 0; i < maxNested; i++ { + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("expected nested subagent %d to become active, but it blocked", i+1) + } + } + + select { + case <-started: + t.Fatalf("3rd nested subagent became active, but limit is 2") + case <-time.After(50 * time.Millisecond): + } + + release <- struct{}{} + + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("3rd nested subagent did not become active after a slot was released") + } + + release <- struct{}{} + release <- struct{}{} + for range 3 { - if err := <-errCh; err != nil { - t.Fatalf("nested subagent spawn failed (queueing failed): %v", err) + select { + case err := <-errCh: + 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") } } } @@ -130,8 +235,11 @@ func TestSubagent_Depth2CannotSpawn(t *testing.T) { } 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: &echoModel{provider: "mock", model: name}}, nil + return &ProviderResult{Model: &blockingModel{echoModel: &echoModel{provider: "mock", model: name}, started: started, release: release}}, nil } unlimited := -1 k := newProviderTestKit(t, &Options{ @@ -141,10 +249,36 @@ func TestSubagent_UnlimitedSubagents(t *testing.T) { }) ctx := context.Background() + errCh := make(chan error, 15) + for i := range 15 { - _, err := k.Subagent(ctx, SubagentConfig{Prompt: "unlimited", NoSession: true, Tools: []Tool{}}) - if err != nil { - t.Fatalf("subagent spawn %d failed: %v", i+1, err) + go func(id int) { + _, 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 := 0; i < 15; i++ { + select { + case <-started: + case <-time.After(1 * time.Second): + t.Fatalf("expected subagent %d to become active, but it blocked", i+1) + } + } + + for i := 0; i < 15; i++ { + release <- struct{}{} + } + + 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") } } } From 5bde69cdfb047c1aeb88bb6a04703df4745021f9 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 15:53:31 +0530 Subject: [PATCH 04/10] fix(subagent): snapshot caller context state at handler entry Capture callerActive at the beginning of executeSubagent so the decision to propagate cancellation cleanly reflects whether the caller context was alive upon entry, preserving detached behavior when already canceled on entry. --- internal/core/subagent.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/core/subagent.go b/internal/core/subagent.go index 8a7364b95..c70a1e24c 100644 --- a/internal/core/subagent.go +++ b/internal/core/subagent.go @@ -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,11 +242,14 @@ 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 alive on entry, propagate cancellation + // 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 ctx.Err() == nil { + // 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() }) From 10c120d018c6ac515a4bc1d8441dc6a5d4120197 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 16:01:40 +0530 Subject: [PATCH 05/10] style: modernize for loops in subagent limits tests Use range over int in TestSubagent_MaxSubagentsLimit, TestSubagent_MaxNestedSubagentsLimit, and TestSubagent_UnlimitedSubagents to satisfy golangci-lint modernize rules. --- pkg/kit/subagent_limits_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/kit/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go index 03bab1ab3..53da8d572 100644 --- a/pkg/kit/subagent_limits_test.go +++ b/pkg/kit/subagent_limits_test.go @@ -66,7 +66,7 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { } // 1. Verify that exactly maxSubs (2) subagents become active. - for i := 0; i < maxSubs; i++ { + for i := range maxSubs { select { case <-started: case <-time.After(1 * time.Second): @@ -155,7 +155,7 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { }(i) } - for i := 0; i < maxNested; i++ { + for i := range maxNested { select { case <-started: case <-time.After(1 * time.Second): @@ -259,7 +259,7 @@ func TestSubagent_UnlimitedSubagents(t *testing.T) { } // Verify all 15 become active immediately because limits are unbounded - for i := 0; i < 15; i++ { + for i := range 15 { select { case <-started: case <-time.After(1 * time.Second): @@ -267,7 +267,7 @@ func TestSubagent_UnlimitedSubagents(t *testing.T) { } } - for i := 0; i < 15; i++ { + for range 15 { release <- struct{}{} } From c86905f50323ed11f00525c172f0e67a85148c55 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 16:09:57 +0530 Subject: [PATCH 06/10] test(subagent): add cleanup stop channel to mock worker in cancellation test Ensure the mock worker in TestSpawnContext_PropagatesCancellationWhileRunning selects on both ctx.Done() and a cleanup stop channel, guaranteeing the background worker goroutine unblocks even if child cancellation were to fail. --- internal/core/subagent_test.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/internal/core/subagent_test.go b/internal/core/subagent_test.go index 18f1f709f..6e5cc393a 100644 --- a/internal/core/subagent_test.go +++ b/internal/core/subagent_test.go @@ -125,10 +125,16 @@ func TestSpawnContext_PropagatesCancellationWhileRunning(t *testing.T) { 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 - <-ctx.Done() // Block until cancelled + select { + case <-ctx.Done(): + case <-stop: + } return &SubagentSpawnResult{Response: "cancelled"}, ctx.Err() }) From f051bffb289fba57b1e7f087169a1d126e893ab0 Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 16:13:24 +0530 Subject: [PATCH 07/10] test(subagent): register cleanup handlers to prevent worker leaks on assertion failure Register t.Cleanup handlers before launching worker goroutines in concurrency limit tests to open release gates, cancel the worker context, and wait for sync.WaitGroup completion even if an assertion triggers t.Fatalf. --- pkg/kit/subagent_limits_test.go | 44 ++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/pkg/kit/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go index 53da8d572..2d4287434 100644 --- a/pkg/kit/subagent_limits_test.go +++ b/pkg/kit/subagent_limits_test.go @@ -3,6 +3,7 @@ package kit import ( "context" "strings" + "sync" "testing" "time" @@ -55,11 +56,21 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { MaxSubagents: &maxSubs, }) - ctx := context.Background() + 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) @@ -145,11 +156,21 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { MaxNestedSubagents: &maxNested, }) - ctx := context.Background() + 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) @@ -248,11 +269,24 @@ func TestSubagent_UnlimitedSubagents(t *testing.T) { MaxSubagents: &unlimited, }) - ctx := context.Background() + 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) @@ -267,9 +301,7 @@ func TestSubagent_UnlimitedSubagents(t *testing.T) { } } - for range 15 { - release <- struct{}{} - } + openRelease() for range 15 { select { From 3b546f8c6635f87ad146a2f4506c893878e2b5ce Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 20:01:59 +0530 Subject: [PATCH 08/10] test(subagent): use observable synchronization point for slot-wait assertions Add an internal onSubagentSlotWait hook fired when a subagent encounters a full concurrency semaphore. Update TestSubagent_MaxSubagentsLimit and TestSubagent_MaxNestedSubagentsLimit to synchronize on this wait point directly, eliminating fixed delay timeouts while guaranteeing the 3rd request is blocked at the limiter before releasing active workers. --- pkg/kit/kit.go | 17 +++++++++++++++-- pkg/kit/subagent_limits_test.go | 26 +++++++++++++++----------- 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/pkg/kit/kit.go b/pkg/kit/kit.go index 4ec13bea8..98a59ad54 100644 --- a/pkg/kit/kit.go +++ b/pkg/kit/kit.go @@ -170,6 +170,7 @@ type Kit struct { 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 @@ -262,13 +263,22 @@ func (m *Kit) acquireSubagentSlot(ctx context.Context) (func(), error) { m.subagentSem = make(chan struct{}, limit) } sem := m.subagentSem + onWait := m.onSubagentSlotWait m.subagentSemMu.Unlock() select { case sem <- struct{}{}: return func() { <-sem }, nil - case <-ctx.Done(): - return nil, ctx.Err() + default: + if onWait != nil { + onWait() + } + select { + case sem <- struct{}{}: + return func() { <-sem }, nil + case <-ctx.Done(): + return nil, ctx.Err() + } } } @@ -1361,6 +1371,7 @@ type Options struct { 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" @@ -1965,6 +1976,7 @@ func New(ctx context.Context, opts *Options) (*Kit, error) { 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) @@ -2695,6 +2707,7 @@ func (m *Kit) Subagent(ctx context.Context, cfg SubagentConfig) (*SubagentResult SubagentDepth: m.subagentDepth + 1, MaxSubagents: &maxSubs, MaxNestedSubagents: &maxNested, + onSubagentSlotWait: m.onSubagentSlotWait, } // Inherit the parent's effective provider/runtime configuration. Since #40 diff --git a/pkg/kit/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go index 2d4287434..22b4757d6 100644 --- a/pkg/kit/subagent_limits_test.go +++ b/pkg/kit/subagent_limits_test.go @@ -45,15 +45,17 @@ func (m *blockingModel) Stream(ctx context.Context, call LLMCall) (LLMStreamResp 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 k := newProviderTestKit(t, &Options{ - Model: "mock/test", - Providers: map[string]ProviderFactory{"mock": factory}, - MaxSubagents: &maxSubs, + Model: "mock/test", + Providers: map[string]ProviderFactory{"mock": factory}, + MaxSubagents: &maxSubs, + onSubagentSlotWait: func() { slotWaiting <- struct{}{} }, }) ctx, cancel := context.WithCancel(context.Background()) @@ -85,12 +87,11 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { } } - // 2. Verify the 3rd subagent is blocked in the queue. + // 2. Verify the 3rd request reaches the limiter's wait point while both model calls remain blocked. select { - case <-started: - t.Fatalf("3rd subagent became active, but limit is 2") - case <-time.After(50 * time.Millisecond): - // correctly blocked + case <-slotWaiting: + case <-time.After(1 * time.Second): + t.Fatal("timed out waiting for 3rd subagent to reach the limiter's wait point") } // 3. Release one active subagent. @@ -144,6 +145,7 @@ func TestSubagent_MaxSubagentsDisabled(t *testing.T) { 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 @@ -154,6 +156,7 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { Providers: map[string]ProviderFactory{"mock": factory}, SubagentDepth: 1, MaxNestedSubagents: &maxNested, + onSubagentSlotWait: func() { slotWaiting <- struct{}{} }, }) ctx, cancel := context.WithCancel(context.Background()) @@ -184,10 +187,11 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { } } + // Verify the 3rd request reaches the limiter's wait point while both model calls remain blocked. select { - case <-started: - t.Fatalf("3rd nested subagent became active, but limit is 2") - case <-time.After(50 * time.Millisecond): + case <-slotWaiting: + case <-time.After(1 * time.Second): + t.Fatal("timed out waiting for 3rd nested subagent to reach the limiter's wait point") } release <- struct{}{} From b7e15d45f7b487ab36f1bafb609938ba05eab09c Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 20:07:45 +0530 Subject: [PATCH 09/10] test(subagent): bound release channel sends and check early worker errors Introduce sendRelease in TestSubagent_MaxSubagentsLimit and TestSubagent_MaxNestedSubagentsLimit to bound all release sends with a deadline and select on early worker errors from errCh, preventing test hangs if a worker terminates unexpectedly. --- pkg/kit/subagent_limits_test.go | 54 ++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/pkg/kit/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go index 22b4757d6..5446a9d95 100644 --- a/pkg/kit/subagent_limits_test.go +++ b/pkg/kit/subagent_limits_test.go @@ -94,8 +94,26 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { 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. - release <- struct{}{} + sendRelease() // 4. Verify the 3rd subagent now unblocks and becomes active. select { @@ -105,13 +123,14 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { } // Release the remaining two. - release <- struct{}{} - release <- struct{}{} + sendRelease() + sendRelease() // Ensure all finished without error. - for range 3 { + for finished < 3 { select { case err := <-errCh: + finished++ if err != nil { t.Fatalf("subagent spawn failed (queueing failed): %v", err) } @@ -194,7 +213,25 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { t.Fatal("timed out waiting for 3rd nested subagent to reach the limiter's wait point") } - release <- struct{}{} + 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: @@ -202,12 +239,13 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { t.Fatalf("3rd nested subagent did not become active after a slot was released") } - release <- struct{}{} - release <- struct{}{} + sendRelease() + sendRelease() - for range 3 { + for finished < 3 { select { case err := <-errCh: + finished++ if err != nil { t.Fatalf("nested subagent spawn failed (queueing failed): %v", err) } From 1243905e7e55fd497e359dff281a6c69c4faefda Mon Sep 17 00:00:00 2001 From: Sai Karthik Date: Wed, 18 Nov 2026 20:23:14 +0530 Subject: [PATCH 10/10] test(subagent): explicitly set both root and nested limits in queuing fixtures Set the limit under test to 2 and the other limit to 3 in TestSubagent_MaxSubagentsLimit and TestSubagent_MaxNestedSubagentsLimit to verify intended limit selection in acquireSubagentSlot without relying on defaults or environment variables. --- pkg/kit/subagent_limits_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pkg/kit/subagent_limits_test.go b/pkg/kit/subagent_limits_test.go index 5446a9d95..803446d22 100644 --- a/pkg/kit/subagent_limits_test.go +++ b/pkg/kit/subagent_limits_test.go @@ -51,10 +51,12 @@ func TestSubagent_MaxSubagentsLimit(t *testing.T) { 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{}{} }, }) @@ -169,11 +171,13 @@ func TestSubagent_MaxNestedSubagentsLimit(t *testing.T) { 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{}{} }, })