tools

package
v0.107.39 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const MaxAskQuestions = 4

MaxAskQuestions bounds the questions of one request, as /v1 clients do.

View Source
const SSHManagerTool = "SSHManager"

SSHManagerTool is the name of the native SSH tool.

View Source
const WebSearchToolName = "web_search"

WebSearchToolName is the function tool that searches the web through the configured third-party service when the model's API has no native search.

Variables

View Source
var Ask func(ctx context.Context, req AskRequest) (answers []AskAnswer, ok bool)
View Source
var Browser *browser.Manager
View Source
var ComputerApprover func(app string) bool
View Source
var ComputerPolicy *computer.Policy
View Source
var ErrNotBackgroundable = errors.New("tool call is not running a command that can be moved to the background")

ErrNotBackgroundable reports that a tool call is not running a command that can be moved to the background: it is unknown, already finished, interactive, or was already moved.

View Source
var ErrTurnEnded = errors.New("turn ended")

ErrTurnEnded is the cancellation cause a host gives a turn's context once the turn has finished on its own. Work the turn hands off to run in the background (a wait poller, a managed process) outlives that cancellation; any other one, such as the user stopping the turn, still ends it.

View Source
var LSP interface {
	WaitDiagnostics(ctx context.Context, path string) string
}

LSP is the process-wide language-server manager. File tools do not call it: the agent's post-tool reminders report diagnostics for the paths a call mutated.

View Source
var PlanReview func(ctx context.Context, plan string) (verdict PlanVerdict, ok bool)

PlanReview shows a submitted plan to the interactive user and waits for their verdict; ok is false when they closed the review without deciding. It is nil where nobody can review a plan in-process (the backend, ACP), and the agent then does not offer its ExitPlanMode tool.

View Source
var Suggester func(name string) []string
View Source
var Version = "dev"

Version names the build in web_fetch's User-Agent; the CLI sets it at startup.

Functions

func AskAnswerText added in v0.107.21

func AskAnswerText(req AskRequest, answers []AskAnswer) string

AskAnswerText is the question tool's result for answers to req, one per question in order (one for the single-question form).

func AsksInPlanMode added in v0.107.13

func AsksInPlanMode(tool string) bool

AsksInPlanMode reports gated tools that Plan mode keeps: they change nothing locally but reach the network, so the user is asked instead of the call being refused. The other gated tools are refused in Plan mode.

func AttachImage added in v0.107.3

func AttachImage(ctx context.Context, ext string, data []byte) bool

AttachImage attaches an image of the given extension (png, jpg, gif, webp) to the current tool result when the model supports vision.

func AttachScreenshot added in v0.103.0

func AttachScreenshot(ctx context.Context, jpeg []byte) bool

func Authorize added in v0.103.0

func Authorize(ctx context.Context, tool, command string) error

func AuthorizePoll added in v0.107.6

func AuthorizePoll(ctx context.Context, tool, id string) error

AuthorizePoll gates a call that only reads the output of a process or terminal this session started; id names it. The caller still checks that the session owns it.

func BeforeFileMutation added in v0.107.0

func BeforeFileMutation(ctx context.Context, path string)

func BinaryPlaceholder

func BinaryPlaceholder(name string, size int) string

func CommandRule

func CommandRule(command string) string

func Defs

func Defs(ts []Tool) []ai.Tool

func Execute

func Execute(ctx context.Context, ts []Tool, name string, args json.RawMessage) string

func IsBinary

func IsBinary(data []byte) bool

func IsStale

func IsStale(err error) bool

func LSPToolAvailable added in v0.107.13

func LSPToolAvailable() bool

LSPToolAvailable reports whether the installed LSP manager can answer lsp tool queries.

func OutliveTurn added in v0.107.18

func OutliveTurn(ctx context.Context) (context.Context, context.CancelFunc)

OutliveTurn returns a context with ctx's values that is cancelled together with ctx unless ctx ends with ErrTurnEnded. The returned cancel releases it.

func ReportElicitation added in v0.107.26

func ReportElicitation(ctx context.Context, e ai.Elicitation)

