tools

package
v0.9.50 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 71 Imported by: 0

Documentation

Overview

Package tools provides a permission-aware local tool system for term-llm.

Index

Constants

View Source
const (
	CreateGoalToolName = "create_goal"
	UpdateGoalToolName = "update_goal"
	GetGoalToolName    = "get_goal"
)
View Source
const (
	UpdateProgressToolName   = "update_progress"
	FinalizeProgressToolName = "finalize_progress"
)
View Source
const (
	QueueAgentEphemeralJobLabelKey   = "term_llm_queue_agent"
	QueueAgentEphemeralJobLabelValue = "ephemeral"
	QueueAgentEphemeralJobLabelsJSON = `{"term_llm_queue_agent":"ephemeral"}`
)
View Source
const (
	QueueAgentOriginWeb      = "web"
	QueueAgentOriginTelegram = "telegram"

	QueueAgentNotifyOriginHeader         = "X-Term-LLM-Queue-Agent-Origin"
	QueueAgentNotifySessionIDHeader      = "X-Term-LLM-Queue-Agent-Session-ID"
	QueueAgentNotifyTelegramChatIDHeader = "X-Term-LLM-Queue-Agent-Telegram-Chat-ID"
)
View Source
const (
	UIGetSourceToolName      = "ui_get_source"
	UIExtensionsToolName     = "ui_extensions"
	UIActivateToolName       = "ui_activate_extensions"
	ReadFileToolName         = "read_file"
	WriteFileToolName        = "write_file"
	EditFileToolName         = "edit_file"
	UnifiedDiffToolName      = "unified_diff"
	ShellToolName            = "shell"
	GrepToolName             = "grep"
	GlobToolName             = "glob"
	ViewImageToolName        = "view_image"
	ShowImageToolName        = "show_image"
	ShowMediaToolName        = "show_media"
	ImageGenerateToolName    = "image_generate"
	AskUserToolName          = "ask_user"
	SpawnAgentToolName       = "spawn_agent"
	QueueAgentToolName       = "queue_agent"
	WaitForJobsToolName      = "wait_for_jobs"
	RunAgentScriptToolName   = "run_agent_script"
	InitiateHandoverToolName = "initiate_handover"
	ManageWorkspaceToolName  = "manage_workspace"
	UpdatePlanToolName       = planpkg.ToolName

	HubDelegateToolName        = "hub_delegate"
	HubCheckDelegationToolName = "hub_check_delegation"
)

Tool specification names

View Source
const ActivateSkillToolName = "activate_skill"

ActivateSkillToolName is the tool spec name.

View Source
const LiveSettingsToolName = "live_settings"

LiveSettingsToolName controls only the current live call, never saved config.

View Source
const SearchSkillsToolName = "search_skills"

SearchSkillsToolName is the tool spec name.

Variables

View Source
var (
	OnApprovalStart func() // Called before showing prompt (pause TUI)
	OnApprovalEnd   func() // Called after prompt answered (resume TUI)
)

ApprovalUIHooks allows the TUI to coordinate with approval prompts. Set these callbacks before running the ask command to pause/resume the UI.

View Source
var (
	OnAskUserStart func() // Called before showing ask_user UI (pause TUI)
	OnAskUserEnd   func() // Called after ask_user UI answered (resume TUI)

	// AskUserUIFunc allows custom UI rendering for ask_user prompts.
	// When set, this function is called instead of RunAskUser.
	// This is used for inline rendering in alt screen mode.
	AskUserUIFunc func(questions []AskUserQuestion) ([]AskUserAnswer, error)
)

AskUserUIHooks allows the TUI to coordinate with ask_user tool prompts.

View Source
var ErrWorkspaceApprovalCancelled = errors.New("workspace approval cancelled")

ErrWorkspaceApprovalCancelled reports that a proactive workspace prompt was dismissed without making an authority decision.

View Source
var MutatorKinds = []ToolKind{KindEdit, KindExecute}

MutatorKinds are tool kinds that can modify the filesystem.

Functions

func AskUserAnswerSummary added in v0.0.106

func AskUserAnswerSummary(answers []AskUserAnswer) string

AskUserAnswerSummary renders a compact summary of canonical ask_user answers.

func CanonicalWorkspaceRoot added in v0.0.379

func CanonicalWorkspaceRoot(path, baseDir string) (string, error)

CanonicalWorkspaceRoot resolves symlinks, rejects missing/non-directory targets, and narrows paths inside Git repositories to that repository's own worktree root (never a broad shared parent/common-dir root).

func ClearApprovalHooks

func ClearApprovalHooks()

ClearApprovalHooks removes the approval hooks.

func ClearAskUserHooks added in v0.0.30

func ClearAskUserHooks()

ClearAskUserHooks removes the ask_user hooks.

func ClearAskUserUIFunc added in v0.0.50

func ClearAskUserUIFunc()

ClearAskUserUIFunc removes the custom ask_user UI function.

func ClearHandoverUIFunc added in v0.0.147

func ClearHandoverUIFunc()

ClearHandoverUIFunc removes the custom handover UI function.

func CollaborativeShellErrorKind added in v0.9.25

func CollaborativeShellErrorKind(err error) string

func ConfigureHubDelegation added in v0.0.296

func ConfigureHubDelegation(url, nodeID, token string)

ConfigureHubDelegation fills hub delegation config gaps in-process (explicit TERM_LLM_HUB_* values captured at startup win, matching the old env precedence) without ever writing the token into the process environment.

func ContextWithAskUserUIFunc added in v0.0.106

func ContextWithAskUserUIFunc(ctx context.Context, fn AskUserContextUIFunc) context.Context

ContextWithAskUserUIFunc stores a request-scoped ask_user handler in ctx.

func ContextWithCollaborativeShellRunBinding added in v0.9.25

func ContextWithCollaborativeShellRunBinding(ctx context.Context, binding CollaborativeShellRunBinding) context.Context

func ContextWithHandoverFunc added in v0.0.147

func ContextWithHandoverFunc(ctx context.Context, fn InitiateHandoverFunc) context.Context

ContextWithHandoverFunc stores a request-scoped handover handler in ctx.

func ContextWithLiveSettings added in v0.9.49

func ContextWithLiveSettings(ctx context.Context, sessionID string, apply func(context.Context, string) (live.Capabilities, error)) context.Context

ContextWithLiveSettings pins authority to the originating chat and call. A registered schema alone grants no access, including to subagent sessions.

func ContextWithQueueAgentOrigin added in v0.0.281

func ContextWithQueueAgentOrigin(ctx context.Context, origin QueueAgentOriginContext) context.Context

ContextWithQueueAgentOrigin stores trusted queue_agent notification origin metadata in ctx for the duration of a request.

func ContextWithSubagentEventCallback added in v0.9.46

func ContextWithSubagentEventCallback(ctx context.Context, callback SubagentEventCallback) context.Context

ContextWithSubagentEventCallback installs a request-scoped, trusted progress sink. It is used by spawn_agent and wait_for_jobs; arguments cannot replace it. A nil callback masks an inherited sink at a child execution boundary.

func CreateTUIHooks added in v0.0.35

func CreateTUIHooks(prog *tea.Program, flushAndWait func()) (start, end func())

CreateTUIHooks creates start/end hook functions for TUI coordination. flushAndWait is called to flush content before releasing terminal. prog is the tea.Program to release/restore.

func DetectShowMediaType added in v0.9.24

func DetectShowMediaType(data []byte) string

DetectShowMediaType returns a browser-safe media type for supported magic bytes, or an empty string when the data is not on show_media's allowlist.

func ExtractCommandPrefix

func ExtractCommandPrefix(cmd string) string

ExtractCommandPrefix extracts a shell command prefix for policy learning.

func FilterToolSpecsForApprovalMode added in v0.9.18

func FilterToolSpecsForApprovalMode(specs []llm.ToolSpec, approval *ApprovalManager) []llm.ToolSpec

FilterToolSpecsForApprovalMode removes tools that have no model-facing use in the effective approval mode. Executors stay registered so an in-flight call issued before a mode change can still complete safely.

func FindBestMatch added in v0.0.52

func FindBestMatch(lines []string, searchText string) int

FindBestMatch finds the line index that best matches the given text. Returns -1 if no reasonable match is found.

func GenerateDiff

func GenerateDiff(oldContent, newContent, filePath string) string

GenerateDiff creates a unified diff between old and new content.

func GenerateShellPattern added in v0.0.35

func GenerateShellPattern(command string) string

GenerateShellPattern creates a glob pattern from a command. For example: "go test ./..." -> "go test *"

func GetAndClearAskUserResult added in v0.0.37

func GetAndClearAskUserResult() string

GetAndClearAskUserResult retrieves and clears the last ask_user summary. Returns empty string if no result was stored.

func GetGitRepoID added in v0.0.35

func GetGitRepoID(root string) string

GetGitRepoID returns a unique identifier for a git repository. The ID is a SHA256 hash of the absolute root path, suitable for use as a filename.

func GetRelativePath added in v0.0.35

func GetRelativePath(path, repoRoot string) string

GetRelativePath returns the path relative to the repo root, or the original path if not in repo.

func GuardianDenialReason added in v0.0.379

func GuardianDenialReason(err error) (string, bool)

GuardianDenialReason extracts a concise human-facing reason from a Guardian permission denial. Model-directed retry guidance is intentionally omitted.

func HasUnsafeShellSyntax added in v0.0.134

func HasUnsafeShellSyntax(input string) bool

HasUnsafeShellSyntax reports whether input uses shell operators that require a shell.

func HubDelegationConfigured added in v0.0.296

func HubDelegationConfigured() bool

func HubDelegationEnviron added in v0.0.296

func HubDelegationEnviron() []string

HubDelegationEnviron returns the TERM_LLM_HUB_* entries a reload re-exec of this SAME binary needs to keep hub delegation working when the token originally arrived via the environment (init scrubbed it, so os.Environ() no longer carries it). It returns nil when the token came from flags or in-process config. Never pass the result to any other subprocess.

func HubDelegationIDFromContext added in v0.0.296

func HubDelegationIDFromContext(ctx context.Context) string

HubDelegationIDFromContext returns the delegation id ctx executes under, or "" when this execution is not part of a hub delegation.

func HubTokenFromEnvironment added in v0.0.403

func HubTokenFromEnvironment() string

HubTokenFromEnvironment returns the Hub token captured and scrubbed during package initialization. Hub server commands use this to honor the same TERM_LLM_HUB_TOKEN without putting it back into the subprocess environment.

func IsPathCapableTool added in v0.0.379

func IsPathCapableTool(name string) bool

IsPathCapableTool reports whether name is a local file/path operation that requires access to manage_workspace so explicit tool lists cannot strand it.

func IsPathInRepo added in v0.0.35

func IsPathInRepo(path, repoRoot string) bool

IsPathInRepo checks if the given path is under the specified repository root.

func NewCollaborativeShellError added in v0.9.25

func NewCollaborativeShellError(kind, message string) error

func NewCreateGoalTool added in v0.0.321

func NewCreateGoalTool() llm.Tool

NewCreateGoalTool creates the model-facing tool for starting a persisted goal.

func NewFinalizeProgressTool added in v0.0.117

func NewFinalizeProgressTool() llm.Tool

NewFinalizeProgressTool creates the finishing progress tool used only during finalization.

func NewGetGoalTool added in v0.0.321

func NewGetGoalTool(getter func() *session.Goal) llm.Tool

NewGetGoalTool creates the model-facing tool for reading the active goal.

func NewUpdateGoalTool added in v0.0.321

func NewUpdateGoalTool() llm.Tool

NewUpdateGoalTool creates the model-facing tool for completing or blocking a goal.

func NewUpdateProgressTool added in v0.0.117

func NewUpdateProgressTool() llm.Tool

NewUpdateProgressTool creates the non-finishing progress checkpoint tool.

func ParseToolsFlag

func ParseToolsFlag(value string) []string

ParseToolsFlag parses a comma-separated list of tool names. Special values: "all" or "*" expand to all available tools.

func PrepareCommand added in v0.0.134

func PrepareCommand(cmd *exec.Cmd) (func(), error)

PrepareCommand configures a tool-owned command for safe, non-interactive execution. The child starts a new session so it cannot open the caller's controlling terminal, and cancellation tears down its process group.

func SetApprovalHooks

func SetApprovalHooks(onStart, onEnd func())

SetApprovalHooks sets callbacks for TUI coordination during approval prompts.

func SetAskUserHooks added in v0.0.30

func SetAskUserHooks(onStart, onEnd func())

SetAskUserHooks sets callbacks for TUI coordination during ask_user prompts.

func SetAskUserUIFunc added in v0.0.50

func SetAskUserUIFunc(fn func(questions []AskUserQuestion) ([]AskUserAnswer, error))

SetAskUserUIFunc sets the function to call for ask_user prompts. When set, this replaces the default RunAskUser with custom rendering.

func SetHandoverUIFunc added in v0.0.147

func SetHandoverUIFunc(fn InitiateHandoverFunc)

SetHandoverUIFunc sets the function to call for initiate_handover prompts.

func SetLastAskUserResult added in v0.0.37

func SetLastAskUserResult(summary string)

SetLastAskUserResult stores the summary from the last ask_user execution. This should be called by the ask_user UI before signaling completion.

func SplitShellWords added in v0.0.134

func SplitShellWords(input string) ([]string, error)

SplitShellWords parses a command line into argv without invoking a shell.

func StandardToolNames added in v0.0.339

func StandardToolNames() []string

StandardToolNames returns the implicit tool set used by --tools all and disabled-list agents. Behavior-changing opt-in tools are intentionally absent. Hub delegation tools are included only when this process has Hub delegation credentials, so implicit tool lists do not advertise inoperable hub tools. Note: activate_skill is excluded as it requires a skills registry and is registered separately.

func ValidToolName

func ValidToolName(name string) bool

ValidToolName checks if a name is a valid tool spec name.

func ValidToolNames added in v0.0.339

func ValidToolNames() []string

ValidToolNames returns every accepted built-in tool name for validation and shell completion. Hub names remain valid even on standalone nodes so explicit configuration behaves consistently with the historical allowlist.

func WarnUnknownParams added in v0.0.96

func WarnUnknownParams(args json.RawMessage, knownKeys []string) string

WarnUnknownParams checks args JSON for keys not in knownKeys. Returns a warning string (with trailing newline) to prepend to tool output, or "" if no unknown keys found.

func WithHubDelegationID added in v0.0.296

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

WithHubDelegationID marks ctx as executing inside the given hub delegation.

Types

type ActivateSkillArgs added in v0.0.37

type ActivateSkillArgs struct {
	Name   string `json:"name"`
	Prompt string `json:"prompt,omitempty"`
}

ActivateSkillArgs are the arguments for the activate_skill tool.

type ActivateSkillTool added in v0.0.37

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

ActivateSkillTool implements the activate_skill tool.

func NewActivateSkillTool added in v0.0.37

func NewActivateSkillTool(registry *skills.Registry, approval *ApprovalManager) *ActivateSkillTool

NewActivateSkillTool creates a new activate_skill tool.

