core

package
v0.135.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package core provides the built-in core tools for KIT's coding agent. These tools are direct fantasy.AgentTool implementations — no MCP layer, no JSON-RPC, no serialization overhead. Core tool set: shell, read, write, edit, grep, find, ls.

Index

Constants

View Source
const (
	ShellToolName       = "shell"
	LegacyShellToolName = "bash"
)

The command-execution tool is a shell tool, and ShellToolName is its name: in the registry, in the tool definition sent to the model, and in a session transcript. It does not vary with the configured shell.

LegacyShellToolName is the name the tool had before the shell became configurable. It appears in existing user configuration and in existing sessions, so it is accepted wherever a user names the tool; see NormalizeCoreToolName.

View Source
const (

	// DefaultMaxLines is the exported default line limit for truncation.
	DefaultMaxLines = defaultMaxLines
	// DefaultMaxBytes is the exported default byte limit for truncation.
	DefaultMaxBytes = defaultMaxBytes
)
View Source
const BangShellTimeout = 120 * time.Second

BangShellTimeout is the ceiling for a bang command when the caller sets no timeout of its own. It matches the shell tool's default so that `!go build` and the same command from the model behave the same way.

View Source
const CodeModeToolName = "codemode"

CodeModeToolName is the name of the code mode core tool.

Variables

View Source
var ErrShellCommandTimedOut = errors.New("command timed out")

ErrShellCommandTimedOut reports a command that exceeded its timeout. It is a distinct error because the bang path shows it as a status line rather than as output: the command produced nothing useful, and saying so is more useful than showing the empty buffer.

Functions

func AllTools

func AllTools(opts ...ToolOption) []fantasy.AgentTool

AllTools returns all available core tools.

func CodingTools

func CodingTools(opts ...ToolOption) []fantasy.AgentTool

CodingTools returns the default set of core tools for a coding agent: shell, read, write, edit.

func ContextWithPasswordPrompt added in v0.53.0

func ContextWithPasswordPrompt(ctx context.Context, callback PasswordPromptCallback) context.Context

ContextWithPasswordPrompt returns a new context with the password prompt callback set. This allows the TUI to show a modal password prompt when sudo needs a password.

func ContextWithToolOutputCallback added in v0.20.0

func ContextWithToolOutputCallback(ctx context.Context, callback ToolOutputCallback) context.Context

ContextWithToolOutputCallback returns a new context with the tool output callback set.

func DefaultCoreToolNames added in v0.117.0

func DefaultCoreToolNames() []string

DefaultCoreToolNames returns the core tools enabled when none are named.

func ListAllCoreToolNames added in v0.81.0

func ListAllCoreToolNames() []string

ListAllCoreToolNames returns all available core tool names.

func ListedTools added in v0.81.0

func ListedTools(toolList []string, opts ...ToolOption) []fantasy.AgentTool

ListedTools builds the named core tools. Names are normalized first, so a list carrying the shell tool's earlier name still selects it, and a name that matches no core tool is skipped rather than dereferenced.

func NewCodeModeTool added in v0.117.0

func NewCodeModeTool(opts ...ToolOption) fantasy.AgentTool

NewCodeModeTool creates the code mode core tool.

func NewEditTool

func NewEditTool(opts ...ToolOption) fantasy.AgentTool

NewEditTool creates the edit core tool.

func NewFindTool

func NewFindTool(opts ...ToolOption) fantasy.AgentTool

NewFindTool creates the find core tool.

func NewGrepTool

func NewGrepTool(opts ...ToolOption) fantasy.AgentTool

NewGrepTool creates the grep core tool.

func NewLsTool

func NewLsTool(opts ...ToolOption) fantasy.AgentTool

NewLsTool creates the ls core tool.

func NewReadTool

func NewReadTool(opts ...ToolOption) fantasy.AgentTool

NewReadTool creates the read core tool.

func NewShellTool added in v0.103.0

func NewShellTool(opts ...ToolOption) fantasy.AgentTool

NewShellTool creates the shell core tool. It runs one command string through the configured shell, which defaults to bash.