ReportElicitation records a form an MCP server asked the user to fill during the current tool call, for the call's history.

func ReportQuestionAnswers added in v0.107.23

func ReportQuestionAnswers(ctx context.Context, answers []ai.QuestionAnswer)

ReportQuestionAnswers records the user's answers to the question the current tool call asked, for the call's history. The first report wins, so an AskFunc that knows the answers' exact form can record them before the question tool derives its own.

func ReportUserWait added in v0.107.26

func ReportUserWait(ctx context.Context, d time.Duration)

ReportUserWait leaves d, time the current tool call spent waiting for the user (an MCP elicitation form), out of the call's duration.

func ResolvePath added in v0.103.0

func ResolvePath(ctx context.Context, path string) string

func ResolveWorkspacePath added in v0.107.28

func ResolveWorkspacePath(ctx context.Context, raw, access, label string, allowDirectory bool) (string, error)

ResolveWorkspacePath resolves a local path argument the way the LiveAgent file tools do (workspace-relative, absolute, ~/..., file://, root://) and requires it inside the run's workspace roots; access is "read" or "write". label names the argument in errors, for example "SSHManager.local_path".

func SSHManagerGateCommand added in v0.107.28

func SSHManagerGateCommand(args json.RawMessage) (command string, readOnly bool)

SSHManagerGateCommand is the command an SSHManager call is gated with: "<action> <host_id or session_id> <detail>", where detail is the remote command, input or paths the action works on. Permission rules match it as text, for example SSHManager(exec web-1:*). readOnly is true for the actions SSHManagerReadOnly lists.

func SSHManagerReadOnly added in v0.107.28

func SSHManagerReadOnly(action string) bool

SSHManagerReadOnly reports the SSHManager actions that only read K-brain's own state (configured hosts, open sessions, buffered shell output, transfer progress): they open no connection and change nothing remote.

func SuggestTool

func SuggestTool(name string, candidates []string) []string

func ToolCallID added in v0.107.0

func ToolCallID(ctx context.Context) string

func Truncate

func Truncate(s string) string

func TruncateTail

func TruncateTail(s string) string

func WebSearchFallback added in v0.107.33

func WebSearchFallback(settings func() config.WebSearchConfig) func() (Tool, bool)

WebSearchFallback returns a function that offers the web_search tool while settings names a usable search service. It reads settings on every call, so a changed configuration applies to the next request without a restart.

func WithAsk added in v0.107.0

func WithAsk(ctx context.Context, ask AskFunc) context.Context

func WithBackgrounding added in v0.107.28

func WithBackgrounding(ctx context.Context, fg *Foreground, processes func() *ManagedProcessManager) context.Context

WithBackgrounding lets the shell tools of a call register their foreground command with fg, so the user can move it to the background. processes returns the manager that takes the command over; it is called only then.

func WithComputerConfig added in v0.107.6

func WithComputerConfig(ctx context.Context, cfg config.ComputerConfig) context.Context

func WithComputerRuntime added in v0.107.6

func WithComputerRuntime(ctx context.Context, client *cua.Client) context.Context

func WithFileMutationObserver added in v0.107.0

func WithFileMutationObserver(ctx context.Context, observe func(string)) context.Context

WithFileMutationObserver records the pre-image immediately before a file tool mutates it.

func WithFileMutationRecorder added in v0.107.13

func WithFileMutationRecorder(ctx context.Context, record func(string)) context.Context

WithFileMutationRecorder scopes a recorder of the resolved paths file tools mutate under ctx. Unlike the observer it does not chain: the innermost scope (one tool call) owns its paths, so a subagent's edits are not attributed to the parent's task call.

func WithGate added in v0.103.0

func WithGate(ctx context.Context, gate func(GateRequest) (GateDecision, string)) context.Context

func WithLiveAgentNamedRoots added in v0.107.0

func WithLiveAgentNamedRoots(ctx context.Context, roots map[string]WorkspaceRoot) context.Context

WithLiveAgentNamedRoots maps root:// aliases and enabled skill:// names to explicit grants. Unmapped names never fall back to arbitrary host paths.

func WithOnUpdate

func WithOnUpdate(ctx context.Context, onUpdate func(outputSoFar string)) context.Context

func WithProcessStarted added in v0.107.6

func WithProcessStarted(ctx context.Context, record func(id string)) context.Context

WithProcessStarted lets the caller learn the ids of the processes and terminal sessions a tool call starts. Tools report them when the start succeeds, so the ids never come from the call's output text, which a foreground command controls.

func WithReview added in v0.107.6

func WithReview(ctx context.Context, hooks ReviewHooks) context.Context

func WithRunIdentity added in v0.107.0

func WithRunIdentity(ctx context.Context, identity RunIdentity) context.Context

func WithSkillReadRoots added in v0.107.6

func WithSkillReadRoots(ctx context.Context, dirs []string) context.Context

WithSkillReadRoots grants read-only access to the directories the system prompt advertises skills from. The prompt tells the model to read each skill's SKILL.md by absolute path, and those directories usually live outside the workspace. They extend the run's roots (or its default working-directory grant) and never replace them.

func WithToolCallID added in v0.107.0

func WithToolCallID(ctx context.Context, id string) context.Context

func WithWorkingDir added in v0.103.0

func WithWorkingDir(ctx context.Context, dir string) context.Context

func WithWorkspaceRoots added in v0.107.0

func WithWorkspaceRoots(ctx context.Context, roots []WorkspaceRoot) context.Context

func WithWorktreeWorkspaceRoots added in v0.107.6

func WithWorktreeWorkspaceRoots(ctx context.Context, parent, worktree string) context.Context

WithWorktreeWorkspaceRoots transfers the parent's workspace grants to an isolated worktree. Preserve access levels and unrelated additional roots; an explicitly empty grant set must remain empty.

func WorkingDir added in v0.103.0

func WorkingDir(ctx context.Context) string

Types

type AskAnswer added in v0.107.23

type AskAnswer struct {
	Labels []string
	Custom string
}

AskAnswer is the user's answer to one question: the options they chose (Labels, each one of the question's labels, in option order) and their own words (Custom, typed instead of or, on a multi-select question, beside the chosen options).

