tools

package
v0.157.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tools implements the read-only tool surface `gk chat` exposes to the model: five whitelisted git subcommands and two file tools, every invocation passing through the Sandbox and the shared redaction pipeline before its result reaches a (remote) provider.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterContextTools

func RegisterContextTools(r *Registry, collect func(ctx context.Context) (string, error))

RegisterContextTools adds git_context: an on-demand re-query of the same lightweight repository orientation snapshot gk chat injects into its system prompt as REPO_CONTEXT. REPO_CONTEXT is collected once at session start, so a long-lived REPL conversation can drift out of date (the user starts a rebase in another terminal, switches branches, etc.) — this tool lets the model clear that staleness instead of trusting a stale snapshot or guessing.

collect is injected by the CLI layer rather than implemented here: the actual collection (branch/upstream/ahead-behind/dirty/in-progress-op/ base-drift/worktree-count) is gk context's collectContext, which lives in internal/cli — the layer ABOVE this package that wires up the registry in the first place, so importing it here would create an import cycle. collect must return the exact same JSON shape the REPO_CONTEXT block carries (same source, same field-selected projection) so a re-query reads as "the same document, refreshed" rather than a different view.

func RegisterFileTools

func RegisterFileTools(r *Registry, f *FileTools)

RegisterFileTools adds the two file tools to the registry.

func RegisterGitTools

func RegisterGitTools(r *Registry, g *GitTools)

RegisterGitTools adds the five git tools to the registry.

func RegisterStatusTools

func RegisterStatusTools(r *Registry, g *GitTools)

RegisterStatusTools adds git_status, git_snapshot_list, and git_snapshot_diff to the registry. It reuses the same *GitTools (Runner + Sandbox + DenyGlobs) RegisterGitTools binds — no additional wiring.

func RegisterSuggestTools

func RegisterSuggestTools(r *Registry, lookup func(ctx context.Context, intent string) (string, error))

RegisterSuggestTools adds gk_suggest: a lookup of gk's OWN command tree by intent keywords. It exists to make the follow-up suggestion at the end of a chat answer a lookup rather than an invention.

The distinction matters more here than anywhere else in the registry. Every other tool reads the repository, so the model's claims are grounded by construction. A "what should I run next?" suggestion is inherently forward- looking — nothing in the repository can confirm it — so left to prior knowledge the model will confidently name subcommands and flags that do not exist in THIS build of gk. Routing it through the real cobra tree means the worst failure mode degrades from "a plausible command that errors out" to "no suggestion".

lookup is injected by the CLI layer for the same import-cycle reason RegisterContextTools takes a collector: the cobra command tree lives in internal/cli, the layer ABOVE this package that wires up the registry. Injecting it also keeps the catalogue honest — it is built by walking the live root command, so a command added, renamed, or removed anywhere in gk changes what this tool can suggest without anyone updating a table here.

func UnwrapEnvelope

func UnwrapEnvelope(toolName string, raw json.RawMessage) (json.RawMessage, error)

UnwrapEnvelope returns the real arguments for a call, unwrapping the envelope when one is present. Anything that is not unambiguously an envelope is returned untouched: a false positive would silently drop real arguments, which is far worse than the error a genuine envelope produces.

A recipient naming a DIFFERENT tool than the one invoked is rejected rather than unwrapped. That combination means the model addressed one tool and called another, so its arguments belong to the tool it named — feeding them to the invoked tool would either error confusingly or, worse, succeed with arguments meant for something else. Naming both sides lets the model fix the call in one step instead of guessing.

Types

type FileTools

type FileTools struct {
	Sandbox *Sandbox
	// PerFileCap bounds one file read (0 → registry's ResultCap applies
	// anyway; this exists to keep single reads well under it).
	PerFileCap int
}