func NewSubagentTool added in v0.9.0

func NewSubagentTool(opts ...ToolOption) fantasy.AgentTool

NewSubagentTool creates the subagent core tool. When named agents are configured via WithNamedAgents, they are advertised in the tool description so the LLM can delegate to the right specialist.

func NewWriteTool

func NewWriteTool(opts ...ToolOption) fantasy.AgentTool

NewWriteTool creates the write core tool.

func NormalizeCoreToolName added in v0.103.0

func NormalizeCoreToolName(name string) string

NormalizeCoreToolName maps a user-supplied core tool name onto its registry key, so that the earlier name for the shell tool keeps selecting it. An unrecognised name in include-core-tools or exclude-core-tools produces a warning and no effect, which is what this avoids.

func ReadOnlyTools

func ReadOnlyTools(opts ...ToolOption) []fantasy.AgentTool

ReadOnlyTools returns tools for read-only exploration: read, grep, find, ls.

func SubagentTools added in v0.12.0

func SubagentTools(opts ...ToolOption) []fantasy.AgentTool

SubagentTools returns all core tools except subagent. This prevents infinite recursion when a subagent is itself a Kit instance.

func WithSubagentSpawner added in v0.12.0

func WithSubagentSpawner(ctx context.Context, fn SubagentSpawnFunc) context.Context

WithSubagentSpawner stores a spawn function in the context so that the subagent core tool can create in-process subagents.

Types

type CodeModeConfig added in v0.117.0

type CodeModeConfig struct {
	// Limits bounds each script run. Zero fields use the defaults.
	Limits codemode.Limits
	// Policy decides which tools the model sees directly and which only
	// scripts can call.
	Policy codemode.Policy
	// CatalogBudget caps the bytes of the tool catalog in the tool
	// description. Zero uses 12000.
	CatalogBudget int
}

CodeModeConfig configures the code mode tool.

type CodeModeRunInfo added in v0.117.0

type CodeModeRunInfo struct {
	OK        bool            `json:"ok"`
	ErrorKind string          `json:"error_kind,omitempty"`
	WallTime  time.Duration   `json:"wall_time_ns"`
	Calls     []codemode.Call `json:"calls,omitempty"`
	FullPath  string          `json:"full_output_path,omitempty"`
}

CodeModeRunInfo is the structured metadata attached to each code mode result.

type CodeModeTool added in v0.117.0

type CodeModeTool struct {
	// contains filtered or unexported fields
}

CodeModeTool runs model-written JavaScript that calls other tools. See package codemode.

func (*CodeModeTool) Info added in v0.117.0

func (t *CodeModeTool) Info() fantasy.ToolInfo

Info implements fantasy.AgentTool. The description carries the live catalog, refreshed by ObserveToolSet.

func (*CodeModeTool) ModelVisible added in v0.117.0

func (t *CodeModeTool) ModelVisible(name string) bool

ModelVisible implements ToolSetObserver.

func (*CodeModeTool) ObserveToolSet added in v0.117.0

func (t *CodeModeTool) ObserveToolSet(all []fantasy.AgentTool)

ObserveToolSet implements ToolSetObserver. It rebuilds the catalog and the description when the tool set changed.

func (*CodeModeTool) ProviderOptions added in v0.117.0

func (t *CodeModeTool) ProviderOptions() fantasy.ProviderOptions

ProviderOptions implements fantasy.AgentTool.

func (*CodeModeTool) Run added in v0.117.0

Run implements fantasy.AgentTool.

func (*CodeModeTool) SetProviderOptions added in v0.117.0

func (t *CodeModeTool) SetProviderOptions(o fantasy.ProviderOptions)

SetProviderOptions implements fantasy.AgentTool.

func (*CodeModeTool) Store added in v0.117.0

func (t *CodeModeTool) Store() *codemode.Store

Store returns the store that keeps store()/load() values across runs.

type CommandRequest added in v0.116.0