func (AskAnswer) Text added in v0.107.23

func (a AskAnswer) Text() string

Text is the answer as the model sees it: chosen options by their labels, the user's own words marked as typed rather than listed.

type AskFunc added in v0.107.0

type AskFunc func(context.Context, AskRequest) ([]AskAnswer, bool)

func AskHandler added in v0.107.28

func AskHandler(ctx context.Context) AskFunc

AskHandler returns the front end that asks the user for ctx: the one WithAsk set, else Ask; nil when nobody can be asked. Tools other than question use it to ask a question of their own.

type AskOption

type AskOption struct {
	Label       string `json:"label"`
	Description string `json:"description"`
	Recommended bool   `json:"recommended,omitempty"`
}

type AskQuestion added in v0.107.0

type AskQuestion struct {
	ID       string      `json:"id,omitempty"`
	Header   string      `json:"header,omitempty"`
	Prompt   string      `json:"prompt"`
	Options  []AskOption `json:"options"`
	Multiple bool        `json:"multiple,omitempty"`
}

type AskRequest

type AskRequest struct {
	Question  string        `json:"question,omitempty"`
	Options   []AskOption   `json:"options,omitempty"`
	Multiple  bool          `json:"multiple,omitempty"`
	Questions []AskQuestion `json:"questions,omitempty"`
}

AskRequest is one question (Question, Options, Multiple) or, when Questions is set, several asked together. An AskFunc answers with one AskAnswer per question, in order: a single one for the first form.

func ParseAskRequest added in v0.107.21

func ParseAskRequest(args json.RawMessage) (AskRequest, error)

ParseAskRequest reads the question tool's arguments. The single-question form passes through as before; the questions form is checked against what every client can show: 1-4 questions, each with a prompt and 2-6 distinct labels, ids unique (q1, q2, ... when omitted).

type EditPreview added in v0.107.21

