# Ready-Made Tools

The root `tools` package and its subpackages (`tools/fs`, `tools/exec`, `tools/subagent`, `tools/web`, `tools/task`) ship ready-made, standard-library-only `tool.Tool` implementations for local workspaces, managed subagent lifecycles, web retrieval, and planning. Filesystem and command tools support symlink-resolved root containment, command tools can promote long-running processes to the background, and subagent tools manage multi-turn delegation with optional git-worktree isolation.

## Wire up the standard tool sets

Construct tool sets with explicit root directories and close managed command runners when finished:

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ijaidev/gojent/tools"
	"github.com/ijaidev/gojent/tools/exec"
	"github.com/ijaidev/gojent/tools/fs"
	"github.com/ijaidev/gojent/tools/web"
)

func main() {
	fsTools, err := tools.StandardFilesystemTools(fs.Config{BaseDir: "/workspace"})
	if err != nil {
		log.Fatal(err)
	}
	webTools, err := tools.StandardWebTools(web.FetchConfig{})
	if err != nil {
		log.Fatal(err)
	}
	managedExec, err := tools.NewExecTools(exec.ManagerConfig{BaseDir: "/workspace"})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = managedExec.Close(context.Background()) }()

	execTools := managedExec.All()
	tracker, taskTools, err := tools.StandardTaskTools()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(fsTools), len(webTools), len(execTools), len(taskTools), tracker != nil)
}
```

## Filesystem sandboxing and search (`tools/fs`)

`tools.StandardFilesystemTools` returns four core tools: `read_file`, `write_file`, `edit_file`, and `list_files`. For bounded, standard-library-only file-name and content search, also register `fs.NewGlobFilesTool` and `fs.NewGrepFilesTool`:

- **Root containment:** When `BaseDir` or `AdditionalDirs` is configured, relative paths resolve against `BaseDir`, and every read, write, edit, list, glob, and grep access is verified **after symlink resolution** against all configured roots so a symlinked entry cannot escape the sandbox.
- **Annotations:** Inspection tools (`read_file`, `list_files`, `glob_files`, `grep_files`) are annotated `ReadOnly: true, Idempotent: true`, whereas `write_file` and `edit_file` are annotated `Destructive: true`.

## Managed command execution (`tools/exec`)

`tools.NewExecTools(exec.ManagerConfig{...})` creates a process `Manager` and exposes five tools (`execute_command`, `process_status`, `read_process_output`, `wait_process`, and `kill_process`):

- **Foreground-to-background promotion:** `execute_command` waits up to the foreground timeout (default 30 seconds), then promotes a still-running command to the background instead of killing it. Pass `background: true` in the tool call to start in the background immediately.
- **Opaque process handles:** Background processes are referenced by opaque handles rather than raw OS PIDs. Always call `managedExec.Close(ctx)` to terminate remaining processes on shutdown.
- **Working directory containment and host permissions:** `ManagerConfig.BaseDir` and `ManagerConfig.AdditionalDirs` constrain working directories after symlink resolution (even when `BaseDir` is empty). However, commands execute with the host user's OS permissions—always gate command tools with an [agent.Policy and Approver](/docs/core/policies) before exposing them to a model.
- **Live observer without polling:** Set `ManagerConfig.Observer` (`exec.ProcessObserver`) to receive synchronous `start`, copied stdout/stderr `output`, and `exit` `ProcessEvent` values. Observer panics are recovered so they never disrupt buffered reads or manager shutdown.
- **Foreground-only alternative:** `tools.StandardExecTools(exec.Config{...})` remains available when you only want a single synchronous `execute_command` tool without background process management.

## Managed subagent lifecycle (`tools/subagent`)

`tools.NewSubagentTools(subagent.ManagerConfig{...})` builds a `*subagent.Manager` from registered `subagent.Profile` definitions and exposes six lifecycle tools (`subagent_spawn`, `subagent_send`, `subagent_wait`, `subagent_status`, `subagent_cancel`, and `subagent_cleanup`), plus `subagent_define` when `ManagerConfig.Dynamic != nil`:

- **Sync, background, and timeout promotion:** `subagent_spawn` and `subagent_send` can wait for turn completion, start immediately in the background (`background: true`), or wait up to `wait_seconds` (or `ManagerConfig.DefaultForegroundWait`) before promoting the active subagent to background (`Snapshot.Promoted`).
- **Multi-turn resume and bounded waits:** `subagent_send` preserves child conversation history in `ManagerConfig.Store` (defaulting to `session.NewMemory()`), queuing follow-up prompts if the child is running or starting a new turn if idle. `subagent_wait` waits for `"all"` (default) or `"any"` subagent IDs up to `timeout_seconds` (capped by `ManagerConfig.MaxWait`, default 5 minutes) and returns `WaitResult` cleanly on timeout (`TimedOut: true`).
- **Cascading cancellation and cleanup:** `subagent_cancel` cancels a subagent and recursively cancels all descendants; always call `subTools.Close(ctx)` on shutdown to stop active workers.
- **Git worktree isolation:** Attach `subagent.NewGitWorktreeProvider(subagent.GitWorktreeConfig{RepoDir: ...})` as `ManagerConfig.Workspace` to run `subagent.WorkspaceWorktree` profiles in isolated git worktrees and temporary branches, report dirty/ahead status via `Inspect`, and remove retained worktrees with `subagent_cleanup`.
- **Opt-in capability-attenuated `DynamicConfig`:** Setting `ManagerConfig.Dynamic` enables `subagent_define` (`Manager.Define`) while failing closed (`subagent.ErrCapabilityDenied`) whenever a requested tool, `AllowWorktree`, `AllowNested`, or `MaxBudget` exceeds the configured ceiling (`MaxProfiles` defaults to 16).

```go
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()

	subTools, err := tools.NewSubagentTools(subagent.ManagerConfig{
		DefaultModel: mockllm.New("Subagent findings confirmed."),
		Profiles: []subagent.Profile{
			{
				Name:         "explorer",
				Description:  "Read-only researcher",
				Instructions: "Inspect and summarize concisely.",
				Workspace:    subagent.WorkspaceInherit,
			},
		},
		Dynamic: &subagent.DynamicConfig{
			MaxProfiles: 4,
			MaxBudget:   agent.Budget{MaxSteps: 4},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = subTools.Close(ctx) }()

	turn := 0
	leadModel := mockllm.New().ApplyOptions(
		mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) {
			turn++
			if turn == 1 {
				return llm.NewSliceStream(ctx, []llm.StreamEvent{
					llm.MessageStart{Model: "mock-llm"},
					llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{
						CallID: "s1",
						Name:   "subagent_spawn",
						Input:  []byte(`{"profile":"explorer","prompt":"Check status."}`),
					})},
					llm.PartEnd{Index: 0},
					llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool},
				}), nil
			}
			return llm.NewSliceStream(ctx, []llm.StreamEvent{
				llm.MessageStart{Model: "mock-llm"},
				llm.PartStart{Index: 0, Part: llm.NewTextPart("")},
				llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Delegation complete."},
				llm.PartEnd{Index: 0},
				llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop},
			}), nil
		}),
	)

	lead, err := agent.New(agent.Config{
		Name:  "lead",
		Model: leadModel,
		Tools: subTools.All(),
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := lead.Generate(ctx, "Delegate a quick check.")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Text, "tools:", len(subTools.All()))
}
```

## Web and task tools (`tools/web`, `tools/task`)

- **`tools.StandardWebTools` / `web.NewWebSearchTool`:** Provides `web_fetch` (bounded HTTP fetch with optional HTML-to-text extraction) and `web_search` backed by your `web.SearchProvider` implementation.
- **`tools.StandardTaskTools`:** Returns an in-memory, thread-safe `*task.Tracker` and `task_create`, `task_list`, and `task_update` tools for multi-step agent planning.

Browse the full `tools` API on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/tools).