type CommandRequest struct {
	// ToolCallID is the ID of the shell tool call that runs the command.
	ToolCallID string
	// Command is the command string the model wrote.
	Command string
	// Argv is the full argument vector to run: the resolved shell, its
	// arguments, and Command, e.g. ["bash", "-c", "go test ./..."].
	Argv []string
	// WorkDir is the directory to run in. Empty means the process working
	// directory.
	WorkDir string
	// Timeout is how long the command may run.
	Timeout time.Duration
}

CommandRequest describes one command the shell tool wants to run.

type CommandResult added in v0.116.0

type CommandResult struct {
	// Output is the combined stdout and stderr.
	Output string
	// ExitCode is the exit status. It is ignored when Signal is set.
	ExitCode int
	// Signal is the name of the signal that ended the command, if any.
	Signal string
	// TimedOut reports that the command was stopped at Timeout.
	TimedOut bool
}

CommandResult is the outcome of a command run by a CommandRunner.

type CommandRunner added in v0.116.0

type CommandRunner interface {
	RunCommand(ctx context.Context, req CommandRequest) (CommandResult, error)
}

CommandRunner runs the shell tool's commands somewhere other than a local child process, for example in an editor's terminal. A runner receives the command after the tool's own checks (banned builtins, timeout limits). Interactive sudo password prompts are not available through a runner.

type Edit added in v0.26.0

type Edit struct {
	OldText string `json:"old_text"`
	NewText string `json:"new_text"`
}

Edit represents a single replacement in a multi-edit operation.

type FileSystem added in v0.116.0

type FileSystem interface {
	// ReadTextFile returns the full content of the text file at the absolute
	// path. It returns an error that satisfies errors.Is(err, os.ErrNotExist)
	// when the file does not exist, if it can tell.
	ReadTextFile(ctx context.Context, path string) (string, error)
	// WriteTextFile replaces the content of the file at the absolute path,
	// creating the file when it does not exist.
	WriteTextFile(ctx context.Context, path, content string) error
}

FileSystem reads and writes text files for the read, write and edit tools. The default reads and writes the local disk. An embedder can route file access elsewhere, for example to an editor that has unsaved changes.

Only text content goes through a FileSystem. The read tool still reads images from the local disk, and the tools still check paths (existence, directories) on the local disk.

type NamedAgentSpec added in v0.85.0

type NamedAgentSpec struct {
	// Name is the value the LLM passes in the "agent" parameter.
	Name string
	// Description summarises what the agent does.
	Description string
	// Tools lists the tool names the agent may use. Empty means the full
	// default subagent tool set.
	Tools []string
}

NamedAgentSpec summarises a named agent definition for advertisement in the subagent tool description. It is intentionally minimal so the core package does not depend on the agent discovery machinery.

type PasswordPromptCallback added in v0.53.0

type PasswordPromptCallback func(prompt string) (password string, cancelled bool)

PasswordPromptCallback is the signature for password prompts. It receives a prompt message and returns the password and whether it was cancelled.

type ShellChunkSink added in v0.118.0

type ShellChunkSink func(chunk string, isStderr bool)

ShellChunkSink receives output as it arrives. isStderr says which stream the bytes came from.

The call happens on a reader goroutine, one of two running concurrently, so an implementation must be safe for concurrent use. It must also not block: a sink that waits for the UI while the UI waits for the command deadlocks both. The caller here drops a chunk when its channel is full, which is the correct trade — the full text is still collected for the final result.

type ShellRunOptions added in v0.118.0

type ShellRunOptions struct {
	// Command is the command string to run through the configured shell.
	Command string

	// Shell is the configured shell vector. Empty means the default shell.
	Shell []string

	// WorkDir is the working directory. Empty means the process working
	// directory.
	WorkDir string

	// Timeout bounds the whole run. Zero means BangShellTimeout. The command
	// and its process group are killed when it expires.
	Timeout time.Duration

	// OnChunk receives output as it arrives. Nil collects the output without
	// streaming it, which is what a caller with nothing live to draw wants.
	OnChunk ShellChunkSink
}

ShellRunOptions configures one bang-mode shell command.