type EditPreview struct {
	// Path is the file the tool will write.
	Path string
	// Diff lists the changed lines in the edit tool's result diff format:
	// "<line> <mark> <text>", mark one of ' ', '-', '+'. Empty when the change
	// is too large to compute a preview for (Truncated is then set) or when it
	// changes nothing.
	Diff string
	// NewFile marks a write that creates the file.
	NewFile bool
	// Truncated marks a Diff cut to the preview limits, or left out because the
	// file or the new content is too large.
	Truncated bool
}

EditPreview shows the change a gated file tool (write, edit, Write, Edit) is about to make, so a client can show it while the user decides. It is display only: the model never sees it.

type Foreground added in v0.107.28

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

Foreground tracks the foreground shell commands that the user can move to the background while they run, by tool call id.

func NewForeground added in v0.107.28

func NewForeground() *Foreground

func (*Foreground) Background added in v0.107.28

func (f *Foreground) Background(ctx context.Context, toolCallID string) (string, error)

Background moves the running command of tool call id to the background and returns the managed process id it continues under. The tool call then returns at once. A call that is unknown, finished or already moved returns ErrNotBackgroundable.

func (*Foreground) Running added in v0.107.28

func (f *Foreground) Running() []string

Running returns the ids of the tool calls that can be moved to the background now.

func (*Foreground) SetOnChange added in v0.107.28

func (f *Foreground) SetOnChange(fn func(toolCallID string, backgroundable bool))

SetOnChange registers fn to learn when a tool call becomes backgroundable and when it stops being so. fn runs on the tool's goroutine and must not block for long.

type GateDecision

type GateDecision int
const (
	GateAllowOnce GateDecision = iota
	GateAllowAlways
	GateReject
)

type GateRequest

type GateRequest struct {
	Context context.Context
	Tool    string
	Command string
	// Shell is the resolved shell that will run Command, for tools that run one;
	// empty when unknown, which permission rules parse strictly.
	Shell       string
	Rule        string
	Description string
	// Poll marks a call that only reads the output of a process or terminal this
	// session started; the tool checks ownership after the gate.
	Poll bool
	// OtherDir marks a command that runs outside the session's working directory
	// because of a cwd argument.
	OtherDir bool
	// Preview is the change a file tool (write, edit, Write, Edit) will make,
	// for the client to show before the user decides; nil for other tools and
	// when there is nothing to show. Rules never match on it.
	Preview *EditPreview
}

func GateRequestFor added in v0.107.6

func GateRequestFor(ctx context.Context, tool string, args json.RawMessage) GateRequest

GateRequestFor builds the request a tool's own gate check makes for args, so that a caller gating the call before it runs (AI review) shows the same command, shell and path, and permission rules match it the same way. Tools without a known target keep the raw arguments as the command.

type InteractiveRunner

type InteractiveRunner interface {
	Run(ctx context.Context, command string, timeout time.Duration, keys <-chan []byte) string
}
var InteractiveBash InteractiveRunner

type LSPQuerier added in v0.107.13

type LSPQuerier interface {
	Definition(ctx context.Context, path string, line, col int) ([]lsp.Location, error)
	References(ctx context.Context, path string, line, col int) ([]lsp.Location, error)
	Hover(ctx context.Context, path string, line, col int) (string, error)
	DocumentSymbols(ctx context.Context, path string) ([]lsp.Symbol, error)
	WorkspaceSymbols(ctx context.Context, path, dir, query string) ([]lsp.Symbol, error)
}

LSPQuerier is the code-intelligence side of the LSP manager the lsp tool uses.

type LiveAgentToolMetadata added in v0.107.0

type LiveAgentToolMetadata struct {
	ID            string   `json:"id"`
	Icon          string   `json:"icon"`
	ToolName      string   `json:"toolName"`
	Category      string   `json:"categoryId"`
	ReadOnly      bool     `json:"isReadOnly"`
	RuntimeScope  []string `json:"runtimeScopes"`
	DefaultPolicy string   `json:"defaultPolicy"`
}