FileTools exposes direct work-tree reads. Everything routes through the Sandbox — these two tools are the widest leak surface in gk chat (an arbitrary file's bytes travel to a remote provider), so there is no path that bypasses Resolve.

type GitTools

type GitTools struct {
	Runner    git.Runner
	Sandbox   *Sandbox
	DenyGlobs []string
}

GitTools binds the whitelisted read-only git surface (log/show/diff/ blame/grep — the whole list, there is no way to reach other subcommands) to a Runner. Every model-supplied string is validated at execution time: refs may not look like flags, paths go through the Sandbox, and pathspecs always follow a `--` separator, so a hostile tool input can never smuggle `--exec-path`-style options (the same blocked-args rule aichat's executor enforces).

type Registry

type Registry struct {

	// Redact scrubs a tool result before it reaches the model or disk.
	// Injected by the CLI layer (aicommit.Redact + secret patterns); nil
	// means no redaction and is only acceptable in tests.
	Redact func(string) string
	// ResultCap bounds one result's bytes (0 → defaultResultCap).
	ResultCap int
	// contains filtered or unexported fields
}

Registry owns the tool set and the two non-negotiable result stages: redact (secrets never leave the process un-scrubbed — results go to a REMOTE provider and are persisted to the session file) and cap.

func NewRegistry

func NewRegistry(redact func(string) string, resultCap int) *Registry

NewRegistry returns an empty registry with the given redactor.

func (*Registry) Dispatch

func (r *Registry) Dispatch(ctx context.Context, call provider.ToolCall) (res provider.ToolResult)

Dispatch executes one model-requested call. Every failure mode returns an IsError result instead of an error — the model should see "that didn't work" and adapt, not kill the conversation. Execution-time validation lives in the handlers (executor.go's defense-in-depth rule: never trust that a request which LOOKS safe was validated elsewhere).

func (*Registry) Register

func (r *Registry) Register(t Tool)

Register adds a tool, keeping registration order for Specs.

func (*Registry) Specs

func (r *Registry) Specs() []provider.ToolSpec

Specs renders the registry as vendor-neutral tool definitions.

type Sandbox

type Sandbox struct {
	// Root is the EvalSymlinks-canonicalized absolute repo work-tree root.
	Root string
	// DenyGlobs are matched against the repo-relative slash path with
	// aicommit.MatchDeny — the same semantics the commit privacy gate
	// applies to diffs. The list is a UNION of the built-in defaults and
	// config layers; callers must never let a repo-local config shrink it.
	DenyGlobs []string
}

Sandbox confines model-driven file access to the repository work tree. It is the single enforcement point — prompt-level "please stay inside the repo" instructions are advisory, this is not.

Resolution order matters: symlinks are resolved BEFORE the containment check (Rel + ".." test), or a symlink inside the repo pointing outside would pass on its unresolved name (see internal/cli/ignore.go's repoRelPath for the same idiom, and macOS /var → /private/var for why the root itself must be canonicalized too).

func NewSandbox

func NewSandbox(repoRoot string, denyGlobs []string) (*Sandbox, error)

NewSandbox canonicalizes the repo root and returns a sandbox enforcing the given deny globs.

func (*Sandbox) Resolve

func (s *Sandbox) Resolve(p string) (abs, rel string, err error)

Resolve validates a model-supplied path and returns its canonical absolute form plus the repo-relative slash path. Every rejection reason is deliberate:

  • containment: resolved (post-symlink) path must stay under Root — blocks ../ traversal AND in-repo symlinks pointing out
  • .git: never readable through file tools (credential helpers, hooks)
  • submodule boundary: an intermediate component owning its own .git is a different repository — outside this sandbox's contract
  • deny globs: same list, same matcher as the commit privacy gate

type Tool

type Tool struct {
	Name        string
	Description string
	Schema      json.RawMessage
	Handler     func(ctx context.Context, input json.RawMessage) (string, error)
}

Tool is one model-callable operation: schema for the vendor API, handler for execution. Handlers receive pre-validated JSON input and return raw text — redaction and capping happen in Dispatch, uniformly, so no individual handler can forget them.

Jump to

Keyboard shortcuts

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