type ShellRunResult added in v0.118.0

type ShellRunResult struct {
	// Command is the command that was run.
	Command string

	// Output is stdout followed by stderr, in that order, with a newline
	// between them when both are present. It holds the escape sequences the
	// program emitted, unmodified: the display layer and the model layer each
	// need a different treatment and neither can be undone from the other.
	Output string

	// ExitCode is the process exit status, or -1 when the command never
	// produced one.
	ExitCode int

	// TimedOut reports that the timeout fired. Output collected before the
	// kill is still present.
	TimedOut bool
}

ShellRunResult is the outcome of one bang-mode shell command.

func RunShellCommand added in v0.118.0

func RunShellCommand(ctx context.Context, opts ShellRunOptions) (ShellRunResult, error)

RunShellCommand runs one command through the configured shell, streams its output to opts.OnChunk as it arrives, and returns the complete output.

It applies the same shell resolution, environment and exit handling as the shell tool, so a bang command and the model's own call to the same command differ only in who is watching.

type SubagentSpawnFunc added in v0.12.0

type SubagentSpawnFunc func(ctx context.Context, req SubagentSpawnRequest) (*SubagentSpawnResult, error)

SubagentSpawnFunc is a callback that spawns an in-process subagent. The parent Kit instance injects this into the context so the core tool can call back without importing pkg/kit (which would create a cycle).

type SubagentSpawnRequest added in v0.85.0

type SubagentSpawnRequest struct {
	// ToolCallID is the LLM-assigned ID of the subagent tool call,
	// enabling the parent to correlate subagent events.
	ToolCallID string
	// Prompt is the task for the subagent (required).
	Prompt string
	// Agent optionally names a discovered agent definition whose presets
	// (model, system prompt, tools, timeout) apply as defaults.
	Agent string
	// Model optionally overrides the model.
	Model string
	// SystemPrompt optionally overrides the system prompt.
	SystemPrompt string
	// Timeout bounds execution. Zero means "unset": the spawner applies
	// the named agent's timeout (if any) or the default.
	Timeout time.Duration
	// SessionID optionally resumes an existing subagent session (the
	// subagent_session_id returned by a previous run) instead of starting
	// fresh, so follow-up tasks reuse the subagent's accumulated context.
	SessionID string
}

SubagentSpawnRequest carries the parameters of an in-process subagent spawn from the subagent core tool to the parent Kit instance.

type SubagentSpawnResult added in v0.12.0

type SubagentSpawnResult struct {
	Response     string
	Error        error
	SessionID    string
	InputTokens  int64
	OutputTokens int64
	Elapsed      time.Duration
	// Killed is true when the user stopped the run (for example with
	// /kill-subagent) before it completed.
	Killed bool
}

SubagentSpawnResult carries the outcome of an in-process subagent spawn.

type ToolConfig

type ToolConfig struct {
	WorkDir string
	// NamedAgents lists discovered named agent definitions advertised in
	// the subagent tool description. Only the subagent tool consumes this.
	NamedAgents []NamedAgentSpec
	// ShellTimeout overrides the default per-call timeout for the shell tool.
	// Zero uses the built-in default (120s). Only the shell tool consumes this.
	ShellTimeout time.Duration
	// ShellMaxTimeout overrides the ceiling a shell tool call may request via
	// its timeout argument. Zero uses the built-in default (600s). Only the
	// shell tool consumes this.
	ShellMaxTimeout time.Duration
	// Shell is the shell the shell tool runs a command string through, plus
	// its own leading arguments, e.g. ["bash"] or ["busybox", "ash"]. Nil or
	// empty uses the built-in default ["bash"]. This exists so KIT can run
	// on images that do not ship bash (Alpine, distroless and similar). Only
	// the shell tool consumes this.
	Shell []string
	// ImageLimits bounds the pixel size and encoded byte size of an image
	// the read tool attaches to a message. The zero value applies the
	// built-in defaults. Only the read tool consumes this.
	ImageLimits media.Limits
	// FileSystem handles the text file access of the read, write and edit
	// tools. Nil uses the local disk. See WithFileSystem.
	FileSystem FileSystem
	// CommandRunner runs the shell tool's commands. Nil runs them as local
	// child processes. See WithCommandRunner.
	CommandRunner CommandRunner
	// CodeMode configures the code mode tool. Nil uses the defaults. Only
	// the code mode tool consumes this.
	CodeMode *CodeModeConfig
}