LiveAgentToolMetadata mirrors the original builtinToolCatalog entries needed by provider/UI policy code without importing LiveAgent's TypeScript bundle.

func LiveAgentToolCatalogMetadata added in v0.107.0

func LiveAgentToolCatalogMetadata() []LiveAgentToolMetadata

type ManagedProcessManager added in v0.107.0

type ManagedProcessManager = liveagentProcessManager

ManagedProcessManager retains tool processes across model changes in a session.

func NewManagedProcessManager added in v0.107.0

func NewManagedProcessManager() *ManagedProcessManager

type PlanVerdict added in v0.107.21

type PlanVerdict struct {
	// Approved means the user accepted the plan; the client has already left
	// plan mode, so the agent goes on to implement it in the same turn.
	Approved bool
	// Feedback is what the user wants changed when they did not approve: a
	// general comment and comments on single lines of the plan.
	Feedback string
}

PlanVerdict is the user's answer to a plan the agent submitted with ExitPlanMode.

type Result added in v0.103.0

type Result struct {
	Text      string
	Parts     []ai.ContentPart
	Failed    bool
	Cancelled bool
	// ExitCode is the exit status of the command a shell tool (bash, Bash,
	// ManagedProcess, ProcessWait, ProcessStop) ran or observed, 0 included; nil
	// when the tool runs no command, or the command did not exit on its own
	// (it timed out, was cancelled or killed, or is still running).
	ExitCode *int
	// TimedOut marks a command the tool killed when its timeout passed.
	TimedOut bool
	// Duration is the tool's own wall-clock time, without time spent waiting for
	// the user's permission; zero when the tool did not run. Display only: the
	// model sees Text alone.
	Duration time.Duration
	// SandboxDenial is set when the OS sandbox most likely caused a shell
	// command to fail; the same explanation is appended to Text.
	SandboxDenial *sandbox.Denial
	// QuestionAnswers is what the user answered a question tool call, one
	// entry per question (see ReportQuestionAnswers). Display only.
	QuestionAnswers []ai.QuestionAnswer
	// Elicitations are the forms MCP servers asked the user to fill during
	// the call (see ReportElicitation). Display only.
	Elicitations []ai.Elicitation
}

func ExecuteResult added in v0.103.0

func ExecuteResult(ctx context.Context, ts []Tool, name string, args json.RawMessage, vision bool) Result

func (Result) DurationMs added in v0.107.21

func (r Result) DurationMs() int64

DurationMs is Duration rounded up to whole milliseconds, so a call that ran never reads as taking none; 0 when the tool did not run.

type ReviewHooks added in v0.107.6

type ReviewHooks struct {
	Before func(context.Context, string, json.RawMessage) (context.Context, error)
	After  func(context.Context, string, json.RawMessage, Result) Result
}

type RunIdentity added in v0.107.0

type RunIdentity struct {
	ConversationID string
	RunID          string
}

func RunIdentityFromContext added in v0.107.0

func RunIdentityFromContext(ctx context.Context) (RunIdentity, bool)

type TerminalManager added in v0.107.0

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

func NewTerminalManager added in v0.107.0

func NewTerminalManager() *TerminalManager

func (*TerminalManager) CloseAll added in v0.107.0

func (m *TerminalManager) CloseAll()

func (*TerminalManager) Handle added in v0.107.0

func (*TerminalManager) HasRunningSessions added in v0.107.6

func (m *TerminalManager) HasRunningSessions() bool

func (*TerminalManager) Read added in v0.107.0

func (m *TerminalManager) Read(ctx context.Context, id string, maxBytes int) (string, error)

func (*TerminalManager) Start added in v0.107.0

func (m *TerminalManager) Start(ctx context.Context, command, cwd string) (string, error)

type TerminalRecord added in v0.107.0

type TerminalRecord struct {
	ID             string `json:"id"`
	ProjectPathKey string `json:"project_path_key"`
	CWD            string `json:"cwd"`
	Shell          string `json:"shell"`
	Title          string `json:"title"`
	PID            int    `json:"pid"`
	Cols           uint16 `json:"cols"`
	Rows           uint16 `json:"rows"`
	CreatedAt      int64  `json:"created_at"`
	UpdatedAt      int64  `json:"updated_at"`
	FinishedAt     int64  `json:"finished_at"`
	ExitCode       int    `json:"exit_code"`
	Running        bool   `json:"running"`
	Kind           string `json:"kind"`
}

type TerminalRequest added in v0.107.0

type TerminalRequest struct {
	Action         string `json:"action"`
	ConversationID string `json:"conversation_id"`
	RunID          string `json:"run_id"`
	SessionID      string `json:"session_id"`
	ProjectPathKey string `json:"project_path_key"`
	CWD            string `json:"cwd"`
	Shell          string `json:"shell"`
	Title          string `json:"title"`
	Data           string `json:"data"`
	Cols           uint16 `json:"cols"`
	Rows           uint16 `json:"rows"`
	MaxBytes       int    `json:"max_bytes"`
}

TerminalRequest and TerminalResponse mirror the local Gateway v2 terminal protocol.

type TerminalResponse added in v0.107.0

type TerminalResponse struct {
	Action            string                `json:"action"`
	ConversationID    string                `json:"conversation_id"`
	RunID             string                `json:"run_id"`
	Session           *TerminalRecord       `json:"session,omitempty"`
	Sessions          []TerminalRecord      `json:"sessions,omitempty"`
	Output            []byte                `json:"output,omitempty"`
	Truncated         bool                  `json:"truncated"`
	OutputStartOffset uint64                `json:"output_start_offset"`
	OutputEndOffset   uint64                `json:"output_end_offset"`
	ShellOptions      []TerminalShellOption `json:"shell_options,omitempty"`
	DefaultShell      string                `json:"default_shell,omitempty"`
}

type TerminalShellOption added in v0.107.0

type TerminalShellOption struct {
	ID      string `json:"id"`
	Label   string `json:"label"`
	Command string `json:"command"`
}

type Tool

type Tool struct {
	Def       ai.Tool
	Run       func(ctx context.Context, args json.RawMessage) (string, error)
	NoInherit bool
	// Memory marks K-brain's own memory tools, which the memory switch hides; a
	// client tool that happens to share a name is not one of them.
	Memory bool
}

func All

func All() []Tool

func BackgroundProcessTool added in v0.107.28

func BackgroundProcessTool(manager *ManagedProcessManager) Tool

BackgroundProcessTool is the ManagedProcess tool for a catalog that has none: it reads, waits for and stops the commands the user moved to the background. It cannot start processes.

func BrowserExec

func BrowserExec() Tool

func ComputerExec

func ComputerExec() Tool

func LSPTool added in v0.107.13

func LSPTool() Tool

LSPTool is the read-only code-intelligence tool backed by the configured language servers. Permission-wise it is a read of path: Read rules and workspace roots apply.

func LegacyComputerExec added in v0.107.6

func LegacyComputerExec() Tool

func LiveAgentCatalog added in v0.107.0

func LiveAgentCatalog(provider ...string) []Tool

LiveAgentCatalog creates session-local tools without changing CLI defaults.

func LiveAgentCatalogWithManagers added in v0.107.0

func LiveAgentCatalogWithManagers(provider []string, terminalManager *TerminalManager, processManager *ManagedProcessManager) []Tool

func QuestionTool

func QuestionTool() Tool

func WebSearchTool added in v0.107.33

func WebSearchTool(settings func() config.WebSearchConfig) Tool

WebSearchTool is the web_search tool backed by the service settings names.

func WithoutCLIOnlyTools added in v0.107.13

func WithoutCLIOnlyTools(ts []Tool) []Tool

WithoutCLIOnlyTools returns ts without the CLI's grep, glob, list and web_fetch. The LiveAgent catalog brings its own root-confined Grep, Glob and List, so the backend drops these; web_fetch is not in that catalog, whose policies the app lets users set.

type WorkspaceRoot added in v0.107.0

type WorkspaceRoot struct {
	Path   string
	Access string
}

WorkspaceRoot is the backend's authoritative filesystem boundary.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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