func (*ActivateSkillTool) Execute added in v0.0.37

Execute runs the activate_skill tool.

func (*ActivateSkillTool) Preview added in v0.0.37

func (t *ActivateSkillTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*ActivateSkillTool) SetOnActivated added in v0.0.37

func (t *ActivateSkillTool) SetOnActivated(cb SkillActivatedCallback)

SetOnActivated sets a callback that's called when a skill is activated.

func (*ActivateSkillTool) SetOnToolsActivated added in v0.0.90

func (t *ActivateSkillTool) SetOnToolsActivated(cb SkillToolsRegisteredCallback)

SetOnToolsActivated sets a callback that's called when a skill with declared tools is activated. The callback receives the tool definitions and the skill's directory so the caller can register them with the engine.

func (*ActivateSkillTool) Spec added in v0.0.37

func (t *ActivateSkillTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type ApprovalCache

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

ApprovalCache provides session-scoped caching for tool+path decisions.

func NewApprovalCache

func NewApprovalCache() *ApprovalCache

NewApprovalCache creates a new ApprovalCache.

func (*ApprovalCache) Clear

func (c *ApprovalCache) Clear()

Clear removes all cached approvals.

func (*ApprovalCache) Get

func (c *ApprovalCache) Get(toolName, path string) (ConfirmOutcome, bool)

Get retrieves a cached approval decision.

func (*ApprovalCache) GetForDirectory

func (c *ApprovalCache) GetForDirectory(toolName, dir string) (ConfirmOutcome, bool)

GetForDirectory checks if there's an approval for a directory.

func (*ApprovalCache) Set

func (c *ApprovalCache) Set(toolName, path string, outcome ConfirmOutcome)

Set stores an approval decision.

func (*ApprovalCache) SetForDirectory

func (c *ApprovalCache) SetForDirectory(toolName, dir string, outcome ConfirmOutcome)

SetForDirectory stores an approval for all paths under a directory. This is used when user approves "always" for a directory.

type ApprovalChoice added in v0.0.35

type ApprovalChoice int

ApprovalChoice represents a user's approval selection.

const (
	ApprovalChoiceDeny              ApprovalChoice = iota // Deny the request
	ApprovalChoiceOnce                                    // Allow once, no memory
	ApprovalChoiceFile                                    // Allow this file only (session)
	ApprovalChoiceDirectory                               // Allow this directory (session)
	ApprovalChoiceRepoRead                                // Allow read for entire repo (remembered)
	ApprovalChoiceRepoWrite                               // Allow write for entire repo (remembered)
	ApprovalChoicePattern                                 // Allow shell pattern in repo (remembered)
	ApprovalChoiceCommand                                 // Allow this specific command (session)
	ApprovalChoiceWorkspace                               // Confirm the canonical primary workspace (session)
	ApprovalChoiceCancelled                               // User cancelled with esc/ctrl+c
	ApprovalChoiceWorkspaceRemember                       // Confirm and remember the canonical primary workspace
)

type ApprovalManager

type ApprovalManager struct {
	YoloMode bool // Deprecated compatibility mirror for ModeYolo.

	// IgnoreProjectApprovals when true, skips persisted project-level approvals
	// (e.g., read_approved/write_approved from prior CLI sessions).
	// Used in serve mode so the web UI user is always prompted.
	IgnoreProjectApprovals bool

	// DebugApproval when true, logs approval decision details to stderr.
	DebugApproval bool

	// Callback for prompting user (set by TUI or CLI)
	// Legacy callback - will be replaced by PromptUIFunc
	PromptFunc func(req *ApprovalRequest) (ConfirmOutcome, string)

	// New UI callback for improved per-file and shell approval prompts.
	// Takes path/command, isWrite (for files), isShell, and workDir
	// (non-empty for shell commands to show where the command will run).
	// If nil, falls back to PromptFunc.
	PromptUIFunc func(path string, isWrite bool, isShell bool, workDir string) (ApprovalResult, error)
	// SharedShellPromptUIFunc is distinct so shared-shell approval can never be
	// mistaken for a local cwd/project authorization.
	SharedShellPromptUIFunc func(command string) (ApprovalResult, error)

	// WorkspacePromptFunc asks the human to establish whole-workspace read/write
	// authority for the proposed primary workspace outside yolo mode. Yolo never
	// invokes this callback or persists confirmation. PromptUIFunc cannot substitute
	// for it because per-file/project choices are not valid at this boundary.
	WorkspacePromptFunc func(workspace string) (WorkspaceApprovalResult, error)

	// GuardianEventFunc receives structured audit events for auto approvals/denials.
	GuardianEventFunc func(event GuardianEvent)
	// contains filtered or unexported fields
}

ApprovalManager coordinates approval requests and caching.

func NewApprovalManager

func NewApprovalManager(perms *ToolPermissions) *ApprovalManager

NewApprovalManager creates a new ApprovalManager.

func (*ApprovalManager) AddReadFile added in v0.9.37

func (m *ApprovalManager) AddReadFile(path string) error

AddReadFile grants read-only access to one existing regular file in this session. Descendants inherit the grant; siblings, directories, writes and shell commands do not.

func (*ApprovalManager) AddToolReadDir added in v0.0.312

func (m *ApprovalManager) AddToolReadDir(toolName, dir string) error

AddToolReadDir adds a per-tool read-only directory allowlist entry. Unlike ToolPermissions.ReadDirs, this does not grant access to other read tools.

func (*ApprovalManager) ApprovalMode added in v0.0.317

func (m *ApprovalManager) ApprovalMode() ApprovalMode

ApprovalMode returns this manager's effective mode, inheriting from parents. A root breaker suspension demotes locally-auto children without mutating the requested or persisted policy.

func (*ApprovalManager) ApproveDirectory

func (m *ApprovalManager) ApproveDirectory(toolName, dir string, outcome ConfirmOutcome)

ApproveDirectory adds a directory approval to the session cache.

func (*ApprovalManager) ApprovePath

func (m *ApprovalManager) ApprovePath(toolName, path string, outcome ConfirmOutcome)

ApprovePath adds a path/directory approval to the session cache.

func (*ApprovalManager) ApproveShellPattern

func (m *ApprovalManager) ApproveShellPattern(pattern string) error

ApproveShellPattern adds a pattern to the session cache.

func (*ApprovalManager) AutoHeadless added in v0.0.317

func (m *ApprovalManager) AutoHeadless() bool

func (*ApprovalManager) BindWorkspaceSessionID added in v0.0.379

func (m *ApprovalManager) BindWorkspaceSessionID(sessionID string)

BindWorkspaceSessionID records the owning root session once it becomes known. Child agent contexts cannot replace an existing root owner.

func (*ApprovalManager) CheckPathApproval

func (m *ApprovalManager) CheckPathApproval(toolName, path, toolInfo string, isWrite bool) (ConfirmOutcome, error)

CheckPathApproval checks if a path is approved for the given tool. Approvals are directory-scoped and tool-agnostic - approving a directory for one tool allows all tools to access files within it. toolInfo is optional context for display (e.g., filename being accessed).

func (*ApprovalManager) CheckPathApprovalWithContext added in v0.0.379

func (m *ApprovalManager) CheckPathApprovalWithContext(ctx context.Context, toolName, path, toolInfo string, isWrite bool) (ConfirmOutcome, error)

CheckPathApprovalWithContext checks path approval and supplies conversation evidence to Guardian when auto mode reviews an unmatched file request.

func (*ApprovalManager) CheckSharedShellApprovalWithContext added in v0.9.25

func (m *ApprovalManager) CheckSharedShellApprovalWithContext(ctx context.Context, command string, transcript []TranscriptEntry) (ConfirmOutcome, error)

CheckSharedShellApprovalWithContext authorizes a command for the current session's shared interactive terminal without consulting local/project state.

func (*ApprovalManager) CheckShellApproval

func (m *ApprovalManager) CheckShellApproval(command, workDir string) (ConfirmOutcome, error)

CheckShellApproval checks if a shell command is approved. workDir is the directory where the command will execute (may be empty for cwd).

func (*ApprovalManager) CheckShellApprovalWithContext added in v0.0.317

func (m *ApprovalManager) CheckShellApprovalWithContext(ctx context.Context, command, workDir string, transcript []TranscriptEntry) (ConfirmOutcome, error)

CheckShellApprovalWithContext checks shell approval with optional transcript evidence. It keeps the existing eager transcript API for callers that have already materialized approval evidence.

func (*ApprovalManager) ClearPrimaryWorkspace added in v0.0.379

func (m *ApprovalManager) ClearPrimaryWorkspace(ctx context.Context) error

ClearPrimaryWorkspace removes a proposal/confirmation without touching additional dynamic grants.

func (*ApprovalManager) Close added in v0.0.341

func (m *ApprovalManager) Close()

Close releases resources owned by the installed policy reviewer. It is safe to call repeatedly and leaves the manager without an auto-review callback.

func (*ApprovalManager) ConfigureWorkspacePersistence added in v0.0.379

func (m *ApprovalManager) ConfigureWorkspacePersistence(ctx context.Context, store session.Store, sessionID string) error

ConfigureWorkspacePersistence installs the optional durable grant backend and rehydrates primary confirmation plus additional grants before tools execute. Migration 46 needs no schema change: the stable reserved ID "primary" distinguishes the primary decision row from additional dynamic grants.

func (*ApprovalManager) EnsurePrimaryWorkspaceAccess added in v0.0.384

func (m *ApprovalManager) EnsurePrimaryWorkspaceAccess(ctx context.Context) error

EnsurePrimaryWorkspaceAccess proactively confirms the proposed primary workspace through the same direct-human boundary used by the first path tool access. Remembered workspaces and already-confirmed sessions return without a visible prompt; yolo remains an in-memory bypass and never persists trust.

func (*ApprovalManager) GrantWorkspace added in v0.0.379

func (m *ApprovalManager) GrantWorkspace(ctx context.Context, canonicalPath string, access session.WorkspaceAccess, reason string) (WorkspaceGrantResult, error)

GrantWorkspace validates, reviews, persists, and then installs an additional workspace capability. Callers must pass the already canonical narrow project root returned by CanonicalWorkspaceRoot.

func (*ApprovalManager) GuardianAutoSuspended added in v0.0.379

func (m *ApprovalManager) GuardianAutoSuspended() bool

GuardianAutoSuspended reports whether the root breaker is currently holding a requested auto policy in effective prompt mode. It is used to offer an explicit resume control; ordinary approvals must not clear the latch.

func (*ApprovalManager) GuardianReviewerAvailable added in v0.0.317

func (m *ApprovalManager) GuardianReviewerAvailable() bool

GuardianReviewerAvailable reports whether this manager or an ancestor has a policy reviewer installed for auto approval mode.

func (*ApprovalManager) IsWorkspacePathAllowed added in v0.0.379

func (m *ApprovalManager) IsWorkspacePathAllowed(path string, isWrite bool) bool

IsWorkspacePathAllowed performs a race-safe, boundary-safe capability check. It never consults shell permissions and therefore cannot authorize commands.

func (*ApprovalManager) PromptLock added in v0.0.44

func (m *ApprovalManager) PromptLock() *sync.Mutex

PromptLock returns the mutex used to serialize prompts. When a parent is set, returns the parent's lock to ensure all sub-agents share the same serialization.

func (*ApprovalManager) RequestedApprovalMode added in v0.9.22

func (m *ApprovalManager) RequestedApprovalMode() ApprovalMode

RequestedApprovalMode returns the configured mode before a Guardian breaker suspension is applied. Child managers inherit the first non-prompt parent mode.

func (*ApprovalManager) ResumeAuto added in v0.0.379

func (m *ApprovalManager) ResumeAuto() bool

ResumeAuto explicitly clears a breaker suspension and starts a fresh auto epoch. It returns false when auto is not currently suspended.

func (*ApprovalManager) ReviewPolicy added in v0.0.341

ReviewPolicy invokes the installed policy reviewer, including an inherited parent reviewer. Callers cannot replace the callback without going through SetPolicyReviewFunc and its resource-cleanup contract.

func (*ApprovalManager) RevokeWorkspace added in v0.0.379

func (m *ApprovalManager) RevokeWorkspace(ctx context.Context, selector string) (WorkspaceCapability, bool, error)

RevokeWorkspace removes an additional grant by stable ID or exact canonical path. A yolo overlay is removed without touching any durable baseline beneath it. The proposed/confirmed primary can only change through direct session controls, never through the model-facing tool.

func (*ApprovalManager) SetApprovalMode added in v0.0.317

func (m *ApprovalManager) SetApprovalMode(mode ApprovalMode)

SetApprovalMode sets the manager's requested approval mode. Root mode transitions start or end an auto epoch; child setup must not reset root-owned Guardian breaker state. Yolo workspace grants are ephemeral overlays: the transition out of an effective yolo mode removes them before it returns.

func (*ApprovalManager) SetAutoHeadless added in v0.0.317

func (m *ApprovalManager) SetAutoHeadless(headless bool)

SetAutoHeadless preserves the legacy headless marker for API/setup compatibility. Guardian review outcomes fail closed in every runtime.

func (*ApprovalManager) SetAutoMode added in v0.0.317

func (m *ApprovalManager) SetAutoMode(enabled bool)

SetAutoMode enables or disables guardian auto mode.

func (*ApprovalManager) SetGuardianClassifyAllShell added in v0.0.379

func (m *ApprovalManager) SetGuardianClassifyAllShell(enabled bool)

SetGuardianClassifyAllShell controls whether auto mode sends every pattern-based shell approval through Guardian. Exact approvals remain usable.

func (*ApprovalManager) SetParent added in v0.0.44

func (m *ApprovalManager) SetParent(parent *ApprovalManager) error

SetParent sets the parent ApprovalManager for inheritance. When set, this manager checks the parent's session caches and prompt transports. The shared root prompt lock serializes parent/child prompts. Returns an error if setting parent would create a cycle.

func (*ApprovalManager) SetPolicyReviewFunc added in v0.0.341

func (m *ApprovalManager) SetPolicyReviewFunc(reviewFunc func(context.Context, PolicyReviewRequest) (PolicyDecision, error), cleanup func())

SetPolicyReviewFunc installs a policy reviewer and atomically retires the previous reviewer's resources. Cleanup runs outside the manager lock so an in-flight callback can finish or observe cancellation without deadlocking.

func (*ApprovalManager) SetPrimaryWorkspace added in v0.0.379

func (m *ApprovalManager) SetPrimaryWorkspace(path string) error

SetPrimaryWorkspace records a canonical proposed primary workspace. The proposal grants no file authority until the direct human confirmation path succeeds. Rebinding preserves additional grants and invalidates a mismatched primary confirmation.

func (*ApprovalManager) SetPrimaryWorkspaceWithContext added in v0.0.379

func (m *ApprovalManager) SetPrimaryWorkspaceWithContext(ctx context.Context, path string) error

SetPrimaryWorkspaceWithContext is the context-aware rebinding path used by session/worktree controls.

func (*ApprovalManager) SetYoloMode added in v0.0.35

func (m *ApprovalManager) SetYoloMode(enabled bool)

SetYoloMode enables or disables yolo mode. Yolo mode auto-approves all tool executions without prompting.

func (*ApprovalManager) WorkspaceCapabilities added in v0.0.379

func (m *ApprovalManager) WorkspaceCapabilities() []WorkspaceCapability

WorkspaceCapabilities returns a deterministic snapshot shared by this manager and every descendant. A proposed primary is visible but is not authority.

func (*ApprovalManager) YoloEnabled added in v0.0.182

func (m *ApprovalManager) YoloEnabled() bool

YoloEnabled reports whether this manager or any parent manager is in yolo mode.

type ApprovalMode added in v0.0.317

type ApprovalMode int

ApprovalMode controls how unmatched tool approval requests are handled.

const (
	ModePrompt ApprovalMode = iota
	ModeAuto
	ModeYolo
)

func (ApprovalMode) String added in v0.0.317

func (m ApprovalMode) String() string

type ApprovalModel added in v0.0.50

type ApprovalModel struct {
	Done bool // Prompt completed
	// contains filtered or unexported fields
}

ApprovalModel is the bubbletea model for approval prompts. It can be embedded in a parent TUI for inline rendering.

func NewEmbeddedApprovalModel added in v0.0.50

func NewEmbeddedApprovalModel(path string, isWrite bool, width int) *ApprovalModel

NewEmbeddedApprovalModel creates an approval model for file access that can be embedded in a parent TUI.

func NewEmbeddedShellApprovalModel added in v0.0.50

func NewEmbeddedShellApprovalModel(command, workDir string, width int) *ApprovalModel

NewEmbeddedShellApprovalModel creates an approval model for shell commands that can be embedded in a parent TUI.

func NewEmbeddedWorkspaceApprovalModel added in v0.0.379

func NewEmbeddedWorkspaceApprovalModel(workspace string, width int) *ApprovalModel

NewEmbeddedWorkspaceApprovalModel creates the dedicated authority-boundary prompt for a proposed primary workspace. It deliberately offers no per-file, directory, pattern, or project-persistent choices.

func (*ApprovalModel) Init added in v0.0.50

func (m *ApprovalModel) Init() tea.Cmd

func (*ApprovalModel) IsDone added in v0.0.50

func (m *ApprovalModel) IsDone() bool

IsDone returns true if the user has made a selection.

func (*ApprovalModel) RenderSummary added in v0.0.50

func (m *ApprovalModel) RenderSummary() string

RenderSummary returns a summary of the user's choice for display after the UI closes.

func (*ApprovalModel) Result added in v0.0.50

func (m *ApprovalModel) Result() ApprovalResult

Result returns the user's selection after the prompt is done.

func (*ApprovalModel) SetWidth added in v0.0.50

func (m *ApprovalModel) SetWidth(width int)

SetWidth updates the width for rendering.

func (*ApprovalModel) Update added in v0.0.50

func (m *ApprovalModel) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles messages for standalone tea.Program use (calls tea.Quit on completion).

func (*ApprovalModel) UpdateEmbedded added in v0.0.50

func (m *ApprovalModel) UpdateEmbedded(msg tea.Msg) bool

UpdateEmbedded handles messages for embedded use (does not call tea.Quit). Returns true if the model finished (user made a selection or cancelled).

func (*ApprovalModel) View added in v0.0.50

func (m *ApprovalModel) View() tea.View

type ApprovalOption added in v0.0.35

type ApprovalOption struct {
	Label       string         // Display text
	Description string         // Explanation text
	Choice      ApprovalChoice // The choice this option represents
	Path        string         // Path for directory/file choices
	Pattern     string         // Pattern for shell choices
	SaveToRepo  bool           // Whether this saves to project
}

ApprovalOption represents a single option in the approval UI.

func BuildFileOptions added in v0.0.111

func BuildFileOptions(path string, repoInfo *GitRepoInfo, isWrite bool) []ApprovalOption

BuildFileOptions creates the options for a file access prompt.

func BuildSharedShellOptions added in v0.9.25

func BuildSharedShellOptions(command string) []ApprovalOption

BuildSharedShellOptions creates session-scoped options for a command running in the browser-visible terminal, which may be attached to a remote host.

func BuildShellOptions added in v0.0.111

func BuildShellOptions(command string, repoInfo *GitRepoInfo) []ApprovalOption

BuildShellOptions creates the options for a shell command prompt.

func BuildWorkspaceOptions added in v0.0.379

func BuildWorkspaceOptions(workspace string) []ApprovalOption

BuildWorkspaceOptions returns the valid human choices for proposed primary authority. The canonical root is shown separately by ApprovalModel.

type ApprovalRequest

type ApprovalRequest struct {
	ToolName    string
	Path        string   // For file tools
	Command     string   // For shell tool
	Description string   // Human-readable description
	Options     []string // Directory options for file tools
	ToolInfo    string   // Preview info for display (filename, URL, etc.)

	// Callbacks
	OnApprove func(choice string, saveToConfig bool) // choice is dir path or pattern
	OnDeny    func()
}

ApprovalRequest represents a pending approval request.

type ApprovalResult added in v0.0.35

type ApprovalResult struct {
	Choice     ApprovalChoice
	Path       string // Selected path (for file/directory)
	Pattern    string // Selected pattern (for shell)
	SaveToRepo bool   // Whether to save to project approvals
	Cancelled  bool   // Whether user cancelled
}

ApprovalResult contains the result of an approval prompt.

func RunFileApprovalUI added in v0.0.35

func RunFileApprovalUI(path string, isWrite bool) (ApprovalResult, error)

RunFileApprovalUI displays the approval UI for file access and returns the result.

func RunShellApprovalUI added in v0.0.35

func RunShellApprovalUI(command, workDir string) (ApprovalResult, error)

RunShellApprovalUI displays the approval UI for shell commands and returns the result.

type AskUserAnswer added in v0.0.30

type AskUserAnswer struct {
	QuestionIndex int      `json:"question_index"`
	Header        string   `json:"header"`
	Selected      string   `json:"selected"`
	SelectedList  []string `json:"selected_list,omitempty"`
	IsCustom      bool     `json:"is_custom"`
	IsMultiSelect bool     `json:"is_multi_select,omitempty"`
}

AskUserAnswer represents the user's answer to a question.

func NormalizeAskUserAnswers added in v0.0.106

func NormalizeAskUserAnswers(questions []AskUserQuestion, answers []AskUserAnswer) ([]AskUserAnswer, error)

NormalizeAskUserAnswers validates ask_user answers and rewrites them into the canonical shape expected by the tool result.

func RunAskUser added in v0.0.30

func RunAskUser(questions []AskUserQuestion) ([]AskUserAnswer, error)

RunAskUser presents the questions to the user and returns their answers.

type AskUserArgs added in v0.0.30

type AskUserArgs struct {
	Questions []AskUserQuestion `json:"questions"`
}

AskUserArgs are the arguments passed to the ask_user tool.

type AskUserContextUIFunc added in v0.0.106

type AskUserContextUIFunc func(context.Context, []AskUserQuestion) ([]AskUserAnswer, error)

AskUserContextUIFunc renders ask_user questions using a request-scoped UI implementation, such as the web serve roundtrip.

type AskUserModel added in v0.0.50

type AskUserModel struct {
	Done      bool
	Cancelled bool
	// contains filtered or unexported fields
}

AskUserModel is the bubbletea model for the ask_user UI. It can be embedded in a parent TUI for inline rendering.

func NewEmbeddedAskUserModel added in v0.0.50

func NewEmbeddedAskUserModel(questions []AskUserQuestion, width int) *AskUserModel

NewEmbeddedAskUserModel creates an ask_user model for embedding in a parent TUI.

func (*AskUserModel) Answers added in v0.0.50

func (m *AskUserModel) Answers() []AskUserAnswer

Answers returns the collected answers after the user completes the dialog.

func (*AskUserModel) Init added in v0.0.50

func (m *AskUserModel) Init() tea.Cmd

func (*AskUserModel) IsCancelled added in v0.0.50

func (m *AskUserModel) IsCancelled() bool

IsCancelled returns true if the user cancelled the dialog.

func (*AskUserModel) IsDone added in v0.0.50

func (m *AskUserModel) IsDone() bool

IsDone returns true if the user has completed all questions.

func (*AskUserModel) RenderPlainSummary added in v0.0.50

func (m *AskUserModel) RenderPlainSummary() string

RenderPlainSummary returns a plain text summary (styling applied at display time).

func (*AskUserModel) RenderSummary added in v0.0.50

func (m *AskUserModel) RenderSummary() string

RenderSummary returns a styled summary of the user's choices.

func (*AskUserModel) SetWidth added in v0.0.50

func (m *AskUserModel) SetWidth(width int)

SetWidth updates the width for rendering.

func (*AskUserModel) Update added in v0.0.50

func (m *AskUserModel) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles messages for standalone tea.Program use (calls tea.Quit on completion).

func (*AskUserModel) UpdateEmbedded added in v0.0.50

func (m *AskUserModel) UpdateEmbedded(msg tea.Msg) tea.Cmd

UpdateEmbedded handles messages for embedded use (does not call tea.Quit). Returns a tea.Cmd if one is needed (e.g., for text input blinking).

func (*AskUserModel) View added in v0.0.50

func (m *AskUserModel) View() tea.View

type AskUserOption added in v0.0.30

type AskUserOption struct {
	Label       string `json:"label"`
	Description string `json:"description"`
}

AskUserOption represents a choice for a question.

type AskUserQuestion added in v0.0.30

type AskUserQuestion struct {
	Header      string          `json:"header"`
	Question    string          `json:"question"`
	Options     []AskUserOption `json:"options"`
	MultiSelect bool            `json:"multi_select"`
}

AskUserQuestion represents a question to present to the user.

type AskUserResult added in v0.0.30

type AskUserResult struct {
	Answers []AskUserAnswer `json:"answers,omitempty"`
	Error   string          `json:"error,omitempty"`
	Type    string          `json:"type,omitempty"`
}

AskUserResult is the complete result returned by the tool.

type AskUserTool added in v0.0.30

type AskUserTool struct{}

AskUserTool implements the ask_user tool.

func NewAskUserTool added in v0.0.30

func NewAskUserTool() *AskUserTool

NewAskUserTool creates a new ask_user tool.

func (*AskUserTool) Execute added in v0.0.30

func (t *AskUserTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

Execute runs the ask_user tool.

func (*AskUserTool) Preview added in v0.0.30

func (t *AskUserTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*AskUserTool) Spec added in v0.0.30

func (t *AskUserTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type Attachment

type Attachment struct {
	Path     string `json:"path"`
	MimeType string `json:"mime_type,omitempty"`
	Data     []byte `json:"data,omitempty"`
}

Attachment represents a file attachment in tool results.

type AttributedFileRecorder added in v0.9.0

type AttributedFileRecorder interface {
	RecordAttributedChange(ctx context.Context, rec filetrack.ChangeRecord) (*llm.FileChange, error)
}

type AttributedPathChecker added in v0.9.0

type AttributedPathChecker interface {
	HasAttributedPath(ctx context.Context, sessionID, path string) bool
}

FileChangeRecorder records file changes made by tools so sessions can expose a cumulative diff. An interface keeps the tools package decoupled from filetrack storage internals (mirrors ImageRecorder).

Implementations must be best-effort: recording failures never surface to the calling tool.

type CollaborativeShellActivityController added in v0.9.25

type CollaborativeShellActivityController interface {
	ReserveActivity(ctx context.Context, sessionID, expectedShellID string) (*SharedShellActivity, error)
	CommitDurableActivity(ctx context.Context, sessionID string, activity SharedShellActivity) error
	CommitActivity(ctx context.Context, sessionID, reservationID string) error
	ReleaseActivity(ctx context.Context, sessionID, reservationID string)
}

CollaborativeShellActivityController advances terminal activity only after its matching transcript boundary has committed.

type CollaborativeShellActivityFence added in v0.9.25

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

CollaborativeShellActivityFence records the newest terminal offset visible to one model run. The controller advances it when a shell call is rejected with fresh browser activity, allowing the model to reconsider and retry safely.

func NewCollaborativeShellActivityFence added in v0.9.25

func NewCollaborativeShellActivityFence(offset int64, browserInputRevision ...uint64) *CollaborativeShellActivityFence

func (*CollaborativeShellActivityFence) Advance added in v0.9.25

func (f *CollaborativeShellActivityFence) Advance(offset int64, browserInputRevision ...uint64)

func (*CollaborativeShellActivityFence) Offset added in v0.9.25

func (*CollaborativeShellActivityFence) Snapshot added in v0.9.25

func (f *CollaborativeShellActivityFence) Snapshot() (int64, uint64)

type CollaborativeShellController added in v0.9.25

type CollaborativeShellController interface {
	Mode(ctx context.Context, sessionID string) CollaborativeShellMode
	Execute(ctx context.Context, sessionID string, args SharedShellArgs) (ShellResult, error)
	PrepareRequestContext(ctx context.Context, sessionID string, messages []llm.Message) ([]llm.Message, error)
	PrepareCompactionContext(ctx context.Context, sessionID string, result *llm.CompactionResult) error
}

CollaborativeShellController is the transport-neutral bridge used by ShellTool.

type CollaborativeShellError added in v0.9.25

type CollaborativeShellError struct {
	Kind    string
	Message string
}

CollaborativeShellError has a stable machine-readable failure kind.

func (*CollaborativeShellError) Error added in v0.9.25

func (e *CollaborativeShellError) Error() string

type CollaborativeShellMode added in v0.9.25

type CollaborativeShellMode struct {
	State                CollaborativeShellState
	ShellID              string
	Enabled              bool
	Reason               string
	ActivityOffset       int64
	BrowserInputRevision uint64
}

CollaborativeShellMode is a point-in-time routing snapshot. Enabled remains true for attention states so a run cannot silently fall back to local execution.

type CollaborativeShellRunBinding added in v0.9.25

type CollaborativeShellRunBinding struct {
	Required bool
	ShellID  string
	Fence    *CollaborativeShellActivityFence
}

CollaborativeShellRunBinding pins authority for one complete engine run.

func CollaborativeShellRunBindingFromContext added in v0.9.25

func CollaborativeShellRunBindingFromContext(ctx context.Context) (CollaborativeShellRunBinding, bool)

type CollaborativeShellState added in v0.9.25

type CollaborativeShellState string

CollaborativeShellState is the controller's authoritative shared-shell state.

const (
	CollaborativeShellOff            CollaborativeShellState = "off"
	CollaborativeShellReady          CollaborativeShellState = "ready"
	CollaborativeShellAgentRunning   CollaborativeShellState = "agent_running"
	CollaborativeShellDesynchronized CollaborativeShellState = "desynchronized"
	CollaborativeShellUnavailable    CollaborativeShellState = "unavailable"
)

type ConfirmOutcome

type ConfirmOutcome string

ConfirmOutcome represents the result of a user confirmation prompt.

const (
	ProceedOnce          ConfirmOutcome = "once"        // Single approval
	ProceedAlways        ConfirmOutcome = "always"      // Session-scoped approval
	ProceedAlwaysAndSave ConfirmOutcome = "always_save" // Persist to config
	Cancel               ConfirmOutcome = "cancel"      // User denied
)

func HuhApprovalPrompt

func HuhApprovalPrompt(req *ApprovalRequest) (ConfirmOutcome, string)

HuhApprovalPrompt prompts the user for approval using a huh form. This provides a nicer UI than the TTY-based prompt.

func TTYApprovalPrompt

func TTYApprovalPrompt(req *ApprovalRequest) (ConfirmOutcome, string)

TTYApprovalPrompt prompts the user for directory access approval via /dev/tty. This allows prompting even when stdin is piped.

type CreateGoalArgs added in v0.0.321

type CreateGoalArgs struct {
	Objective   string `json:"objective"`
	TokenBudget int    `json:"token_budget,omitempty"`
}

func ParseCreateGoalArgs added in v0.0.321

func ParseCreateGoalArgs(args json.RawMessage) (CreateGoalArgs, error)

ParseCreateGoalArgs validates create_goal arguments for both tool execution and runner commit tracking.

type CustomScriptTool added in v0.0.90

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

CustomScriptTool implements llm.Tool for a script-backed custom tool declared in agent.yaml under tools.custom.

func (*CustomScriptTool) Execute added in v0.0.90

Execute runs the custom script with the LLM's args as JSON on stdin.

func (*CustomScriptTool) Preview added in v0.0.90

func (t *CustomScriptTool) Preview(args json.RawMessage) string

Preview returns a short preview string for display in the UI.

func (*CustomScriptTool) Spec added in v0.0.90

func (t *CustomScriptTool) Spec() llm.ToolSpec

Spec returns the tool spec for the LLM.

type DirCache

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

DirCache provides tool-agnostic directory approval caching. When a directory is approved, all tools can access files within it. Read and write approvals are tracked separately: a read approval does not grant write access, but a write approval implies read access.

func NewDirCache

func NewDirCache() *DirCache

NewDirCache creates a new DirCache.

func (*DirCache) IsPathInApprovedDir

func (c *DirCache) IsPathInApprovedDir(path string, isWrite bool) bool

IsPathInApprovedDir checks if a path is within any approved directory for the given access type. Write access requires an explicit write approval; read access is satisfied by either a read or write approval.

func (*DirCache) Set

func (c *DirCache) Set(dir string, outcome ConfirmOutcome, isWrite bool)

Set stores a directory approval for the given access type.

func (*DirCache) Snapshot added in v0.0.317

func (c *DirCache) Snapshot() (readDirs []string, writeDirs []string)

type EditFileArgs

type EditFileArgs struct {
	Path string `json:"path"`
	// Mode 1: Delegated edit (natural language)
	Instructions string `json:"instructions,omitempty"`
	LineRange    string `json:"line_range,omitempty"` // e.g., "10-20"
	// Mode 2: Direct edit (deterministic)
	OldText string `json:"old_text,omitempty"`
	NewText string `json:"new_text,omitempty"`
}

EditFileArgs supports two modes: - Mode 1 (Delegated): instructions + optional line_range - Mode 2 (Direct): old_text + new_text

type EditFileTool

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

EditFileTool implements the edit_file tool with dual modes.

func NewEditFileTool

func NewEditFileTool(approval *ApprovalManager, configs ...*ToolConfig) *EditFileTool

NewEditFileTool creates a new EditFileTool.

func (*EditFileTool) Execute

func (t *EditFileTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*EditFileTool) Preview

func (t *EditFileTool) Preview(args json.RawMessage) string

func (*EditFileTool) Spec

func (t *EditFileTool) Spec() llm.ToolSpec

type EnvMap added in v0.0.94

type EnvMap map[string]string

EnvMap is a string-to-string map that can unmarshal both the standard JSON object form ({"KEY":"val"}) used by non-strict providers, and the array form ([{"key":"KEY","value":"val"}]) emitted by OpenAI strict-mode schemas where additionalProperties must be false.

func (*EnvMap) UnmarshalJSON added in v0.0.94

func (e *EnvMap) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type FileChangeRecorder added in v0.0.286

type FileChangeRecorder interface {
	RecordChange(ctx context.Context, rec filetrack.ChangeRecord) *llm.FileChange
	// SessionPaths returns absolute paths already recorded for a session.
	SessionPaths(ctx context.Context, sessionID string) []string
	// MaxFileBytes is the per-file content cap; callers can use it to bound
	// snapshot reads before handing content to RecordChange.
	MaxFileBytes() int
}

FileChangeRecorder retains the compatibility method for embedders. Built-in tools require/use the explicit classified interfaces above and never route a shell detection through RecordChange.

type FileEntry

type FileEntry struct {
	FilePath  string    `json:"file_path"`
	IsDir     bool      `json:"is_dir"`
	SizeBytes int64     `json:"size_bytes"`
	ModTime   time.Time `json:"mod_time"`
}

FileEntry represents a file in glob results.

type FilesystemObservationRecorder added in v0.9.0

type FilesystemObservationRecorder interface {
	RecordFilesystemObservation(ctx context.Context, obs filetrack.FilesystemObservation) (*llm.FilesystemObservationSummary, error)
}

type GitRepoInfo added in v0.0.35

type GitRepoInfo struct {
	IsRepo   bool   // Whether the path is inside a git repository
	Root     string // Absolute path to the repository root
	RepoName string // Basename of the repository (for display)
}

GitRepoInfo contains information about a git repository.

func DetectGitRepo added in v0.0.35

func DetectGitRepo(path string) GitRepoInfo

DetectGitRepo detects if the given path is inside a git repository. Returns GitRepoInfo with IsRepo=false if not in a repo or if git is unavailable. The path can be a file or directory.

type GlobArgs

type GlobArgs struct {
	Pattern string `json:"pattern"`
	Path    string `json:"path,omitempty"`
}

GlobArgs are the arguments for glob.

type GlobTool

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

GlobTool implements the glob tool.

func NewGlobTool

func NewGlobTool(approval *ApprovalManager, configs ...*ToolConfig) *GlobTool

NewGlobTool creates a new GlobTool.

func (*GlobTool) Execute

func (t *GlobTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*GlobTool) Preview

func (t *GlobTool) Preview(args json.RawMessage) string

func (*GlobTool) Spec

func (t *GlobTool) Spec() llm.ToolSpec

type GrepArgs

type GrepArgs struct {
	Pattern          string `json:"pattern"`
	Path             string `json:"path,omitempty"`
	Include          string `json:"include,omitempty"` // glob filter e.g., "*.go"
	Exclude          string `json:"exclude,omitempty"` // glob pattern to exclude e.g., "vendor/**"
	Type             string `json:"type,omitempty"`    // rg --type filter, e.g. "go"
	MaxResults       int    `json:"max_results,omitempty"`
	ContextLines     int    `json:"context_lines,omitempty"`      // lines of context around match (default 2)
	FilesWithMatches bool   `json:"files_with_matches,omitempty"` // return filenames only
	Multiline        bool   `json:"multiline,omitempty"`          // allow matches to span line boundaries
}

GrepArgs are the arguments for grep.

type GrepMatch

type GrepMatch struct {
	FilePath   string `json:"file_path"`
	LineNumber int    `json:"line_number"`
	Match      string `json:"match"`
	Context    string `json:"context,omitempty"` // 3 lines of context
}

GrepMatch represents a single grep match.

type GrepTool

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

GrepTool implements the grep tool.

func NewGrepTool

func NewGrepTool(approval *ApprovalManager, limits OutputLimits, configs ...*ToolConfig) *GrepTool

NewGrepTool creates a new GrepTool.

func (*GrepTool) Execute

func (t *GrepTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*GrepTool) Preview

func (t *GrepTool) Preview(args json.RawMessage) string

func (*GrepTool) Spec

func (t *GrepTool) Spec() llm.ToolSpec

type GuardianEvent added in v0.0.324

type GuardianEvent struct {
	ToolCallID string
	ToolName   string
	Path       string
	IsWrite    bool
	Command    string
	WorkDir    string
	Message    string
	Outcome    GuardianOutcome
	Model      string
	Usage      llm.Usage
}

GuardianEvent is a guardian review annotation correlated with the tool invocation that caused the review.

type GuardianOutcome added in v0.0.324

type GuardianOutcome string

GuardianOutcome describes the result of an automatic guardian review.

const (
	GuardianApproved GuardianOutcome = "approved"
	GuardianDenied   GuardianOutcome = "denied"
	GuardianWarning  GuardianOutcome = "warning"
	GuardianError    GuardianOutcome = "error"
)

type HubCheckDelegationArgs added in v0.0.296

type HubCheckDelegationArgs struct {
	DelegationIDs       []string `json:"delegation_ids"`
	Wait                *bool    `json:"wait,omitempty"`
	PollIntervalSeconds int      `json:"poll_interval_seconds,omitempty"`
}

type HubCheckDelegationTool added in v0.0.296

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

func NewHubCheckDelegationTool added in v0.0.296

func NewHubCheckDelegationTool() *HubCheckDelegationTool

func NewHubCheckDelegationToolWithClient added in v0.0.296

func NewHubCheckDelegationToolWithClient(client *hubDelegationClient) *HubCheckDelegationTool

func (*HubCheckDelegationTool) Execute added in v0.0.296

func (*HubCheckDelegationTool) Preview added in v0.0.296

func (t *HubCheckDelegationTool) Preview(args json.RawMessage) string

func (*HubCheckDelegationTool) Spec added in v0.0.296

type HubDelegateArgs added in v0.0.296

type HubDelegateArgs struct {
	TargetNode         string `json:"target_node"`
	Prompt             string `json:"prompt"`
	AgentName          string `json:"agent_name,omitempty"`
	TimeoutSeconds     int    `json:"timeout_seconds,omitempty"`
	Model              string `json:"model,omitempty"`
	Cwd                string `json:"cwd,omitempty"`
	Wait               bool   `json:"wait,omitempty"`
	ParentDelegationID string `json:"parent_delegation_id,omitempty"`
}

type HubDelegateTool added in v0.0.296

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

func NewHubDelegateTool added in v0.0.296

func NewHubDelegateTool() *HubDelegateTool

func NewHubDelegateToolWithClient added in v0.0.296

func NewHubDelegateToolWithClient(client *hubDelegationClient) *HubDelegateTool

func (*HubDelegateTool) Execute added in v0.0.296

func (t *HubDelegateTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*HubDelegateTool) Preview added in v0.0.296

func (t *HubDelegateTool) Preview(args json.RawMessage) string

func (*HubDelegateTool) Spec added in v0.0.296

func (t *HubDelegateTool) Spec() llm.ToolSpec

type HubDelegationResult added in v0.0.296

type HubDelegationResult struct {
	DelegationID string `json:"delegation_id"`
	TargetNode   string `json:"target_node,omitempty"`
	Status       string `json:"status"`
	Response     string `json:"response,omitempty"`
	Error        string `json:"error,omitempty"`
	// RefreshError surfaces a hub-side polling problem (e.g. target node
	// unreachable) without failing the whole check.
	RefreshError string `json:"refresh_error,omitempty"`
}

HubDelegationResult is the tool-facing view of one delegation.

type ImageGenerateArgs

type ImageGenerateArgs struct {
	Prompt      string   `json:"prompt"`
	InputImage  string   `json:"input_image,omitempty"`  // Single path for editing/variation (backward compat)
	InputImages []string `json:"input_images,omitempty"` // Multiple paths for multi-image editing
	Size        string   `json:"size,omitempty"`         // Resolution: "1K", "2K", "4K"
	AspectRatio string   `json:"aspect_ratio,omitempty"` // e.g., "16:9", "4:3"
	Quality     string   `json:"quality,omitempty"`      // auto, low, medium, high, xhigh, max
	Background  string   `json:"background,omitempty"`   // auto, opaque, transparent
	OutputPath  string   `json:"output_path,omitempty"`  // Save location
	ShowImage   *bool    `json:"show_image,omitempty"`   // Display via icat (default: true)
}

ImageGenerateArgs are the arguments for image_generate.

type ImageGenerateTool

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

ImageGenerateTool implements the image_generate tool.

func NewImageGenerateTool

func NewImageGenerateTool(approval *ApprovalManager, cfg *config.Config, providerOverride string, recorder ImageRecorder, agent, sessionID string, toolConfigs ...*ToolConfig) *ImageGenerateTool

NewImageGenerateTool creates a new ImageGenerateTool.

func (*ImageGenerateTool) Execute

func (*ImageGenerateTool) Preview

func (t *ImageGenerateTool) Preview(args json.RawMessage) string

func (*ImageGenerateTool) Spec

func (t *ImageGenerateTool) Spec() llm.ToolSpec

type ImageRecorder added in v0.0.94

type ImageRecorder interface {
	RecordImage(ctx context.Context, r *memorystore.ImageRecord) error
}

ImageRecorder is a minimal interface for recording generated images. Using an interface keeps the tools package decoupled from memory internals.

type InitiateHandoverArgs added in v0.0.147

type InitiateHandoverArgs struct {
	Agent string `json:"agent"`
}

InitiateHandoverArgs are the arguments passed to the initiate_handover tool.

type InitiateHandoverFunc added in v0.0.147

type InitiateHandoverFunc func(ctx context.Context, agent string) (confirmed bool, err error)

InitiateHandoverFunc triggers the handover UI for a target agent. It blocks until the user confirms or cancels. Returns true if the user confirmed, false if cancelled.

var (
	HandoverUIFunc InitiateHandoverFunc
)

type InitiateHandoverResult added in v0.0.147

type InitiateHandoverResult struct {
	Status string `json:"status"` // "confirmed", "cancelled", "error"
	Error  string `json:"error,omitempty"`
}

InitiateHandoverResult is the result returned by the tool.

type InitiateHandoverTool added in v0.0.147

type InitiateHandoverTool struct{}

InitiateHandoverTool implements the initiate_handover tool.

func NewInitiateHandoverTool added in v0.0.147

func NewInitiateHandoverTool() *InitiateHandoverTool

NewInitiateHandoverTool creates a new initiate_handover tool.

func (*InitiateHandoverTool) Execute added in v0.0.147

Execute runs the initiate_handover tool.

func (*InitiateHandoverTool) Preview added in v0.0.147

func (t *InitiateHandoverTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*InitiateHandoverTool) Spec added in v0.0.147

func (t *InitiateHandoverTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type LiveSettingsTool added in v0.9.49

type LiveSettingsTool struct{}

LiveSettingsTool exposes a host-bound, session-local voice control.

func (*LiveSettingsTool) Execute added in v0.9.49

func (*LiveSettingsTool) Preview added in v0.9.49

func (*LiveSettingsTool) Spec added in v0.9.49

func (*LiveSettingsTool) Spec() llm.ToolSpec

type LocalToolRegistry

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

LocalToolRegistry manages local tools and their registration with the engine.

func NewLocalToolRegistry

func NewLocalToolRegistry(toolConfig *ToolConfig, appConfig *config.Config, approvalMgr *ApprovalManager) (*LocalToolRegistry, error)

NewLocalToolRegistry creates a new registry from configuration. The approvalMgr parameter is used for interactive permission prompts.

func (*LocalToolRegistry) AddReadDir

func (r *LocalToolRegistry) AddReadDir(dir string) error

AddReadDir adds a directory to the read allowlist at runtime.

func (*LocalToolRegistry) AddShellPattern

func (r *LocalToolRegistry) AddShellPattern(pattern string) error

AddShellPattern adds a shell pattern to the allowlist at runtime.

func (*LocalToolRegistry) AddWriteDir

func (r *LocalToolRegistry) AddWriteDir(dir string) error

AddWriteDir adds a directory to the write allowlist at runtime.

func (*LocalToolRegistry) BaseDir added in v0.0.321

func (r *LocalToolRegistry) BaseDir() string

BaseDir returns the current per-session base directory, if any.

func (*LocalToolRegistry) CollaborativeShellActivityController added in v0.9.25

func (r *LocalToolRegistry) CollaborativeShellActivityController() CollaborativeShellActivityController

func (*LocalToolRegistry) CollaborativeShellMode added in v0.9.25

func (r *LocalToolRegistry) CollaborativeShellMode(ctx context.Context, sessionID string) CollaborativeShellMode

func (*LocalToolRegistry) CollaborativeShellRouting added in v0.9.25

func (r *LocalToolRegistry) CollaborativeShellRouting() (ShellRoutingMode, bool)

func (*LocalToolRegistry) Get

func (r *LocalToolRegistry) Get(specName string) (llm.Tool, bool)

Get returns a tool by spec name.

func (*LocalToolRegistry) GetOutputTool added in v0.0.37

func (r *LocalToolRegistry) GetOutputTool(name string) *SetOutputTool

GetOutputTool returns the output tool by name if it exists and is a SetOutputTool.

func (*LocalToolRegistry) GetSkillTool added in v0.0.37

func (r *LocalToolRegistry) GetSkillTool() *ActivateSkillTool

GetSkillTool returns the activate_skill tool if registered.

func (*LocalToolRegistry) GetSpawnAgentTool added in v0.0.35

func (r *LocalToolRegistry) GetSpawnAgentTool() *SpawnAgentTool

GetSpawnAgentTool returns the spawn_agent tool if enabled.

func (*LocalToolRegistry) GetSpecs

func (r *LocalToolRegistry) GetSpecs() []llm.ToolSpec

GetSpecs returns tool specs for all enabled tools.

func (*LocalToolRegistry) HasVisibleShell added in v0.9.25

func (r *LocalToolRegistry) HasVisibleShell() bool

HasVisibleShell reports whether shell is registered in this registry.

func (*LocalToolRegistry) IsEnabled

func (r *LocalToolRegistry) IsEnabled(specName string) bool

IsEnabled checks if a tool is enabled.

func (*LocalToolRegistry) MediaPublisher added in v0.9.24

func (r *LocalToolRegistry) MediaPublisher() MediaPublisher

MediaPublisher returns the publisher configured for this registry, including registries whose own enabled tool set does not contain show_media.

func (*LocalToolRegistry) Permissions

func (r *LocalToolRegistry) Permissions() *ToolPermissions

Permissions returns the underlying permissions manager.

func (*LocalToolRegistry) RegisterCustomTools added in v0.0.90

func (r *LocalToolRegistry) RegisterCustomTools(defs []agents.CustomToolDef, agentDir string) error

RegisterCustomTools registers script-backed custom tools from agent.yaml into the registry. It validates that custom tool names don't collide with built-in tool names. A startup warning (not an error) is emitted if a script file doesn't exist yet.

func (*LocalToolRegistry) RegisterOutputTool added in v0.0.37

func (r *LocalToolRegistry) RegisterOutputTool(tool *SetOutputTool)

RegisterOutputTool adds an output tool to the local registry.

func (*LocalToolRegistry) RegisterSkillTool added in v0.0.37

func (r *LocalToolRegistry) RegisterSkillTool(skillRegistry *skills.Registry) *ActivateSkillTool

RegisterSkillTool registers the activate_skill tool with the given registry. This must be called after the skills registry is created.

func (*LocalToolRegistry) RegisterSkillTools added in v0.0.90

func (r *LocalToolRegistry) RegisterSkillTools(defs []skills.SkillToolDef, skillDir string) error

RegisterSkillTools registers script-backed tools declared in a skill's frontmatter. skillDir is the skill's SourcePath (absolute directory containing SKILL.md). Tools are resolved relative to skillDir and executed from there. Duplicate registrations (same name) overwrite the previous entry — activating a skill twice is idempotent. Name collisions with built-in tools are rejected.

func (*LocalToolRegistry) RegisterWithEngine

func (r *LocalToolRegistry) RegisterWithEngine(engine *llm.Engine)

RegisterWithEngine registers all enabled tools with the LLM engine.

func (*LocalToolRegistry) RestoreSkillTools added in v0.0.337

func (r *LocalToolRegistry) RestoreSkillTools(names []string, previous map[string]llm.Tool)

RestoreSkillTools removes tools registered for a skill turn and restores any same-named tools that were present before that turn.

func (*LocalToolRegistry) SetBaseDir added in v0.0.321

func (r *LocalToolRegistry) SetBaseDir(dir string) error

SetBaseDir updates the registry's per-session working directory and records a pending primary workspace proposal. Dynamic grants are preserved and shell approval remains independent.

func (*LocalToolRegistry) SetBaseDirWithContext added in v0.0.379

func (r *LocalToolRegistry) SetBaseDirWithContext(ctx context.Context, dir string) error

SetBaseDirWithContext is the context-aware session/worktree rebinding path.

func (*LocalToolRegistry) SetCollaborativeShellController added in v0.9.25

func (r *LocalToolRegistry) SetCollaborativeShellController(controller CollaborativeShellController, mode ShellRoutingMode)

SetCollaborativeShellController configures authoritative shell routing. Web runtimes use controller_required; all other callers retain local_only.

func (*LocalToolRegistry) SetExtensionDirectory added in v0.9.33

func (r *LocalToolRegistry) SetExtensionDirectory(dir, mainConfig string) error

SetExtensionDirectory installs a replaceable, runtime-only file capability. Only the web host calls this for the verified built-in extension-builder. It is not a workspace confirmation, is not persisted/inherited, and never authorizes shell commands or access to the main configuration file.

func (*LocalToolRegistry) SetFileChangeRecorder added in v0.0.286

func (r *LocalToolRegistry) SetFileChangeRecorder(recorder FileChangeRecorder)

SetFileChangeRecorder wires a recorder for file-change tracking into the already-registered file-modifying tools. This mutates registered instances directly (the SetServeMode pattern) so the recorder takes effect regardless of registration order.

func (*LocalToolRegistry) SetImageRecorder added in v0.0.94

func (r *LocalToolRegistry) SetImageRecorder(recorder ImageRecorder, agent, sessionID string)

SetImageRecorder wires an image recorder for image generation tracking into the already-registered image generation tool.

func (*LocalToolRegistry) SetLimits

func (r *LocalToolRegistry) SetLimits(limits OutputLimits)

SetLimits updates the output limits.

func (*LocalToolRegistry) SetMediaPublisher added in v0.9.24

func (r *LocalToolRegistry) SetMediaPublisher(publisher MediaPublisher)

SetMediaPublisher installs durable media publication for show_media. It is intentionally separate from SetServeMode so legacy show_image behavior is unchanged.

func (*LocalToolRegistry) SetPlanStore added in v0.0.339

func (r *LocalToolRegistry) SetPlanStore(store session.Store)

SetPlanStore wires durable latest-snapshot persistence only when update_plan was explicitly configured and registered.

func (*LocalToolRegistry) SetServeMode added in v0.0.111

func (r *LocalToolRegistry) SetServeMode(enabled bool, imageBaseURL string)

SetServeMode marks tools as running in serve (web/telegram) mode. This strips terminal-only params like show_image from tool specs. imageBaseURL is retained for compatibility with older callers; generated images are now reported through ToolOutput.Images and served by the response-stream/session layers.

func (*LocalToolRegistry) SetUIBrowserContext added in v0.9.33

func (r *LocalToolRegistry) SetUIBrowserContext(browser *UIBrowserContext)

SetUIBrowserContext records non-authoritative, bounded presentation metadata. It never grants filesystem or configuration access.

func (*LocalToolRegistry) SetUIExtensionControl added in v0.9.33

func (r *LocalToolRegistry) SetUIExtensionControl(f UIExtensionControl)

func (*LocalToolRegistry) SetViewImageVisionProvider added in v0.0.312

func (r *LocalToolRegistry) SetViewImageVisionProvider(provider llm.Provider, model string)

SetViewImageVisionProvider switches view_image into routed-vision mode. If view_image was not enabled, it is registered so the primary model can call it.

type ManageWorkspaceTool added in v0.0.379

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

ManageWorkspaceTool grants, lists, and revokes session-scoped local file capabilities. Registration is automatic only when a path-capable tool exists.

func NewManageWorkspaceTool added in v0.0.379

func NewManageWorkspaceTool(approval *ApprovalManager, configs ...*ToolConfig) *ManageWorkspaceTool

func (*ManageWorkspaceTool) Execute added in v0.0.379

func (*ManageWorkspaceTool) Preview added in v0.0.379

func (t *ManageWorkspaceTool) Preview(args json.RawMessage) string

func (*ManageWorkspaceTool) Spec added in v0.0.379

func (t *ManageWorkspaceTool) Spec() llm.ToolSpec

type MediaPublisher added in v0.9.24

type MediaPublisher interface {
	PublishMedia(ctx context.Context, sourcePath, mediaType string) (string, error)
}

MediaPublisher imports approved local media into storage owned by a presentation surface. Serve runtimes use this to make media durable and safe to publish without granting the HTTP layer arbitrary filesystem access.

type OutputClaim added in v0.9.0

type OutputClaim struct {
	Path string `json:"path"`
	Kind string `json:"kind"`
}

OutputClaim declares intended shell output before execution.

type OutputLimits

type OutputLimits struct {
	MaxLines       int   // Max lines for read_file (default 2000)
	MaxBytes       int64 // Max bytes per tool output (default 50KB)
	MaxResults     int   // Max results for grep/glob (default 100/200)
	CumulativeSoft int64 // Soft cumulative limit per turn (default 100KB)
	CumulativeHard int64 // Hard cumulative limit per turn (default 200KB)
}

OutputLimits defines limits for tool output.

func DefaultOutputLimits

func DefaultOutputLimits() OutputLimits

DefaultOutputLimits returns the default output limits.

type PlanController added in v0.0.339

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

PlanController owns the lazily loaded current snapshot for configured update_plan tools. State is keyed by session because engines used by command runners may service more than one non-persisted request over their lifetime.

func NewPlanController added in v0.0.339

func NewPlanController(store session.PlanSnapshotStore) *PlanController

NewPlanController creates a lightweight in-memory plan controller.

func (*PlanController) SetPromptGuidance added in v0.0.339

func (c *PlanController) SetPromptGuidance(enabled bool)

SetPromptGuidance enables built-in developer guidance. Engine capability gating ensures this text is never added when update_plan is unavailable.

func (*PlanController) SetStore added in v0.0.339

func (c *PlanController) SetStore(store session.PlanSnapshotStore)

SetStore attaches the optional durable latest-snapshot capability.

type PolicyDecision added in v0.0.317

type PolicyDecision struct {
	Allowed           bool
	RiskLevel         string
	UserAuthorization string
	Rationale         string
	Model             string
	Usage             llm.Usage
}

PolicyDecision is the guardian's allow/deny verdict.

type PolicyReviewRequest added in v0.0.317

type PolicyReviewRequest struct {
	Command         string
	WorkDir         string
	ToolName        string
	Path            string
	Selector        string
	IsWrite         bool
	IsDirectory     bool
	Transcript      []TranscriptEntry
	ApprovalContext string
	ScopeID         string
	ApprovalScope   string
	WorkspaceAccess string
	Reason          string
}

PolicyReviewRequest describes an action requiring guardian review.

type ProjectApprovals added in v0.0.35

type ProjectApprovals struct {
	RepoRoot      string    `yaml:"repo_root"`
	RepoName      string    `yaml:"repo_name"`
	UpdatedAt     time.Time `yaml:"updated_at"`
	ReadApproved  bool      `yaml:"read_approved"`  // Whole repo read access
	WriteApproved bool      `yaml:"write_approved"` // Whole repo write access
	ApprovedPaths []string  `yaml:"approved_paths"` // Individual approved paths (relative to repo)
	ShellPatterns []string  `yaml:"shell_patterns"` // Approved shell command patterns
	// contains filtered or unexported fields
}

ProjectApprovals stores per-project approval decisions. Approvals are persisted to ~/.config/term-llm/projects/<repo-slug>/<context-slug>-<short-hash>.yaml

func LoadProjectApprovals added in v0.0.35

func LoadProjectApprovals(repoRoot string) (*ProjectApprovals, error)

LoadProjectApprovals loads or creates approval data for a git repository. Returns nil if the repo root is empty or invalid.

func (*ProjectApprovals) ApprovePath added in v0.0.35

func (p *ProjectApprovals) ApprovePath(path string) error

ApprovePath adds a specific path to the approved list. Path should be absolute; it will be stored relative to the repo root.

func (*ProjectApprovals) ApproveRead added in v0.0.35

func (p *ProjectApprovals) ApproveRead() error

ApproveRead approves read access for the entire repo.

func (*ProjectApprovals) ApproveShellPattern added in v0.0.35

func (p *ProjectApprovals) ApproveShellPattern(pattern string) error

ApproveShellPattern adds a shell command pattern to the approved list.

func (*ProjectApprovals) ApproveWrite added in v0.0.35

func (p *ProjectApprovals) ApproveWrite() error

ApproveWrite approves write access for the entire repo.

func (*ProjectApprovals) IsPathApproved added in v0.0.35

func (p *ProjectApprovals) IsPathApproved(path string, isWrite bool) bool

IsPathApproved checks if a specific path is approved. Path should be absolute; it will be checked against repo root and approved paths.

func (*ProjectApprovals) IsReadApproved added in v0.0.35

func (p *ProjectApprovals) IsReadApproved() bool

IsReadApproved checks if read access is approved for the entire repo.

func (*ProjectApprovals) IsWriteApproved added in v0.0.35

func (p *ProjectApprovals) IsWriteApproved() bool

IsWriteApproved checks if write access is approved for the entire repo.

func (*ProjectApprovals) Save added in v0.0.35

func (p *ProjectApprovals) Save() error

Save persists the approval data to disk.

type QueueAgentArgs added in v0.0.280

type QueueAgentArgs struct {
	AgentName      string `json:"agent_name"`
	Prompt         string `json:"prompt"`
	Timeout        int    `json:"timeout,omitempty"`
	Model          string `json:"model,omitempty"`
	Cwd            string `json:"cwd,omitempty"`
	NotifyWhenDone bool   `json:"notify_when_done,omitempty"`
}

type QueueAgentOriginContext added in v0.0.281

type QueueAgentOriginContext struct {
	Origin         string
	SessionID      string
	TelegramChatID int64
}

QueueAgentOriginContext carries the trusted runtime origin for queue_agent completion notifications. It is intentionally supplied by runtime code rather than by queue_agent tool arguments, so callers can only opt in to notification, not choose an arbitrary target.

func QueueAgentOriginFromContext added in v0.0.281

func QueueAgentOriginFromContext(ctx context.Context) (QueueAgentOriginContext, bool)

QueueAgentOriginFromContext returns trusted queue_agent notification origin metadata previously stored by ContextWithQueueAgentOrigin.

type QueueAgentResult added in v0.0.280

type QueueAgentResult struct {
	JobID     string `json:"job_id"`
	RunID     string `json:"run_id"`
	AgentName string `json:"agent_name"`
}

type QueueAgentTool added in v0.0.280

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

func NewQueueAgentTool added in v0.0.280

func NewQueueAgentTool(configs ...*ToolConfig) *QueueAgentTool

func NewQueueAgentToolWithClient added in v0.0.280

func NewQueueAgentToolWithClient(client *jobsBackedAgentClient, configs ...*ToolConfig) *QueueAgentTool

func (*QueueAgentTool) Execute added in v0.0.280

func (t *QueueAgentTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*QueueAgentTool) Preview added in v0.0.280

func (t *QueueAgentTool) Preview(args json.RawMessage) string

func (*QueueAgentTool) Spec added in v0.0.280

func (t *QueueAgentTool) Spec() llm.ToolSpec

type QueuedJobResult added in v0.0.280

type QueuedJobResult struct {
	JobID           string   `json:"job_id"`
	RunID           string   `json:"run_id,omitempty"`
	Status          string   `json:"status"`
	ExitReason      string   `json:"exit_reason,omitempty"`
	Truncated       bool     `json:"truncated,omitempty"`
	TurnCount       *int     `json:"turn_count,omitempty"`
	InputTokens     *int     `json:"input_tokens,omitempty"`
	OutputTokens    *int     `json:"output_tokens,omitempty"`
	DurationSeconds *float64 `json:"duration_seconds,omitempty"`
	Response        string   `json:"response,omitempty"`
	Stdout          string   `json:"stdout,omitempty"`
	Error           string   `json:"error,omitempty"`
	ExitCode        *int     `json:"exit_code,omitempty"`
	StartedAt       string   `json:"started_at,omitempty"`
	FinishedAt      string   `json:"finished_at,omitempty"`
}

type ReadFileArgs

type ReadFileArgs struct {
	Path      string `json:"path"`
	StartLine int    `json:"start_line,omitempty"`
	EndLine   int    `json:"end_line,omitempty"`
}

ReadFileArgs are the arguments for read_file.

type ReadFileTool

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

ReadFileTool implements the read_file tool.

func NewReadFileTool

func NewReadFileTool(approval *ApprovalManager, limits OutputLimits, configs ...*ToolConfig) *ReadFileTool

NewReadFileTool creates a new ReadFileTool.

func (*ReadFileTool) Execute

func (t *ReadFileTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ReadFileTool) Preview

func (t *ReadFileTool) Preview(args json.RawMessage) string

func (*ReadFileTool) Spec

func (t *ReadFileTool) Spec() llm.ToolSpec

type RunAgentScriptArgs added in v0.0.74

type RunAgentScriptArgs struct {
	Script         string `json:"script"`
	Args           string `json:"args,omitempty"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty"`
}

RunAgentScriptArgs are the arguments for the run_agent_script tool.

type RunAgentScriptTool added in v0.0.74

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

RunAgentScriptTool executes scripts bundled in the agent's source directory. Scripts are resolved by filename only (no paths), and execution is implicitly trusted — no approval prompts are required.

func NewRunAgentScriptTool added in v0.0.74

func NewRunAgentScriptTool(config *ToolConfig, limits OutputLimits) *RunAgentScriptTool

NewRunAgentScriptTool creates a new RunAgentScriptTool.

func (*RunAgentScriptTool) Execute added in v0.0.74

func (*RunAgentScriptTool) Preview added in v0.0.74

func (t *RunAgentScriptTool) Preview(args json.RawMessage) string

func (*RunAgentScriptTool) Spec added in v0.0.74

func (t *RunAgentScriptTool) Spec() llm.ToolSpec

type RunFileRecorder added in v0.9.0

type RunFileRecorder interface {
	RecordRunStart(ctx context.Context, run filetrack.RunRecord) error
	RecordRunComplete(ctx context.Context, run filetrack.RunRecord) error
}

type SearchSkillsArgs added in v0.0.163

type SearchSkillsArgs struct {
	Query string `json:"query"`
}

SearchSkillsArgs are the arguments for the search_skills tool.

type SearchSkillsTool added in v0.0.163

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

SearchSkillsTool implements the search_skills tool.

func NewSearchSkillsTool added in v0.0.163

func NewSearchSkillsTool(registry *skills.Registry) *SearchSkillsTool

NewSearchSkillsTool creates a new search_skills tool.

func (*SearchSkillsTool) Execute added in v0.0.163

Execute runs the search_skills tool.

func (*SearchSkillsTool) Preview added in v0.0.163

func (t *SearchSkillsTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*SearchSkillsTool) Spec added in v0.0.163

func (t *SearchSkillsTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type SetOutputTool added in v0.0.37

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

SetOutputTool captures structured output from an agent. This tool is dynamically created based on agent configuration and provides a way to force structured output via a tool call, eliminating verbose prose that LLMs often include even with explicit instructions.

func NewSetOutputTool added in v0.0.37

func NewSetOutputTool(name, paramName, description string, schema map[string]interface{}) *SetOutputTool

NewSetOutputTool creates an output tool. A nil schema uses the legacy single-string parameter; a non-nil schema captures the complete argument object as JSON.

func (*SetOutputTool) Captured added in v0.0.236

func (t *SetOutputTool) Captured() bool

Captured returns true once output was captured.

func (*SetOutputTool) Execute added in v0.0.37

func (t *SetOutputTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*SetOutputTool) IsFinishingTool added in v0.0.49

func (t *SetOutputTool) IsFinishingTool() bool

IsFinishingTool returns true because output tools signal agent completion.

func (*SetOutputTool) Name added in v0.0.37

func (t *SetOutputTool) Name() string

Name returns the configured tool name.

func (*SetOutputTool) Preview added in v0.0.37

func (t *SetOutputTool) Preview(args json.RawMessage) string

func (*SetOutputTool) Spec added in v0.0.37

func (t *SetOutputTool) Spec() llm.ToolSpec

func (*SetOutputTool) Value added in v0.0.37

func (t *SetOutputTool) Value() string

Value returns the captured output value.

type SharedShellActivity added in v0.9.25

type SharedShellActivity struct {
	ID                   string
	ShellID              string
	StartOffset          int64
	EndOffset            int64
	BrowserInputRevision uint64
	Excerpt              string
	Truncated            bool
}

SharedShellActivity is a reserved, generation-bound terminal activity range.

type SharedShellArgs added in v0.9.25

type SharedShellArgs struct {
	Command         string
	TimeoutSeconds  int
	ToolCallID      string
	OutputLimit     int64
	ExpectedShellID string
	ActivityFence   *CollaborativeShellActivityFence
}

SharedShellArgs contains internal execution metadata that is never model-visible.

type ShellApprovalCache

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

ShellApprovalCache caches exact shell commands and glob pattern approvals for the session.

func NewShellApprovalCache

func NewShellApprovalCache() *ShellApprovalCache

NewShellApprovalCache creates a new ShellApprovalCache.

func (*ShellApprovalCache) AddCommand added in v0.0.332

func (c *ShellApprovalCache) AddCommand(command, workDir string) error

AddCommand adds an exact command/workdir pair to the session cache. Exact commands are kept separate from glob patterns so shell syntax and glob metacharacters are compared literally.

func (*ShellApprovalCache) AddPattern

func (c *ShellApprovalCache) AddPattern(pattern string) error

AddPattern adds a validated glob pattern to the session cache.

func (*ShellApprovalCache) GetPatterns

func (c *ShellApprovalCache) GetPatterns() []string

GetPatterns returns all session-approved patterns.

func (*ShellApprovalCache) IsCommandApproved added in v0.0.332

func (c *ShellApprovalCache) IsCommandApproved(command, workDir string) bool

IsCommandApproved reports whether command has an exact session approval in workDir.

type ShellArgs

type ShellArgs struct {
	Command        string        `json:"command"`
	WorkingDir     string        `json:"working_dir,omitempty"`
	TimeoutSeconds int           `json:"timeout_seconds,omitempty"`
	Env            EnvMap        `json:"env,omitempty"`
	Description    string        `json:"description,omitempty"`
	AffectedPaths  []string      `json:"affected_paths,omitempty"`
	OutputClaims   []OutputClaim `json:"output_claims,omitempty"`
}

ShellArgs are the arguments for the shell tool.

type ShellResult

type ShellResult struct {
	Stdout          string `json:"stdout"`
	Stderr          string `json:"stderr"`
	ExitCode        int    `json:"exit_code"`
	TimedOut        bool   `json:"timed_out,omitempty"`
	Canceled        bool   `json:"canceled,omitempty"`
	RecoveryFailed  bool   `json:"recovery_failed,omitempty"`
	StdoutTruncated bool   `json:"stdout_truncated,omitempty"`
	StderrTruncated bool   `json:"stderr_truncated,omitempty"`
}

ShellResult contains the result of a shell command.

type ShellRoutingMode added in v0.9.25

type ShellRoutingMode string

ShellRoutingMode determines whether a shell tool may use the local executor.

const (
	ShellRoutingLocalOnly          ShellRoutingMode = "local_only"
	ShellRoutingControllerRequired ShellRoutingMode = "controller_required"
)

type ShellTool

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

ShellTool implements the shell tool.

func NewShellTool

func NewShellTool(approval *ApprovalManager, config *ToolConfig, limits OutputLimits) *ShellTool

NewShellTool creates a new ShellTool.

func (*ShellTool) Execute

func (t *ShellTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ShellTool) PrepareCompactionContext added in v0.9.25

func (t *ShellTool) PrepareCompactionContext(ctx context.Context, sessionID string, result *llm.CompactionResult) error

PrepareCompactionContext implements llm.RequestContextTool.

func (*ShellTool) PrepareRequestContext added in v0.9.25

func (t *ShellTool) PrepareRequestContext(ctx context.Context, sessionID string, messages []llm.Message) ([]llm.Message, error)

PrepareRequestContext implements llm.RequestContextTool.

func (*ShellTool) Preview

func (t *ShellTool) Preview(args json.RawMessage) string

func (*ShellTool) Spec

func (t *ShellTool) Spec() llm.ToolSpec

type ShowImageArgs added in v0.0.33

type ShowImageArgs struct {
	FilePath string `json:"file_path"`
	Prompt   string `json:"prompt,omitempty"` // Steering prompt for image analysis
}

ShowImageArgs are the arguments for show_image.

type ShowImageTool added in v0.0.33

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

ShowImageTool implements the show_image tool for displaying images to users.

func NewShowImageTool added in v0.0.33

func NewShowImageTool(approval *ApprovalManager, configs ...*ToolConfig) *ShowImageTool

NewShowImageTool creates a new ShowImageTool.

func (*ShowImageTool) Execute added in v0.0.33

func (t *ShowImageTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ShowImageTool) Preview added in v0.0.33

func (t *ShowImageTool) Preview(args json.RawMessage) string

func (*ShowImageTool) Spec added in v0.0.33

func (t *ShowImageTool) Spec() llm.ToolSpec

type ShowMediaArgs added in v0.9.24

type ShowMediaArgs struct {
	Path    string `json:"path"`
	Caption string `json:"caption,omitempty"`
}

type ShowMediaTool added in v0.9.24

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

ShowMediaTool presents an existing local image or video to the user.

func NewShowMediaTool added in v0.9.24

func NewShowMediaTool(approval *ApprovalManager, configs ...*ToolConfig) *ShowMediaTool

func (*ShowMediaTool) Execute added in v0.9.24

func (t *ShowMediaTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ShowMediaTool) Preview added in v0.9.24

func (t *ShowMediaTool) Preview(args json.RawMessage) string

func (*ShowMediaTool) SetPublisher added in v0.9.24

func (t *ShowMediaTool) SetPublisher(publisher MediaPublisher)

func (*ShowMediaTool) Spec added in v0.9.24

func (t *ShowMediaTool) Spec() llm.ToolSpec

type SkillActivatedCallback added in v0.0.37

type SkillActivatedCallback func(allowedTools []string, present bool)

SkillActivatedCallback is called after a skill is activated. The presence bit distinguishes an omitted allowlist (inherit all runtime tools) from an explicitly empty allowlist (allow no callable tools).

type SkillToolsRegisteredCallback added in v0.0.90

type SkillToolsRegisteredCallback func(defs []skills.SkillToolDef, skillDir string)

SkillToolsRegisteredCallback is called when a skill with declared tools is activated. It receives the skill's tool definitions and the skill's source directory, allowing the caller to register the tools with the engine dynamically.

type SpawnAgentArgs added in v0.0.35

type SpawnAgentArgs struct {
	AgentName string `json:"agent_name"`        // Required: name of the agent to spawn
	Prompt    string `json:"prompt"`            // Required: task/prompt for the sub-agent
	Timeout   int    `json:"timeout,omitempty"` // Optional: timeout in seconds (default 300)
	Model     string `json:"model,omitempty"`   // Optional: exact provider:model override
}

SpawnAgentArgs are the arguments for the spawn_agent tool.

type SpawnAgentCatalog added in v0.0.375

type SpawnAgentCatalog interface {
	ListSpawnAgentNames() ([]string, error)
	ResolveSpawnAgent(name string) error
}

SpawnAgentCatalog is the optional read-only catalog exposed by runners that can prove which named agent definitions the current runtime can resolve. Capability checks never execute an agent or mutate tool permissions.

type SpawnAgentResult added in v0.0.35

type SpawnAgentResult struct {
	AgentName string `json:"agent_name"`
	Output    string `json:"output,omitempty"`
	Error     string `json:"error,omitempty"`
	Type      string `json:"type,omitempty"` // Error type for structured handling
	Duration  int64  `json:"duration_ms,omitempty"`
	SessionID string `json:"session_id,omitempty"` // Child session ID for inspector integration
}

SpawnAgentResult is the result returned by spawn_agent.

func ParseSpawnAgentResult added in v0.0.394

func ParseSpawnAgentResult(content string) (SpawnAgentResult, error)

ParseSpawnAgentResult decodes the durable JSON contract returned by spawn_agent. Callers should use the matching tool call/result identity to decide whether content belongs to spawn_agent; this parser intentionally does not accept arbitrary plain text as a legacy result.

type SpawnAgentRunOptions added in v0.0.250

type SpawnAgentRunOptions struct {
	ModelOverride string
}

type SpawnAgentRunResult added in v0.0.46

type SpawnAgentRunResult struct {
	Output    string // Text output from the agent
	SessionID string // Child session ID for inspector integration (empty if session tracking disabled)
}

SpawnAgentRunResult contains the output from a sub-agent run.

type SpawnAgentRunner added in v0.0.35

type SpawnAgentRunner interface {
	// RunAgent runs a sub-agent and returns its text output.
	// ctx is used for cancellation, agentName is the agent to load,
	// prompt is the task, and depth is the current nesting level.
	RunAgent(ctx context.Context, agentName string, prompt string, depth int) (SpawnAgentRunResult, error)

	// RunAgentWithCallback runs a sub-agent with an event callback for progress reporting.
	// callID is used to correlate events with the parent's spawn_agent tool call.
	RunAgentWithCallback(ctx context.Context, agentName string, prompt string, depth int,
		callID string, cb SubagentEventCallback) (SpawnAgentRunResult, error)
}

SpawnAgentRunner is the interface for running sub-agents. This is set by the cmd package to avoid circular imports.

type SpawnAgentRunnerWithOptions added in v0.0.250

type SpawnAgentRunnerWithOptions interface {
	RunAgentWithOptions(ctx context.Context, agentName string, prompt string, depth int, opts SpawnAgentRunOptions) (SpawnAgentRunResult, error)
	RunAgentWithCallbackAndOptions(ctx context.Context, agentName string, prompt string, depth int,
		callID string, cb SubagentEventCallback, opts SpawnAgentRunOptions) (SpawnAgentRunResult, error)
}

SpawnAgentRunnerWithOptions can run sub-agents with call-specific overrides.

type SpawnAgentTool added in v0.0.35

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

SpawnAgentTool implements the spawn_agent tool.

func NewSpawnAgentTool added in v0.0.35

func NewSpawnAgentTool(config SpawnConfig, depth int) *SpawnAgentTool

NewSpawnAgentTool creates a new spawn_agent tool.

func (*SpawnAgentTool) CanSpawnAgent added in v0.0.375

func (t *SpawnAgentTool) CanSpawnAgent(name string) error

CanSpawnAgent performs a read-only capability check against the current tool policy and the same runner catalog used by execution.

func (*SpawnAgentTool) Execute added in v0.0.35

func (t *SpawnAgentTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

Execute runs the spawn_agent tool.

func (*SpawnAgentTool) GetEventCallback added in v0.0.42

func (t *SpawnAgentTool) GetEventCallback() SubagentEventCallback

GetEventCallback returns the current event callback (thread-safe).

func (*SpawnAgentTool) PermittedAgentNames added in v0.0.375

func (t *SpawnAgentTool) PermittedAgentNames() ([]string, error)

PermittedAgentNames returns deterministic canonical lookup names that the current tool instance can spawn. Invalid definitions and names denied by the exact whitelist are omitted.

func (*SpawnAgentTool) Preview added in v0.0.35

func (t *SpawnAgentTool) Preview(args json.RawMessage) string

Preview returns a short description of the tool call.

func (*SpawnAgentTool) SetDepth added in v0.0.35

func (t *SpawnAgentTool) SetDepth(depth int)

SetDepth sets the current nesting depth for this tool. Used when creating tools for sub-agents to track depth.

func (*SpawnAgentTool) SetEventCallback added in v0.0.42

func (t *SpawnAgentTool) SetEventCallback(cb SubagentEventCallback)

SetEventCallback sets the callback for receiving subagent progress events. Events are bubbled up to the parent for display during execution.

func (*SpawnAgentTool) SetMediaPublisher added in v0.9.24

func (t *SpawnAgentTool) SetMediaPublisher(publisher MediaPublisher)

SetMediaPublisher forwards serve-owned media publication to runners that support child-registry propagation without expanding the public runner API.

func (*SpawnAgentTool) SetRunner added in v0.0.35

func (t *SpawnAgentTool) SetRunner(runner SpawnAgentRunner)

SetRunner sets the runner for executing sub-agents. This must be called before Execute can succeed.

func (*SpawnAgentTool) Spec added in v0.0.35

func (t *SpawnAgentTool) Spec() llm.ToolSpec

Spec returns the tool specification.

type SpawnConfig added in v0.0.35

type SpawnConfig struct {
	MaxParallel    int               // Max concurrent sub-agents (default 3)
	MaxDepth       int               // Max nesting level (default 2)
	DefaultTimeout int               // Default timeout in seconds (default 300)
	AllowedAgents  []string          // Optional whitelist of allowed agents
	AgentModels    map[string]string // Optional per-spawn model overrides by agent name
}

SpawnConfig configures spawn_agent behavior.

func DefaultSpawnConfig added in v0.0.35

func DefaultSpawnConfig() SpawnConfig

DefaultSpawnConfig returns the default spawn configuration.

type SubagentEvent added in v0.0.42

type SubagentEvent struct {
	Type              SubagentEventType   // "init", "text", "tool_start", "tool_end", "phase", "usage", "done"
	Text              string              // for "text" events
	ToolName          string              // for tool events
	ToolCallID        string              // nested tool invocation ID
	ToolArgs          json.RawMessage     // nested tool arguments
	Guardian          *GuardianEvent      // for guardian events
	ToolInfo          string              // for tool events
	ToolOutput        string              // for "tool_end" events - text content
	Diffs             []llm.DiffData      // for "tool_end" events - structured diffs
	Images            []string            // for "tool_end" events - legacy image paths
	Media             []llm.MediaArtifact // for "tool_end" events - ordered image/video artifacts
	Success           bool                // for "tool_end" events
	Phase             string              // for "phase" events
	InputTokens       int                 // fresh input tokens for "usage" events
	OutputTokens      int                 // output tokens for "usage" events
	CachedInputTokens int                 // cache-read tokens for "usage" events
	CacheWriteTokens  int                 // cache-write tokens for "usage" events
	Provider          string              // resolved provider for init/usage events
	Model             string              // resolved model for init/usage events
	Timestamp         time.Time           // authoritative child lifecycle/event time when available
	Deadline          time.Time           // independently enforced child/run deadline when available
	RunID             string              // queued run identity; never model-provided display text
	JobID             string              // queued job identity
	EventID           int64               // monotonic persisted queued-event identity; zero for synchronous events
	ProgressTruncated bool                // queued event history could not be read completely
}

SubagentEvent represents an event from a running subagent.

type SubagentEventCallback added in v0.0.42

type SubagentEventCallback func(callID string, event SubagentEvent)

SubagentEventCallback is called to bubble up events from a running subagent. callID is the tool call ID of the spawn_agent call.

func SubagentEventCallbackFromContext added in v0.9.46

func SubagentEventCallbackFromContext(ctx context.Context) SubagentEventCallback

SubagentEventCallbackFromContext returns the runtime-owned progress sink.

type SubagentEventType added in v0.0.42

type SubagentEventType string

SubagentEventType identifies the type of subagent event.

const (
	SubagentEventInit      SubagentEventType = "init" // Sent first with provider/model info
	SubagentEventText      SubagentEventType = "text"
	SubagentEventToolStart SubagentEventType = "tool_start"
	SubagentEventToolEnd   SubagentEventType = "tool_end"
	SubagentEventPhase     SubagentEventType = "phase"
	SubagentEventUsage     SubagentEventType = "usage"
	SubagentEventGuardian  SubagentEventType = "guardian"
	SubagentEventDone      SubagentEventType = "done"
)

type ToolConfig

type ToolConfig struct {
	Enabled         []string    `mapstructure:"enabled"`            // Enabled tool spec names
	ReadDirs        []string    `mapstructure:"read_dirs"`          // Directories for read operations
	WriteDirs       []string    `mapstructure:"write_dirs"`         // Directories for write operations
	ShellAllow      []string    `mapstructure:"shell_allow"`        // Shell command patterns
	ScriptCommands  []string    `mapstructure:"script_commands"`    // Exact script commands (auto-approved)
	ShellAutoRun    bool        `mapstructure:"shell_auto_run"`     // Auto-approve matching shell
	ShellAutoRunEnv string      `mapstructure:"shell_auto_run_env"` // Env var required for auto-run
	ShellNonTTYEnv  string      `mapstructure:"shell_non_tty_env"`  // Env var for non-TTY execution
	ImageProvider   string      `mapstructure:"image_provider"`     // Override for image provider
	Spawn           SpawnConfig `mapstructure:"spawn"`              // Spawn agent configuration
	AgentDir        string      `mapstructure:"-"`                  // Agent source directory (set at runtime)
	PlanGuidance    bool        `mapstructure:"-"`                  // Add built-in developer guidance only when update_plan is callable
	// BaseDir, when set, is the per-run/session working directory used to
	// resolve relative tool paths and default process-spawn directories. It is
	// deliberately implemented through explicit path resolution / exec.Cmd.Dir;
	// callers must never use process-wide os.Chdir for session binding.
	BaseDir string `mapstructure:"-"`
	// PrimaryWorkspace is set only for an explicit local/session proposal. BaseDir
	// may still be present solely for relative-path resolution; notably, a serve
	// daemon's process CWD must never become even a proposal by implication.
	PrimaryWorkspace string `mapstructure:"-"`
	// RequireExplicitWorkingDir is enabled only for unbound remote/daemon
	// runtimes. With no BaseDir it rejects relative paths and default process
	// execution instead of falling back to the daemon's ambient CWD.
	RequireExplicitWorkingDir bool `mapstructure:"-"`
	// ShellWorkingDir is retained for compatibility with older callers. Prefer
	// BaseDir for new code. When ShellWorkingDir is empty, shell execution falls
	// back to BaseDir. Legacy callers then use process CWD; unbound daemon
	// runtimes set RequireExplicitWorkingDir to reject that ambient fallback.
	ShellWorkingDir string `mapstructure:"-"`
	// contains filtered or unexported fields
}

ToolConfig holds configuration for the local tool system.

func DefaultToolConfig

func DefaultToolConfig() ToolConfig

DefaultToolConfig returns sensible defaults for tool configuration.

func NewToolConfigFromFields

func NewToolConfigFromFields(enabled, readDirs, writeDirs, shellAllow []string, shellAutoRun bool, shellAutoRunEnv, shellNonTTYEnv, imageProvider string) ToolConfig

NewToolConfigFromFields creates a ToolConfig from individual field values. This allows callers from the config package to create ToolConfigs without circular imports.

func (*ToolConfig) BaseDirValue added in v0.0.321

func (c *ToolConfig) BaseDirValue() string

BaseDirValue returns the current runtime BaseDir without racing writers.

func (*ToolConfig) BuildPermissions

func (c *ToolConfig) BuildPermissions() (*ToolPermissions, error)

BuildPermissions creates a ToolPermissions from this config.

func (*ToolConfig) CanAutoRunShell

func (c *ToolConfig) CanAutoRunShell() bool

CanAutoRunShell checks if shell commands can be auto-run.

func (*ToolConfig) CanRunShellNonTTY

func (c *ToolConfig) CanRunShellNonTTY() bool

CanRunShellNonTTY checks if shell can run in non-TTY mode.

func (*ToolConfig) ClearBaseDir added in v0.0.379

func (c *ToolConfig) ClearBaseDir()

ClearBaseDir removes an explicit runtime/session binding. Legacy callers then fall back to process CWD; runtimes requiring an explicit working directory remain fail-closed.

func (*ToolConfig) EnabledSpecNames

func (c *ToolConfig) EnabledSpecNames() []string

EnabledSpecNames returns the spec names for all enabled tools.

func (*ToolConfig) IsToolEnabled

func (c *ToolConfig) IsToolEnabled(specName string) bool

IsToolEnabled checks if a tool is enabled.

func (ToolConfig) Merge

func (c ToolConfig) Merge(other ToolConfig) ToolConfig

Merge combines this config with another, with other taking precedence for non-empty values.

func (*ToolConfig) PrimaryWorkspaceValue added in v0.0.379

func (c *ToolConfig) PrimaryWorkspaceValue() string

PrimaryWorkspaceValue returns the explicitly proposed primary workspace.

func (*ToolConfig) RequiresExplicitWorkingDir added in v0.0.379

func (c *ToolConfig) RequiresExplicitWorkingDir() bool

RequiresExplicitWorkingDir reports whether ambient process-CWD fallback is forbidden for this runtime.

func (*ToolConfig) ResolveDir added in v0.0.321

func (c *ToolConfig) ResolveDir(dir string) string

ResolveDir resolves a user-supplied directory against WorkingDir when it is relative. Empty input resolves to WorkingDir.

func (*ToolConfig) ResolvePath added in v0.0.321

func (c *ToolConfig) ResolvePath(path string) string

ResolvePath resolves a user-supplied file or directory path against WorkingDir when it is relative. It does not evaluate symlinks; callers that need permission-safe canonical paths should pass the result to resolveToolPath.

func (*ToolConfig) ShellDir added in v0.0.321

func (c *ToolConfig) ShellDir() string

ShellDir returns the effective shell cwd. It preserves the historical ShellWorkingDir override while allowing BaseDir to be the unified default.

func (*ToolConfig) UpdateBaseDir added in v0.0.321

func (c *ToolConfig) UpdateBaseDir(dir string)

UpdateBaseDir updates only the runtime working directory fields guarded by the config lock. ApprovalManager separately owns the proposed/confirmed primary workspace state and additional capabilities.

func (*ToolConfig) Validate

func (c *ToolConfig) Validate() []error

Validate checks the configuration for errors.

func (*ToolConfig) WorkingDir added in v0.0.321

func (c *ToolConfig) WorkingDir() string

WorkingDir returns the effective per-run working directory. BaseDir is the preferred source. ShellWorkingDir is a legacy shell-only override retained for compatibility. If neither is set, legacy callers use process CWD; runtimes requiring an explicit directory return empty instead.

type ToolDisplay

type ToolDisplay struct {
	Title    string `json:"title,omitempty"`
	Preview  string `json:"preview,omitempty"`
	FilePath string `json:"file_path,omitempty"`
}

ToolDisplay contains optional display metadata for UI.

type ToolError

type ToolError struct {
	Type    ToolErrorType `json:"type"`
	Message string        `json:"message"`
}

ToolError provides structured error information for retry logic.

func NewToolError

func NewToolError(errType ToolErrorType, message string) *ToolError

NewToolError creates a new ToolError.

func NewToolErrorf

func NewToolErrorf(errType ToolErrorType, format string, args ...interface{}) *ToolError

NewToolErrorf creates a new ToolError with formatted message.

func (*ToolError) Error

func (e *ToolError) Error() string

type ToolErrorType

type ToolErrorType string

ToolErrorType provides structured errors for agent retry logic.

const (
	ErrFileNotFound       ToolErrorType = "FILE_NOT_FOUND"
	ErrInvalidParams      ToolErrorType = "INVALID_PARAMS"
	ErrPathNotInWorkspace ToolErrorType = "PATH_NOT_IN_WORKSPACE"
	ErrExecutionFailed    ToolErrorType = "EXECUTION_FAILED"
	ErrPermissionDenied   ToolErrorType = "PERMISSION_DENIED"
	ErrBinaryFile         ToolErrorType = "BINARY_FILE"
	ErrFileTooLarge       ToolErrorType = "FILE_TOO_LARGE"
	ErrImageGenFailed     ToolErrorType = "IMAGE_GEN_FAILED"
	ErrUnsupportedFormat  ToolErrorType = "UNSUPPORTED_FORMAT"
	ErrTimeout            ToolErrorType = "TIMEOUT"
	ErrSymlinkEscape      ToolErrorType = "SYMLINK_ESCAPE"
)

type ToolKind

type ToolKind string

ToolKind categorizes tools for permission grouping.

const (
	KindRead         ToolKind = "read"
	KindEdit         ToolKind = "edit"
	KindSearch       ToolKind = "search"
	KindExecute      ToolKind = "execute"
	KindImage        ToolKind = "image"
	KindInteractive  ToolKind = "interactive"
	KindAgent        ToolKind = "agent"         // For spawn_agent tool
	KindSkill        ToolKind = "skill"         // For activate_skill tool
	KindSessionState ToolKind = "session_state" // For session-scoped state such as update_plan
)

func GetToolKind

func GetToolKind(specName string) ToolKind

GetToolKind returns the kind for a tool spec name.

type ToolManager

type ToolManager struct {
	Registry    *LocalToolRegistry
	ApprovalMgr *ApprovalManager
}

ToolManager provides a high-level interface for tool management in commands.

func NewToolManager

func NewToolManager(toolConfig *ToolConfig, appConfig *config.Config) (*ToolManager, error)

NewToolManager creates a new tool manager from config.

func (*ToolManager) BaseDir added in v0.0.321

func (m *ToolManager) BaseDir() string

BaseDir returns the current per-session base directory, if any.

func (*ToolManager) ClearPrimaryWorkspace added in v0.0.379

func (m *ToolManager) ClearPrimaryWorkspace(ctx context.Context) error

ClearPrimaryWorkspace removes an explicit session binding and its pending or confirmed primary capability while preserving dynamic grants.

func (*ToolManager) ConfigureWorkspacePersistence added in v0.0.379

func (m *ToolManager) ConfigureWorkspacePersistence(ctx context.Context, store session.Store, sessionID string) error

ConfigureWorkspacePersistence installs optional session grant persistence and rehydrates additional grants before tool execution.

func (*ToolManager) GetSpawnAgentTool added in v0.0.35

func (m *ToolManager) GetSpawnAgentTool() *SpawnAgentTool

GetSpawnAgentTool returns the spawn_agent tool if enabled, for runner configuration.

func (*ToolManager) GetSpecs

func (m *ToolManager) GetSpecs() []llm.ToolSpec

GetSpecs returns all model-facing tool specs for the effective approval mode.

func (*ToolManager) IsReadPathApproved added in v0.0.374

func (m *ToolManager) IsReadPathApproved(path string) bool

IsReadPathApproved reports whether path may be read without prompting. It is intentionally read-only: it neither invokes approval UI nor adds permissions.

func (*ToolManager) SetBaseDir added in v0.0.321

func (m *ToolManager) SetBaseDir(dir string) error

SetBaseDir updates the per-manager base directory used by all local tools.

func (*ToolManager) SetBaseDirWithContext added in v0.0.379

func (m *ToolManager) SetBaseDirWithContext(ctx context.Context, dir string) error

SetBaseDirWithContext is the context-aware session/worktree rebinding path.

func (*ToolManager) SetupEngine

func (m *ToolManager) SetupEngine(engine *llm.Engine)

SetupEngine registers tools with the engine.

type ToolMetadata

type ToolMetadata struct {
	ExecutionTimeMs   int64 `json:"execution_time_ms"`
	PermissionCheckMs int64 `json:"permission_check_ms,omitempty"`
	OutputBytes       int64 `json:"output_bytes"`
	Truncated         bool  `json:"truncated,omitempty"`
}

ToolMetadata contains execution metrics.

type ToolPayload

type ToolPayload struct {
	Output      string         `json:"output"`
	Display     *ToolDisplay   `json:"display,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	Attachments []Attachment   `json:"attachments,omitempty"`
	Error       *ToolError     `json:"error,omitempty"`
}

ToolPayload is an optional JSON payload for tools that need display/metadata. This is encoded in ToolResult.Content when UI metadata is required.

func (*ToolPayload) ToJSON

func (p *ToolPayload) ToJSON() string

ToJSON encodes the payload as JSON for use in ToolResult.Content.

type ToolPermissions

type ToolPermissions struct {
	ReadDirs       []string // Directories for read/grep/glob/view
	WriteDirs      []string // Directories for write/edit
	ShellAllow     []string // Shell command patterns (glob syntax)
	ScriptCommands []string // Exact script commands (auto-approved)
	// contains filtered or unexported fields
}

ToolPermissions manages allowlists for tool access.

func NewToolPermissions

func NewToolPermissions() *ToolPermissions

NewToolPermissions creates a new ToolPermissions instance.

func (*ToolPermissions) AddReadDir

func (p *ToolPermissions) AddReadDir(dir string) error

AddReadDir adds a directory to the read allowlist.

func (*ToolPermissions) AddScriptCommand added in v0.0.33

func (p *ToolPermissions) AddScriptCommand(command string)

AddScriptCommand adds an exact script command to the allowlist.

func (*ToolPermissions) AddShellPattern

func (p *ToolPermissions) AddShellPattern(pattern string) error

AddShellPattern adds a shell command pattern to the allowlist.

func (*ToolPermissions) AddWriteDir

func (p *ToolPermissions) AddWriteDir(dir string) error

AddWriteDir adds a directory to the write allowlist.

func (*ToolPermissions) CompileShellPatterns

func (p *ToolPermissions) CompileShellPatterns() error

CompileShellPatterns validates all shell patterns. The method name is kept for compatibility with callers that populated ShellAllow directly.

func (*ToolPermissions) IsPathAllowedForRead

func (p *ToolPermissions) IsPathAllowedForRead(path string) (bool, error)

IsPathAllowedForRead checks if a path is allowed for read operations.

func (*ToolPermissions) IsPathAllowedForWrite

func (p *ToolPermissions) IsPathAllowedForWrite(path string) (bool, error)

IsPathAllowedForWrite checks if a path is allowed for write operations.

func (*ToolPermissions) Snapshot added in v0.0.321

func (p *ToolPermissions) Snapshot() (readDirs, writeDirs, shellAllow []string)

type TranscriptEntry added in v0.0.317

type TranscriptEntry struct {
	Role string
	Text string
}

TranscriptEntry is compact conversation evidence for policy review.

type UIBrowserContext added in v0.9.33

type UIBrowserContext struct {
	AssetVersion string   `json:"asset_version"`
	Loaded       []string `json:"loaded"`
	Generation   string   `json:"generation"`
	SafeMode     bool     `json:"safe_mode"`
	Width        int      `json:"width"`
	Height       int      `json:"height"`
}

type UIExtensionControl added in v0.9.33

type UIExtensionControl func(context.Context, string) (any, error)

UIExtensionControl is bound only by a web runtime. It exposes extension-only status/reload/activation, not provider configuration, credentials, or arbitrary HTTP URLs.

type UIExtensionsTool added in v0.9.33

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

func (*UIExtensionsTool) Execute added in v0.9.33

func (*UIExtensionsTool) Preview added in v0.9.33

func (t *UIExtensionsTool) Preview(args json.RawMessage) string

func (*UIExtensionsTool) Spec added in v0.9.33

func (t *UIExtensionsTool) Spec() llm.ToolSpec

type UIGetSourceTool added in v0.9.33

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

func (*UIGetSourceTool) Execute added in v0.9.33

func (t *UIGetSourceTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*UIGetSourceTool) Preview added in v0.9.33

func (t *UIGetSourceTool) Preview(args json.RawMessage) string

func (*UIGetSourceTool) Spec added in v0.9.33

func (t *UIGetSourceTool) Spec() llm.ToolSpec

type UnifiedDiffArgs added in v0.0.55

type UnifiedDiffArgs struct {
	Diff string `json:"diff"`
}

UnifiedDiffArgs are the arguments for unified_diff.

type UnifiedDiffTool added in v0.0.55

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

UnifiedDiffTool implements the unified_diff tool.

func NewUnifiedDiffTool added in v0.0.55

func NewUnifiedDiffTool(approval *ApprovalManager, configs ...*ToolConfig) *UnifiedDiffTool

NewUnifiedDiffTool creates a new UnifiedDiffTool.

func (*UnifiedDiffTool) Execute added in v0.0.55

func (t *UnifiedDiffTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*UnifiedDiffTool) Preview added in v0.0.55

func (t *UnifiedDiffTool) Preview(args json.RawMessage) string

func (*UnifiedDiffTool) Spec added in v0.0.55

func (t *UnifiedDiffTool) Spec() llm.ToolSpec

type UpdateGoalArgs added in v0.0.321

type UpdateGoalArgs struct {
	Status   string `json:"status"`
	Reason   string `json:"reason,omitempty"`
	Evidence string `json:"evidence,omitempty"`
	Message  string `json:"message,omitempty"`
}

func ParseUpdateGoalArgs added in v0.0.321

func ParseUpdateGoalArgs(args json.RawMessage) (UpdateGoalArgs, error)

ParseUpdateGoalArgs validates update_goal arguments for both tool execution and runner commit tracking.

type UpdatePlanTool added in v0.0.339

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

UpdatePlanTool atomically replaces a session's current execution-plan snapshot.

func NewUpdatePlanTool added in v0.0.339

func NewUpdatePlanTool(controller *PlanController) *UpdatePlanTool

NewUpdatePlanTool constructs update_plan with an injected controller.

func (*UpdatePlanTool) Execute added in v0.0.339

func (t *UpdatePlanTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*UpdatePlanTool) PrepareCompactionContext added in v0.0.339

func (t *UpdatePlanTool) PrepareCompactionContext(ctx context.Context, sessionID string, result *llm.CompactionResult) error

PrepareCompactionContext implements llm.RequestContextTool.

func (*UpdatePlanTool) PrepareRequestContext added in v0.0.339

func (t *UpdatePlanTool) PrepareRequestContext(ctx context.Context, sessionID string, messages []llm.Message) ([]llm.Message, error)

PrepareRequestContext implements llm.RequestContextTool.

func (*UpdatePlanTool) Preview added in v0.0.339

func (t *UpdatePlanTool) Preview(args json.RawMessage) string

func (*UpdatePlanTool) ResetSessionState added in v0.0.373

func (t *UpdatePlanTool) ResetSessionState(sessionID string)

func (*UpdatePlanTool) Spec added in v0.0.339

func (t *UpdatePlanTool) Spec() llm.ToolSpec

type ViewImageArgs

type ViewImageArgs struct {
	FilePath string  `json:"file_path"`
	Question string  `json:"question,omitempty"` // Optional focused question for routed-vision mode
	Prompt   string  `json:"prompt,omitempty"`   // Alias for question
	Detail   string  `json:"detail,omitempty"`   // "low", "high", or "auto"
	Region   string  `json:"region,omitempty"`   // "full", "left_half", "right_half", "top_half", "bottom_half"
	Scale    float64 `json:"scale,omitempty"`    // 1-4x upscale after region
}

ViewImageArgs are the arguments for view_image.

type ViewImageTool

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

ViewImageTool implements the view_image tool.

func NewViewImageTool

func NewViewImageTool(approval *ApprovalManager, configs ...*ToolConfig) *ViewImageTool

NewViewImageTool creates a new ViewImageTool.

func NewViewImageToolWithVision added in v0.0.312

func NewViewImageToolWithVision(approval *ApprovalManager, provider llm.Provider, model string, configs ...*ToolConfig) *ViewImageTool

NewViewImageToolWithVision creates a view_image tool that analyzes images by calling a separate vision-capable LLM and returning text only.

func (*ViewImageTool) Execute

func (t *ViewImageTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*ViewImageTool) Preview

func (t *ViewImageTool) Preview(args json.RawMessage) string

func (*ViewImageTool) Spec

func (t *ViewImageTool) Spec() llm.ToolSpec

type WaitForJobsArgs added in v0.0.280

type WaitForJobsArgs struct {
	PollIntervalSeconds int      `json:"poll_interval_seconds,omitempty"`
	JobIDs              []string `json:"job_ids,omitempty"`
	RunIDs              []string `json:"run_ids,omitempty"`
}

type WaitForJobsTool added in v0.0.280

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

func NewWaitForJobsTool added in v0.0.280

func NewWaitForJobsTool() *WaitForJobsTool

func NewWaitForJobsToolWithClient added in v0.0.280

func NewWaitForJobsToolWithClient(client *jobsBackedAgentClient) *WaitForJobsTool

func (*WaitForJobsTool) Execute added in v0.0.280

func (t *WaitForJobsTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*WaitForJobsTool) Preview added in v0.0.280

func (t *WaitForJobsTool) Preview(args json.RawMessage) string

func (*WaitForJobsTool) Spec added in v0.0.280

func (t *WaitForJobsTool) Spec() llm.ToolSpec

type WorkspaceApprovalResult added in v0.0.379

type WorkspaceApprovalResult struct {
	Approved  bool
	Remember  bool
	Cancelled bool
}

WorkspaceApprovalResult is the direct human decision for a proposed primary workspace. It is intentionally separate from per-file/project approval choices because neither Guardian nor the model may establish this authority.

func RunWorkspaceApprovalUI added in v0.0.379

func RunWorkspaceApprovalUI(workspace string) (WorkspaceApprovalResult, error)

RunWorkspaceApprovalUI displays the dedicated proposed-primary confirmation.

type WorkspaceCapability added in v0.0.379

type WorkspaceCapability struct {
	ID         string
	Path       string
	Access     session.WorkspaceAccess
	Status     string
	Provenance string
	Rationale  string
	Primary    bool
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

WorkspaceCapability is the combined list view of the proposed/confirmed primary workspace and additional session-scoped grants.

type WorkspaceGrantResult added in v0.0.379

type WorkspaceGrantResult struct {
	Capability WorkspaceCapability
	Changed    bool
	Persisted  bool
}

WorkspaceGrantResult reports whether a grant was newly installed and whether it was durable. Stores without WorkspaceGrantStore intentionally remain runtime-only.

type WriteFileArgs

type WriteFileArgs struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

WriteFileArgs are the arguments for write_file.

type WriteFileTool

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

WriteFileTool implements the write_file tool.

func NewWriteFileTool

func NewWriteFileTool(approval *ApprovalManager, configs ...*ToolConfig) *WriteFileTool

NewWriteFileTool creates a new WriteFileTool.

func (*WriteFileTool) Execute

func (t *WriteFileTool) Execute(ctx context.Context, args json.RawMessage) (llm.ToolOutput, error)

func (*WriteFileTool) Preview

func (t *WriteFileTool) Preview(args json.RawMessage) string

func (*WriteFileTool) Spec

func (t *WriteFileTool) Spec() llm.ToolSpec

Jump to

Keyboard shortcuts

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