ToolConfig holds configuration for tool construction.

func ApplyOptions

func ApplyOptions(opts []ToolOption) ToolConfig

ApplyOptions applies the given ToolOptions to a ToolConfig and returns it.

type ToolOption

type ToolOption func(*ToolConfig)

ToolOption configures tool behavior.

func WithCodeMode added in v0.117.0

func WithCodeMode(cfg CodeModeConfig) ToolOption

WithCodeMode configures the code mode tool. Other tools ignore it.

func WithCommandRunner added in v0.116.0

func WithCommandRunner(r CommandRunner) ToolOption

WithCommandRunner makes the shell tool run commands through r. A nil r keeps local child processes.

func WithFileSystem added in v0.116.0

func WithFileSystem(fs FileSystem) ToolOption

WithFileSystem routes the text file access of the read, write and edit tools through fs. A nil fs keeps the local disk.

func WithImageLimits added in v0.114.0

func WithImageLimits(limits media.Limits) ToolOption

WithImageLimits bounds the images the read tool attaches to a message. A zero field inside limits keeps the built-in default for that field.

func WithNamedAgents added in v0.85.0

func WithNamedAgents(agents ...NamedAgentSpec) ToolOption

WithNamedAgents advertises named agent definitions in the subagent tool description so the LLM can delegate tasks to them by name.

func WithShell added in v0.103.0

func WithShell(argv []string) ToolOption

WithShell sets the shell the shell tool runs command strings through: the shell plus its own leading arguments, e.g. ["bash"] or ["busybox", "ash"]. A nil or empty vector leaves the built-in default ["bash"] in place, so an installation that sets nothing executes exactly what it did before.

func WithShellMaxTimeout added in v0.103.0

func WithShellMaxTimeout(d time.Duration) ToolOption

WithShellMaxTimeout sets the maximum timeout a shell tool call may request. A non-positive duration leaves the built-in default (600s) in place.

func WithShellTimeout added in v0.103.0

func WithShellTimeout(d time.Duration) ToolOption

WithShellTimeout sets the default per-call timeout for the shell tool. A non-positive duration leaves the built-in default (120s) in place.

func WithWorkDir

func WithWorkDir(dir string) ToolOption

WithWorkDir sets the working directory for file-based tools. If empty, os.Getwd() is used at execution time.

type ToolOutputCallback added in v0.20.0

type ToolOutputCallback func(toolCallID, toolName, chunk string, isStderr bool)

ToolOutputCallback is the signature for streaming tool output. It receives tool call ID, tool name, output chunk, and whether it's stderr.

type ToolSetObserver added in v0.117.0

type ToolSetObserver interface {
	ObserveToolSet(tools []fantasy.AgentTool)
	ModelVisible(name string) bool
}

ToolSetObserver is implemented by tools that need the agent's live tool set. The agent calls ObserveToolSet with the full composed tool set (wrapped, so nested calls pass through extension and SDK hooks) before each step, and drops every tool for which ModelVisible returns false from the tools it sends to the model.

type TruncationResult

type TruncationResult struct {
	Content   string
	Truncated bool
	TruncBy   string // "lines", "bytes", or ""
	Total     int    // total lines before truncation
	Kept      int    // lines kept after truncation
}

TruncationResult describes how output was truncated.

func TruncateTail added in v0.5.1

func TruncateTail(content string, maxLines, maxBytes int) TruncationResult

TruncateTail keeps the last maxLines lines and at most maxBytes bytes. Individual lines longer than defaultMaxLineLen are truncated to prevent extremely long single lines from blowing up the TUI when wrapped. Used for bash output where the tail is most relevant.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL