Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 14 additions & 6 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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().
Expand Down Expand Up @@ -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"))

Expand Down
9 changes: 9 additions & 0 deletions cmd/run_mode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
18 changes: 10 additions & 8 deletions cmd/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down
22 changes: 13 additions & 9 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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

Expand Down
17 changes: 16 additions & 1 deletion internal/core/subagent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
59 changes: 59 additions & 0 deletions internal/core/subagent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions pkg/kit/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading