tools

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 87 Imported by: 0

Documentation

Overview

Package tools provides a framework for defining and executing tools/functions.

Index

Constants

View Source
const (
	BrowserLaunchModeDefault BrowserLaunchMode = ""
	BrowserLaunchModeVisible BrowserLaunchMode = "visible"

	ToolRouteKindUnknown  ToolRouteKind = ""
	ToolRouteKindChat     ToolRouteKind = "chat"
	ToolRouteKindAgent    ToolRouteKind = "agent"
	ToolRouteKindWorkflow ToolRouteKind = "workflow"
)
View Source
const (
	ToolLoopReasonUnknown           = "unknown"
	ToolLoopReasonIdenticalRepeat   = "identical_repeat"
	ToolLoopReasonPollingNoProgress = "polling_no_progress"
	ToolLoopReasonErrorRepeat       = "error_repeat"
	ToolLoopReasonPingPong          = "ab_ping_pong"
)
View Source
const (
	DeepResearchActionRun    = "run"
	DeepResearchActionStatus = "status"
)

Variables

View Source
var DefaultSafeBins = []string{
	"jq", "grep", "cut", "sort", "uniq", "head", "tail", "tr", "wc",
	"cat", "ls", "pwd", "echo", "date", "which", "env", "whoami",
	"dirname", "basename", "realpath", "readlink", "stat", "file",
	"true", "false", "test", "printf", "seq", "tee", "xargs",
}

DefaultSafeBins is the set of binaries that are always allowed in allowlist mode.

View Source
var (
	ErrToolNotFound = errors.New("tool not found")
)

Common errors

Functions

func A11yChatSendVerificationDisposition

func A11yChatSendVerificationDisposition(profileID string, status string) string

func AddAllowlistEntry

func AddAllowlistEntry(cfg *AllowlistConfig, pattern string)

AddAllowlistEntry adds a new pattern to the allowlist if not already present.

func AttachDocumentReadServiceToWebTools

func AttachDocumentReadServiceToWebTools(registry *Registry, service DocumentReadService)

func AttachPDFServiceToWebTools

func AttachPDFServiceToWebTools(registry *Registry, service PDFService)

func AttachSTTServiceToWebTools

func AttachSTTServiceToWebTools(registry *Registry, service stt.Service)

func BrowserActionPerformedMessage

func BrowserActionPerformedMessage(lang i18n.Language, actType string, ref int) string

func BrowserLargeDOMNoteMessage

func BrowserLargeDOMNoteMessage(lang i18n.Language, count int) string

func BrowserLegacyPageScrollDelta

func BrowserLegacyPageScrollDelta(action string, actType string) (string, int, int, bool)

BrowserLegacyPageScrollDelta maps compatibility page-scroll directions to a relative browser scroll delta.

func BrowserOpenTabsMessage

func BrowserOpenTabsMessage(lang i18n.Language, count int) string

func BrowserPageMessage

func BrowserPageMessage(lang i18n.Language, title, url, tree string, count int) string

func BrowserPageScrolledMessage

func BrowserPageScrolledMessage(lang i18n.Language, direction string) string

func BrowserPageWithScreenshotInteractiveMessage

func BrowserPageWithScreenshotInteractiveMessage(lang i18n.Language, title, url, tree string, count int) string

func BrowserReadableContentMessage

func BrowserReadableContentMessage(lang i18n.Language, title, url, content string) string

func BrowserReadableContentWithTreeMessage

func BrowserReadableContentWithTreeMessage(
	lang i18n.Language,
	title, url, content, strategy, tree string,
) string

func BrowserRecipesAvailableMessage

func BrowserRecipesAvailableMessage(lang i18n.Language, count int) string

func BrowserScreenshotInteractiveUnavailableMessage

func BrowserScreenshotInteractiveUnavailableMessage(lang i18n.Language) string

func BrowserScreenshotMessage

func BrowserScreenshotMessage(lang i18n.Language, url, targetID string) string

func BrowserTabClosedMessage

func BrowserTabClosedMessage(lang i18n.Language, targetID string) string

func BuildCompactWebQueryPayloadForLLM

func BuildCompactWebQueryPayloadForLLM(ctx context.Context, raw interface{}, auditContent string, opts WebQueryLLMCompactionOptions) (map[string]interface{}, bool)

func BuildSafeBinsSet

func BuildSafeBinsSet(bins []string) map[string]struct{}

BuildSafeBinsSet creates a set from a slice of safe bin names.

func CanonicalizeBrowserAction

func CanonicalizeBrowserAction(action string, actType string) (string, string)

CanonicalizeBrowserAction normalizes legacy top-level browser act aliases. Older callers may send action=scroll/click/type/etc. instead of action=act + act_type=<verb>. This keeps those calls working.

func CanonicalizeToolArgumentsJSON

func CanonicalizeToolArgumentsJSON(raw string) (string, bool)

CanonicalizeToolArgumentsJSON normalizes tool-call arguments into a JSON object string when they are empty or recoverably object-shaped.

func CanonicalizeUIReviewAction

func CanonicalizeUIReviewAction(action string, url string, image string) (string, error)

CanonicalizeUIReviewAction normalizes legacy or natural-language UI review actions to the canonical runtime actions.

func CoerceBrowserRef

func CoerceBrowserRef(v interface{}) (int, bool)

CoerceBrowserRef accepts either a raw integer ref or an accessibility-tree ref like "@12".

func EmitArtifact

func EmitArtifact(ctx context.Context, artifact ToolArtifact) error

func EmitCard

func EmitCard(ctx context.Context, card map[string]interface{})

EmitCard sends a typeless card to the client if an emitter is set. Safe to call even when no emitter is present (no-op). Automatically adds "typeless": true to the card.

func EmitEvent

func EmitEvent(ctx context.Context, event ToolEvent) error

func GetAgentID

func GetAgentID(ctx context.Context) string

GetAgentID extracts the agent identifier from the context.

func GetAutoConfirm

func GetAutoConfirm(ctx context.Context) bool

GetAutoConfirm reports whether the current context should skip confirmations.

func GetChannel

func GetChannel(ctx context.Context) string

GetChannel extracts the channel name from the context.

func GetDevice

func GetDevice(ctx context.Context) string

GetDevice extracts the device type from the context.

func GetFSScope

func GetFSScope(ctx context.Context) (roots []string, aliases map[string]string)

GetFSScope returns additional filesystem roots and aliases from the context.

func GetLang

func GetLang(ctx context.Context) string

GetLang extracts the language from the context. Returns "en-US" if not set.

func GetModel

func GetModel(ctx context.Context) string

GetModel extracts the model from the context.

func GetProvider

func GetProvider(ctx context.Context) string

GetProvider extracts the provider name from the context.

func GetProviderID

func GetProviderID(ctx context.Context) string

GetProviderID extracts the provider ID from the context.

func GetRunArtifactRoot

func GetRunArtifactRoot(ctx context.Context) string

func GetRunID

func GetRunID(ctx context.Context) string

GetRunID extracts the harness run ID from the context.

func GetRunStep

func GetRunStep(ctx context.Context) int

GetRunStep extracts the harness step index from the context.

func GetSessionID

func GetSessionID(ctx context.Context) string

GetSessionID extracts the conversation/session ID from the context.

func GetShellConfig

func GetShellConfig() (shell string, args []string)

GetShellConfig returns the platform-appropriate shell and arguments for executing a command string. On Unix it prefers $SHELL (falling back to bash → sh).

func GetThemeByMood

func GetThemeByMood(mood string) []officeTheme

GetThemeByMood returns themes matching a specific mood for content-based selection.

func GetThemePreview

func GetThemePreview(name string) (officeThemePreview, error)

GetThemePreview returns a renderable preview payload for downstream UI and QA flows.

func GetThemeUseCases

func GetThemeUseCases(name string) []string

GetThemeUseCases returns the use case list for a theme.

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID extracts the user ID from the context.

func GuardOutboundHost

func GuardOutboundHost(ctx context.Context, host string, allowPrivate bool) error

GuardOutboundHost rejects loopback, private, and otherwise internal hostnames.

func GuardOutboundURL

func GuardOutboundURL(ctx context.Context, rawURL string, allowPrivate bool) error

GuardOutboundURL rejects loopback, private, and otherwise internal HTTP targets.

func IsA11yActionHighRisk

func IsA11yActionHighRisk(action string, actType string) bool

func IsBrowserActionHighRisk

func IsBrowserActionHighRisk(action, actType, recipe string) bool

IsBrowserActionHighRisk returns true when browser action should require confirmation.

func IsSafeBin

func IsSafeBin(execName string, safeBins map[string]struct{}) bool

IsSafeBin checks if an executable name is in the safe bins set.

func KillProcessTree

func KillProcessTree(pid int)

KillProcessTree kills a process and all its children on Unix.

func ListThemes

func ListThemes() []string

ListThemes returns all available theme names.

func LooksLikeBrowserURL

func LooksLikeBrowserURL(raw string) bool

LooksLikeBrowserURL reports whether the provided string is probably a URL acceptable to browser navigation and screenshot entry points.

func LooksLikeStructuredWorkspaceArtifactTask

func LooksLikeStructuredWorkspaceArtifactTask(query string) bool

LooksLikeStructuredWorkspaceArtifactTask reports whether the user is asking the model to read one or more concrete local source files and produce a structured saved artifact such as extracted answers, a summary, or a table.

func LooksLikeWorkspaceFileTask

func LooksLikeWorkspaceFileTask(query string) bool

LooksLikeWorkspaceFileTask reports whether the user is asking the model to work from files already provided in the workspace.

func NewSessionID

func NewSessionID() string

NewSessionID generates a unique session ID.

func NormalizeBrowserActionAlias

func NormalizeBrowserActionAlias(action string) (string, bool)

NormalizeBrowserActionAlias maps browser CLI and skill aliases to the canonical action family used by browser tooling.

func NormalizeBrowserSiteOrigin

func NormalizeBrowserSiteOrigin(raw string) string

NormalizeBrowserSiteOrigin converts a browser URL into a stable origin string (scheme + host + optional non-default port). Returns empty string when the input does not represent an http(s) origin.

func NormalizeCommand

func NormalizeCommand(cmd string) string

NormalizeCommand performs basic normalization on a command string: collapse whitespace, trim, lowercase for analysis (original preserved for execution).

func NormalizeToolProgressSummary

func NormalizeToolProgressSummary(content string) string

NormalizeToolProgressSummary extracts a compact, stable summary for loop detection.

func NormalizeToolSchemaForLLM

func NormalizeToolSchemaForLLM(provider, providerID, model string, schema map[string]interface{}) map[string]interface{}

NormalizeToolSchemaForLLM normalizes a tool schema before exposing it to providers.

func NormalizeUIReviewCompatArgs

func NormalizeUIReviewCompatArgs(args map[string]interface{})

NormalizeUIReviewCompatArgs lifts common UI-review aliases onto canonical keys.

func RecordAllowlistUse

func RecordAllowlistUse(cfg *AllowlistConfig, entry *AllowlistEntry, command, resolvedPath string)

RecordAllowlistUse updates the last-used metadata for a matched entry.

func RegisterAgentTools

func RegisterAgentTools(registry *Registry, cfg *config.Config)

RegisterAgentTools registers native agent-management tools.

func RegisterApprovalAwareFileTools

func RegisterApprovalAwareFileTools(registry *Registry, allowedPaths []string, maxFileSize int64, approvals *ApprovalManager, dirStore *DirAllowlistStore)

RegisterApprovalAwareFileTools re-registers filesystem tools with the same scope as the default builtins plus exec-style approval handling for out-of-scope absolute paths.

func RegisterApprovalAwareFileToolsWithRuntimeConfig

func RegisterApprovalAwareFileToolsWithRuntimeConfig(registry *Registry, allowedPaths []string, maxFileSize int64, approvals *ApprovalManager, dirStore *DirAllowlistStore, runtimeCfg BuiltinRuntimeConfig)

func RegisterAskTool

func RegisterAskTool(registry *Registry, mgr *QuestionManager)

RegisterAskTool registers the ask tool.

func RegisterBrowserTool

func RegisterBrowserTool(registry *Registry, backend BrowserBackend)

RegisterBrowserTool registers the browser tool with the registry.

func RegisterBuiltinTools

func RegisterBuiltinTools(registry *Registry)

RegisterBuiltinTools registers built-in core tools with default configuration.

func RegisterBuiltinToolsWithConfig

func RegisterBuiltinToolsWithConfig(registry *Registry, webSearchConfig WebSearchConfig, webFetchConfig WebFetchConfig, allowedPaths []string, maxFileSize int64)

RegisterBuiltinToolsWithConfig registers built-in core tools with custom configuration.

func RegisterBuiltinToolsWithRuntimeConfig

func RegisterBuiltinToolsWithRuntimeConfig(registry *Registry, webSearchConfig WebSearchConfig, webFetchConfig WebFetchConfig, allowedPaths []string, maxFileSize int64, runtimeCfg BuiltinRuntimeConfig)

RegisterBuiltinToolsWithRuntimeConfig registers built-in tools with runtime resource configuration.

func RegisterCanvasTools

func RegisterCanvasTools(registry *Registry, manager *a2ui.Manager)

RegisterCanvasTools registers the native canvas tool.

func RegisterConvertTool

func RegisterConvertTool(registry *Registry, service *convertpkg.Service, approvals *ApprovalManager, dirStore *DirAllowlistStore, allowedPaths []string)

func RegisterCronTool

func RegisterCronTool(registry *Registry, service CronService)

RegisterCronTool registers the native cron tool.

func RegisterExecTools

func RegisterExecTools(registry *Registry, config ExecConfig, approvals *ApprovalManager, broker *sse.Broker, dirStore *DirAllowlistStore, sbx ...SandboxExecutor)

RegisterExecTools registers exec with shared session state.

func RegisterFactoryToolDefinitions

func RegisterFactoryToolDefinitions(registry *Registry)

RegisterFactoryToolDefinitions exposes factory tool names to the model.

func RegisterGatewayTool

func RegisterGatewayTool(registry *Registry, runtime *gatewayruntime.Gateway)

RegisterGatewayTool registers the native gateway tool when a runtime exists.

func RegisterImageTool

func RegisterImageTool(registry *Registry, reviewer ImageReviewService, generate ImageGenerateFunc, lookup ImageTaskLookupFunc)

RegisterImageTool registers the native image tool.

func RegisterLazyNodesTool

func RegisterLazyNodesTool(registry *Registry, resolve func() *workflow.WorkflowService)

RegisterLazyNodesTool registers the native nodes tool with lazy service resolution.

func RegisterMemoryCompatTools

func RegisterMemoryCompatTools(registry *Registry, memoryService MemoryServiceInterface)

RegisterMemoryCompatTools registers legacy memory_* wrappers backed by the native memory service.

func RegisterMemoryTools

func RegisterMemoryTools(registry *Registry, memoryService MemoryServiceInterface)

RegisterMemoryTools registers the unified memory tool plus legacy memory_* wrappers for compatibility.

func RegisterMessageTool

func RegisterMessageTool(registry *Registry, svc PushServiceInterface)

RegisterMessageTool registers the message compatibility tool.

func RegisterNodesTool

func RegisterNodesTool(registry *Registry, runtime *workflow.WorkflowService)

RegisterNodesTool registers the native nodes tool.

func RegisterOfficeTool

func RegisterOfficeTool(registry *Registry, allowedPaths []string, approvals *ApprovalManager, dirStore *DirAllowlistStore)

func RegisterPDFTool

func RegisterPDFTool(registry *Registry, service PDFService)

RegisterPDFTool registers the native PDF tool.

func RegisterPPTTool

func RegisterPPTTool(registry *Registry, service PPTGenerateService)

func RegisterPushTool

func RegisterPushTool(registry *Registry, svc PushServiceInterface)

RegisterPushTool registers the reminder tool with the registry.

func RegisterResearchTools

func RegisterResearchTools(registry *Registry, service ResearchService)

func RegisterSessionTools

func RegisterSessionTools(registry *Registry, service SessionsService)

RegisterSessionTools registers native session tools backed by the provided service.

func RegisterSkill

func RegisterSkill(registry *Registry, s skill.Skill)

RegisterSkill registers a skill as a tool in the registry.

func RegisterTTSTool

func RegisterTTSTool(registry *Registry, backend TTSBackend)

RegisterTTSTool registers the native tts compatibility tool.

func ResolveWorkdir

func ResolveWorkdir(workdir string) (string, []string)

ResolveWorkdir validates a working directory path and returns the resolved path plus any warnings. Falls back to cwd or home if the path is invalid.

func SafeToolPayloadString

func SafeToolPayloadString(raw interface{}, maxStringBytes int) string

SafeToolPayloadString renders arbitrary tool payloads as a stable string without recursing on self-referential values.

func SafeToolPayloadValue

func SafeToolPayloadValue(raw interface{}, maxStringBytes int) interface{}

SafeToolPayloadValue normalizes arbitrary tool payloads into a JSON-safe, cycle-aware value that can be logged or re-serialized safely.

func SanitizeBinaryOutput

func SanitizeBinaryOutput(s string) string

SanitizeBinaryOutput strips control characters (except tab, newline, CR) and Unicode format/surrogate characters from process output.

func SanitizeToolName

func SanitizeToolName(name string) string

SanitizeToolName normalizes a tool name to use underscores instead of hyphens. Anthropic API requires tool names to match ^[a-zA-Z0-9_-]{1,64}$ but underscores are preferred for consistency and to avoid issues with some providers.

func SaveAllowlist

func SaveAllowlist(path string, cfg *AllowlistConfig) error

SaveAllowlist writes the allowlist config to a JSON file.

func SaveBrowserScreenshotBase64

func SaveBrowserScreenshotBase64(mediaDir string, encoded string) (string, error)

SaveBrowserScreenshotBase64 persists a browser screenshot and returns the saved file path.

func StructuredWorkspaceArtifactWorkflowToolNames

func StructuredWorkspaceArtifactWorkflowToolNames(query string) []string

StructuredWorkspaceArtifactWorkflowToolNames returns the compact local tool workflow preferred for structured workspace artifact tasks.

func ToolErrorPayload

func ToolErrorPayload(err error) map[string]interface{}

ToolErrorPayload converts a runtime error into a structured tool payload.

func ValidateCommandSafety

func ValidateCommandSafety(command string) error

ValidateCommandSafety checks the raw command string against the dangerous command blocklist. Returns an error if the command matches any pattern. This check runs for ALL security modes (including "full").

func ValidateHostEnv

func ValidateHostEnv(env map[string]string) error

ValidateHostEnv checks that no dangerous environment variables are set. It also blocks custom PATH to prevent binary hijacking on the host.

func ValidateToolArguments

func ValidateToolArguments(schema map[string]interface{}, args map[string]interface{}) error

ValidateToolArguments validates a parsed argument object against a tool schema.

func ValidateToolSchema

func ValidateToolSchema(schema map[string]interface{}) error

ValidateToolSchema validates a tool JSON schema shape conservatively.

func WithAgentID

func WithAgentID(ctx context.Context, agentID string) context.Context

WithAgentID returns a context carrying the agent identifier.

func WithArtifactEmitter

func WithArtifactEmitter(ctx context.Context, fn ArtifactEmitFunc) context.Context

func WithAutoConfirm

func WithAutoConfirm(ctx context.Context, enabled bool) context.Context

WithAutoConfirm returns a context that auto-confirms approval-style flows.

func WithBrowserCheckpointRequester

func WithBrowserCheckpointRequester(ctx context.Context, fn BrowserCheckpointFunc) context.Context

WithBrowserCheckpointRequester returns a context carrying checkpoint callback.

func WithBrowserLaunchMode

func WithBrowserLaunchMode(ctx context.Context, mode BrowserLaunchMode) context.Context

WithBrowserLaunchMode returns a context carrying a browser launch hint.

func WithBrowserRouteHint

func WithBrowserRouteHint(ctx context.Context, hint BrowserRouteHint) context.Context

WithBrowserRouteHint returns a context carrying browser routing hints.

func WithCardEmitter

func WithCardEmitter(ctx context.Context, fn CardEmitFunc) context.Context

WithCardEmitter returns a context carrying a card emitter callback.

func WithChannel

func WithChannel(ctx context.Context, ch string) context.Context

WithChannel returns a context carrying the channel name (e.g. "telegram", "web").

func WithDevice

func WithDevice(ctx context.Context, device string) context.Context

WithDevice returns a context carrying the device type ("desktop" or "mobile").

func WithEventEmitter

func WithEventEmitter(ctx context.Context, fn EventEmitFunc) context.Context

func WithExecPathGuard

func WithExecPathGuard(ctx context.Context, guard ExecPathGuard) context.Context

WithExecPathGuard returns a context carrying an exec path guard.

func WithFSRootOverride

func WithFSRootOverride(ctx context.Context, roots []string, aliases map[string]string) context.Context

WithFSRootOverride returns a context carrying a filesystem root override for file tools. Relative file paths resolve against these roots instead of the tool's default configured roots.

func WithFSScope

func WithFSScope(ctx context.Context, roots []string, aliases map[string]string) context.Context

WithFSScope returns a context carrying additional filesystem roots and aliases for file tools (read/write/edit/grep/find/ls).

func WithImageInputs

func WithImageInputs(ctx context.Context, inputs []ToolImageInput) context.Context

WithImageInputs returns a context carrying inline image inputs for tools.

func WithLang

func WithLang(ctx context.Context, lang string) context.Context

WithLang returns a context carrying the language/locale (e.g. "en-US", "zh-CN").

func WithMergedFSScope

func WithMergedFSScope(ctx context.Context, roots []string, aliases map[string]string) context.Context

WithMergedFSScope merges additional filesystem roots and aliases into the existing FS scope while preserving whether the current scope replaces tool default roots or merely appends to them.

func WithModel

func WithModel(ctx context.Context, model string) context.Context

WithModel returns a context carrying the model used for tool execution.

func WithProvider

func WithProvider(ctx context.Context, provider string) context.Context

WithProvider returns a context carrying the provider name used for tool execution.

func WithProviderID

func WithProviderID(ctx context.Context, providerID string) context.Context

WithProviderID returns a context carrying the sticky/internal provider ID.

func WithRouteKind

func WithRouteKind(ctx context.Context, kind ToolRouteKind) context.Context

WithRouteKind returns a context carrying the current execution route kind.

func WithRunArtifactRoot

func WithRunArtifactRoot(ctx context.Context, root string) context.Context

func WithRunID

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

WithRunID returns a context carrying the harness run ID.

func WithRunStep

func WithRunStep(ctx context.Context, step int) context.Context

WithRunStep returns a context carrying the current harness step index.

func WithSessionID

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

WithSessionID returns a context carrying the conversation/session ID.

func WithSubagentExecutor

func WithSubagentExecutor(ctx context.Context, exec SubagentExecutor) context.Context

WithSubagentExecutor returns a context carrying a child-run executor.

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID returns a context carrying the user ID for tool/skill execution.

func WithWebExecutionPlan

func WithWebExecutionPlan(ctx context.Context, plan ExecutionPlan) context.Context

func WithWritePathGuard

func WithWritePathGuard(ctx context.Context, guard WritePathGuard) context.Context

WithWritePathGuard returns a context carrying a direct-write guard.

func WriteBinaryArtifact

func WriteBinaryArtifact(ctx context.Context, path string, data []byte) (string, error)

WriteBinaryArtifact writes raw bytes to a scoped workspace path while honoring the same filesystem guardrails as file_write.

Types

type A11yTool

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

func NewA11yTool

func NewA11yTool() *A11yTool

func RegisterHostA11yTool

func RegisterHostA11yTool(registry *Registry, mediaDir string) *A11yTool

func (*A11yTool) Backend

func (t *A11yTool) Backend() a11yruntime.Backend

func (*A11yTool) BrowserBackend

func (t *A11yTool) BrowserBackend() BrowserBackend

func (*A11yTool) Definition

func (t *A11yTool) Definition() ToolDefinition

func (*A11yTool) Execute

func (t *A11yTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*A11yTool) SetBackend

func (t *A11yTool) SetBackend(backend a11yruntime.Backend)

func (*A11yTool) SetBrowser

func (t *A11yTool) SetBrowser(backend BrowserBackend)

func (*A11yTool) SetChatGrounder

func (t *A11yTool) SetChatGrounder(grounder a11yChatGrounder)

func (*A11yTool) SetLLMBridge

func (t *A11yTool) SetLLMBridge(bridge LLMBridge)

func (*A11yTool) SetMediaDir

func (t *A11yTool) SetMediaDir(dir string)

type ACPAuthority

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

func NewACPAuthority

func NewACPAuthority(cfg ACPAuthorityConfig) *ACPAuthority

func (*ACPAuthority) CreateTerminal

func (a *ACPAuthority) CreateTerminal(ctx context.Context, command, workdir string, env map[string]string) (map[string]interface{}, error)

func (*ACPAuthority) ReadTextFile

func (a *ACPAuthority) ReadTextFile(ctx context.Context, path string, startLine, endLine int) (map[string]interface{}, error)

func (*ACPAuthority) SetAuditStore

func (a *ACPAuthority) SetAuditStore(store *ExecAuditStore)

func (*ACPAuthority) TerminalKill

func (a *ACPAuthority) TerminalKill(_ context.Context, terminalID string) (map[string]interface{}, error)

func (*ACPAuthority) TerminalOutput

func (a *ACPAuthority) TerminalOutput(_ context.Context, terminalID string) (map[string]interface{}, error)

func (*ACPAuthority) TerminalRelease

func (a *ACPAuthority) TerminalRelease(_ context.Context, terminalID string) (map[string]interface{}, error)

func (*ACPAuthority) TerminalWaitForExit

func (a *ACPAuthority) TerminalWaitForExit(ctx context.Context, terminalID string, timeout time.Duration) (map[string]interface{}, error)

func (*ACPAuthority) WriteTextFile

func (a *ACPAuthority) WriteTextFile(ctx context.Context, path, content string, appendMode bool) (map[string]interface{}, error)

type ACPAuthorityConfig

type ACPAuthorityConfig struct {
	AllowedPaths []string
	MaxFileSize  int64
	ExecConfig   ExecConfig
	Approvals    *ApprovalManager
	Broker       interface{}
	DirStore     *DirAllowlistStore
}

type AdapterManifest

type AdapterManifest struct {
	ID                  string    `json:"id,omitempty"`
	Host                string    `json:"host,omitempty"`
	PreferredLane       string    `json:"preferred_lane,omitempty"`
	WaitSelectors       []string  `json:"wait_selectors,omitempty"`
	APIEndpointPatterns []string  `json:"api_endpoint_patterns,omitempty"`
	ExtractionKeys      []string  `json:"extraction_keys,omitempty"`
	AuthExpectation     string    `json:"auth_expectation,omitempty"`
	Confidence          float64   `json:"confidence,omitempty"`
	NetworkObserved     bool      `json:"network_observed,omitempty"`
	CreatedAt           time.Time `json:"created_at,omitempty"`
	UpdatedAt           time.Time `json:"updated_at,omitempty"`
}

type AdminAPIKeyCreateResult

type AdminAPIKeyCreateResult struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Key    string `json:"key"` // full key, shown only once
	Prefix string `json:"prefix"`
}

AdminAPIKeyCreateResult holds the result of creating a new API key.

type AdminAPIKeyInfo

type AdminAPIKeyInfo struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Prefix    string `json:"prefix"` // first 8 chars
	CreatedAt string `json:"created_at,omitempty"`
}

AdminAPIKeyInfo is a simplified API key representation.

type AdminAPIKeyService

type AdminAPIKeyService interface {
	ListKeys(ctx context.Context) ([]AdminAPIKeyInfo, error)
	CreateKey(ctx context.Context, name string) (*AdminAPIKeyCreateResult, error)
	RevokeKey(ctx context.Context, id string) error
}

AdminAPIKeyService provides API key management.

type AdminChannelInfo

type AdminChannelInfo struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Status string `json:"status"`
}

AdminChannelInfo is a simplified channel representation.

type AdminChannelService

type AdminChannelService interface {
	ListChannels(ctx context.Context) ([]AdminChannelInfo, error)
	GetStatus(ctx context.Context, name string) (*AdminChannelInfo, error)
}

AdminChannelService provides channel management.

type AdminProviderInfo

type AdminProviderInfo struct {
	ID       string             `json:"id"`
	Name     string             `json:"name"`
	Type     string             `json:"type"`
	Location string             `json:"location,omitempty"` // cloud or local
	BaseURL  string             `json:"base_url,omitempty"`
	Enabled  bool               `json:"enabled"`
	Models   []string           `json:"models,omitempty"`
	Priority int                `json:"priority"`
	APIKeys  []AdminProviderKey `json:"api_keys,omitempty"`
}

AdminProviderInfo is a simplified provider representation for the admin tool.

type AdminProviderKey

type AdminProviderKey struct {
	ID      string `json:"id"`
	KeyHash string `json:"key_hash"` // e.g. "sk-ab...wxyz"
	Label   string `json:"label,omitempty"`
	Enabled bool   `json:"enabled"`
}

AdminProviderKey is a simplified API key representation (no raw key).

type AdminProviderService

type AdminProviderService interface {
	ListProviders(ctx context.Context) ([]AdminProviderInfo, error)
	AddProvider(ctx context.Context, name, providerType, baseURL, apiKey, location string) (*AdminProviderInfo, error)
	AddKey(ctx context.Context, providerID, apiKey string) (*AdminProviderInfo, error)
	RemoveProvider(ctx context.Context, id string) error
	EnableProvider(ctx context.Context, id string) error
	DisableProvider(ctx context.Context, id string) error
	ListModels(ctx context.Context) ([]map[string]interface{}, error)
}

AdminProviderService provides provider management operations.

type AdminProxyService

type AdminProxyService interface {
	Stats(ctx context.Context) (map[string]interface{}, error)
	CacheStats(ctx context.Context) (map[string]interface{}, error)
}

AdminProxyService provides proxy/pipeline statistics.

type AdminSettingsService

type AdminSettingsService interface {
	GetAll(ctx context.Context) (map[string]interface{}, error)
	Set(ctx context.Context, key, value string) error
}

AdminSettingsService provides settings management.

type AdminSkillInfo

type AdminSkillInfo struct {
	ID               string   `json:"id"`
	Name             string   `json:"name"`
	Category         string   `json:"category,omitempty"`
	Enabled          bool     `json:"enabled"`
	Builtin          bool     `json:"builtin"`
	Paths            []string `json:"paths,omitempty"`
	UserInvocable    bool     `json:"user_invocable"`
	ModelInvocable   bool     `json:"model_invocable"`
	ActivationState  string   `json:"activation_state,omitempty"`
	ActivationSource string   `json:"activation_source,omitempty"`
}

AdminSkillInfo is a simplified skill representation.

type AdminSkillService

type AdminSkillService interface {
	ListSkills(ctx context.Context) ([]AdminSkillInfo, error)
	EnableSkill(ctx context.Context, id string) error
	DisableSkill(ctx context.Context, id string) error
}

AdminSkillService provides skill management.

type AdminSystemInfo

type AdminSystemInfo struct {
	Version       string  `json:"version"`
	Uptime        string  `json:"uptime"`
	UptimeSeconds float64 `json:"uptime_seconds"`
	GoVersion     string  `json:"go_version"`
	NumCPU        int     `json:"num_cpu"`
	Goroutines    int     `json:"goroutines"`
	MemAllocMB    float64 `json:"mem_alloc_mb"`
	MemRSSMB      float64 `json:"mem_rss_mb"`
}

AdminSystemInfo holds system health information.

type AdminSystemService

type AdminSystemService interface {
	Health(ctx context.Context) (*AdminSystemInfo, error)
}

AdminSystemService provides system information.

type AdminToolInfo

type AdminToolInfo struct {
	Name                string   `json:"name"`
	Description         string   `json:"description,omitempty"`
	Disabled            bool     `json:"disabled,omitempty"`
	RiskLevel           string   `json:"risk_level,omitempty"`
	VisibilityAllowlist []string `json:"visibility_allowlist,omitempty"`
}

AdminToolInfo is a simplified tool representation.

type AdminToolService

type AdminToolService interface {
	ListTools(ctx context.Context) ([]AdminToolInfo, error)
	EnableTool(ctx context.Context, name string) error
	DisableTool(ctx context.Context, name string) error
}

AdminToolService provides tool management.

type AdminUpgradeInfo

type AdminUpgradeInfo struct {
	CurrentVersion  string   `json:"current_version"`
	UpdateAvailable bool     `json:"update_available"`
	LatestVersion   string   `json:"latest_version,omitempty"`
	DownloadURLs    []string `json:"download_urls,omitempty"`
	ReleaseNoteURL  string   `json:"release_note_url,omitempty"`
	Delay           int      `json:"delay,omitempty"`
	State           string   `json:"state,omitempty"`           // idle, checking, downloading, applying, restarting, failed
	Progress        float64  `json:"progress,omitempty"`        // 0-100
	Error           string   `json:"error,omitempty"`           // error message if failed
	DownloadedPath  string   `json:"downloaded_path,omitempty"` // path to downloaded update
}

AdminUpgradeInfo holds upgrade/OTA information.

type AdminUpgradeService

type AdminUpgradeService interface {
	GetOTAStatus(ctx context.Context) (*AdminUpgradeInfo, error)
	CheckForUpdate(ctx context.Context) (*AdminUpgradeInfo, error)
	GetUpdateStatus(ctx context.Context) (*AdminUpgradeInfo, error)
	StartDownload(ctx context.Context) (*AdminUpgradeInfo, error)
	ApplyUpdate(ctx context.Context) (*AdminUpgradeInfo, error)
}

AdminUpgradeService provides upgrade/OTA management.

type AdminUserInfo

type AdminUserInfo struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Role     string `json:"role,omitempty"`
	Locked   bool   `json:"locked"`
}

AdminUserInfo is a simplified user representation.

type AdminUserService

type AdminUserService interface {
	ListUsers(ctx context.Context) ([]AdminUserInfo, error)
	LockUser(ctx context.Context, id string) error
	UnlockUser(ctx context.Context, id string) error
}

AdminUserService provides user management.

type AdvisorBridge

type AdvisorBridge interface {
	Chat(ctx context.Context, prompt string, maxTokens int, opts AdvisorBridgeOptions) (AdvisorBridgeResponse, error)
}

AdvisorBridge adds advisor-specific model-routing options on top of text chat.

type AdvisorBridgeOptions

type AdvisorBridgeOptions struct {
	ProviderID   string
	ProviderName string
	Model        string
	Purpose      string
}

AdvisorBridgeOptions controls advisor-specific routing intent.

type AdvisorBridgeResponse

type AdvisorBridgeResponse struct {
	Content    string
	Provider   string
	ProviderID string
	Model      string
}

AdvisorBridgeResponse carries response content plus locally resolved route metadata.

type AdvisorTool

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

AdvisorTool returns decision-oriented technology and practice recommendations.

func GetAdvisorTool

func GetAdvisorTool(registry *Registry) *AdvisorTool

GetAdvisorTool retrieves the AdvisorTool from the registry for dependency injection.

func NewAdvisorTool

func NewAdvisorTool() *AdvisorTool

NewAdvisorTool creates a new advisor tool.

func RegisterAdvisorTool

func RegisterAdvisorTool(registry *Registry) *AdvisorTool

RegisterAdvisorTool registers the advisor tool with the registry.

func (*AdvisorTool) Definition

func (t *AdvisorTool) Definition() ToolDefinition

Definition returns the advisor tool schema.

func (*AdvisorTool) Execute

func (t *AdvisorTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs the advisor decision pipeline.

func (*AdvisorTool) SetBridge

func (t *AdvisorTool) SetBridge(bridge AdvisorBridge)

SetBridge injects the advisor bridge.

func (*AdvisorTool) SetExecutor

func (t *AdvisorTool) SetExecutor(executor *Executor)

SetExecutor injects the tool executor for ask/web grounding.

func (*AdvisorTool) SetResearchService

func (t *AdvisorTool) SetResearchService(service ResearchService)

SetResearchService injects the async research runtime used for deep advisor jobs.

type AgentsListTool

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

AgentsListTool lists configured agents and defaults.

func NewAgentsListTool

func NewAgentsListTool(cfg *config.Config) *AgentsListTool

NewAgentsListTool creates a native agents_list tool.

func (*AgentsListTool) Definition

func (t *AgentsListTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*AgentsListTool) Execute

func (t *AgentsListTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute returns the configured agent catalog.

type AllowlistConfig

type AllowlistConfig struct {
	Version  int                  `json:"version"`
	Defaults ExecSecurityDefaults `json:"defaults,omitempty"`
	Entries  []AllowlistEntry     `json:"entries,omitempty"`
}

AllowlistConfig is the persistent allowlist configuration.

func LoadAllowlist

func LoadAllowlist(path string) (*AllowlistConfig, error)

LoadAllowlist reads the allowlist config from a JSON file.

type AllowlistEntry

type AllowlistEntry struct {
	ID               string    `json:"id"`
	Pattern          string    `json:"pattern"`
	LastUsedAt       time.Time `json:"last_used_at,omitempty"`
	LastUsedCommand  string    `json:"last_used_command,omitempty"`
	LastResolvedPath string    `json:"last_resolved_path,omitempty"`
}

AllowlistEntry represents a single allowlist pattern entry.

func EvaluateAllowlist

func EvaluateAllowlist(analysis *CommandAnalysis, entries []AllowlistEntry, safeBins map[string]struct{}) (satisfied bool, matches []AllowlistEntry)

EvaluateAllowlist checks whether all segments of a command analysis are covered by the allowlist or safe bins.

func MatchAllowlist

func MatchAllowlist(entries []AllowlistEntry, resolvedPath string) *AllowlistEntry

MatchAllowlist checks if a resolved path matches any allowlist entry.

type AnalyzeTool

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

AnalyzeTool performs deep-dive content analysis and can return either an inline structured answer or an explicit HTML report.

func GetAnalyzeTool

func GetAnalyzeTool(registry *Registry) *AnalyzeTool

GetAnalyzeTool retrieves the AnalyzeTool from the registry for dependency injection.

func NewAnalyzeTool

func NewAnalyzeTool() *AnalyzeTool

NewAnalyzeTool creates a new analyze tool.

func RegisterAnalyzeTool

func RegisterAnalyzeTool(registry *Registry, mediaDir string) *AnalyzeTool

RegisterAnalyzeTool registers the analyze tool with the registry.

func (*AnalyzeTool) Definition

func (t *AnalyzeTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*AnalyzeTool) Execute

func (t *AnalyzeTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs the analysis pipeline.

func (*AnalyzeTool) SetBrowser

func (t *AnalyzeTool) SetBrowser(browser BrowserBackend)

SetBrowser injects the browser backend for URL scraping.

func (*AnalyzeTool) SetExecutor

func (t *AnalyzeTool) SetExecutor(executor *Executor)

SetExecutor injects the tool executor for calling web_search.

func (*AnalyzeTool) SetLLMBridge

func (t *AnalyzeTool) SetLLMBridge(bridge LLMBridge)

SetLLMBridge injects the LLM bridge for analysis.

func (*AnalyzeTool) SetMediaDir

func (t *AnalyzeTool) SetMediaDir(dir string)

SetMediaDir sets the directory for persisting HTML reports.

func (*AnalyzeTool) SetSmallModelDocExtractToggle

func (t *AnalyzeTool) SetSmallModelDocExtractToggle(setter func(bool) (bool, error))

SetSmallModelDocExtractToggle wires a persistence setter used by auto-rollback gate.

func (*AnalyzeTool) SetSmallModelRuntime

func (t *AnalyzeTool) SetSmallModelRuntime(rt smallmodel.Runtime)

SetSmallModelRuntime injects optional small-model runtime used for doc extraction pre-pass.

func (*AnalyzeTool) SetSmallModelStatsRecorder

func (t *AnalyzeTool) SetSmallModelStatsRecorder(recorder SmallModelStatsRecorder)

SetSmallModelStatsRecorder injects cross-module small-model counters.

func (*AnalyzeTool) SetSmallModelSwitchFuncs

func (t *AnalyzeTool) SetSmallModelSwitchFuncs(enabledFn, docExtractFn func() bool)

SetSmallModelSwitchFuncs injects runtime switch readers.

type ApprovalDecision

type ApprovalDecision string

ApprovalDecision represents the user's response to an exec approval request.

const (
	ApprovalAllowOnce   ApprovalDecision = "allow-once"
	ApprovalAllowAlways ApprovalDecision = "allow-always"
	ApprovalDeny        ApprovalDecision = "deny"
)

type ApprovalManager

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

ApprovalManager handles the exec approval flow via SSE.

func NewApprovalManager

func NewApprovalManager(broker *sse.Broker) *ApprovalManager

NewApprovalManager creates a new approval manager.

func (*ApprovalManager) GetPending

func (m *ApprovalManager) GetPending(userID string) *ApprovalRequest

GetPending returns the first pending approval request (if any). Used by REST endpoint so frontend can restore approval dialog after refresh.

func (*ApprovalManager) GetPendingByRun

func (m *ApprovalManager) GetPendingByRun(runID string) *ApprovalRequest

GetPendingByRun returns the first pending approval request for a harness run.

func (*ApprovalManager) GetPendingBySession

func (m *ApprovalManager) GetPendingBySession(sessionID string) *ApprovalRequest

GetPendingBySession returns the first pending approval request for a session.

func (*ApprovalManager) PendingCount

func (m *ApprovalManager) PendingCount() int

PendingCount returns the number of pending approval requests.

func (*ApprovalManager) RequestApproval

func (m *ApprovalManager) RequestApproval(ctx context.Context, req ApprovalRequest) (ApprovalDecision, error)

RequestApproval sends an approval request to the user via SSE and blocks until the user responds or the timeout expires.

func (*ApprovalManager) ResolveApproval

func (m *ApprovalManager) ResolveApproval(id string, decision ApprovalDecision) bool

ResolveApproval is called by the REST endpoint when the user responds. Returns false if the approval ID is not found (expired or already resolved).

func (*ApprovalManager) ResolveApprovalWithBinding

func (m *ApprovalManager) ResolveApprovalWithBinding(id string, decision ApprovalDecision, bindingHash string) bool

ResolveApprovalWithBinding resolves a pending approval and validates its binding hash.

func (*ApprovalManager) ResolveApprovalWithBindingStatus

func (m *ApprovalManager) ResolveApprovalWithBindingStatus(id string, decision ApprovalDecision, bindingHash string) ApprovalResolveStatus

ResolveApprovalWithBindingStatus resolves a pending approval and reports why a resolution failed.

func (*ApprovalManager) SetObserver

func (m *ApprovalManager) SetObserver(observer RuntimeEventObserver)

SetObserver wires lifecycle notifications for exec approvals.

type ApprovalPathSnapshot

type ApprovalPathSnapshot struct {
	Path    string `json:"path"`
	Exists  bool   `json:"exists"`
	Type    string `json:"type,omitempty"`
	ModTime int64  `json:"mtime,omitempty"`
	Size    int64  `json:"size,omitempty"`
}

ApprovalPathSnapshot binds an approval to the state of a target path.

type ApprovalPresentation

type ApprovalPresentation struct {
	Purpose         string   `json:"purpose,omitempty"`
	RiskSummary     string   `json:"risk_summary,omitempty"`
	ScopeSummary    string   `json:"scope_summary,omitempty"`
	ExpectedEffects string   `json:"expected_effects,omitempty"`
	AffectedTargets []string `json:"affected_targets,omitempty"`
}

ApprovalPresentation contains human-readable approval metadata for dialogs.

func BuildExecApprovalPresentation

func BuildExecApprovalPresentation(req ApprovalRequest, lang string) ApprovalPresentation

func BuildToolApprovalPresentation

func BuildToolApprovalPresentation(req ToolApprovalRequest, lang string) ApprovalPresentation

type ApprovalRequest

type ApprovalRequest struct {
	ID              string                 `json:"id"`
	RunID           string                 `json:"run_id,omitempty"`
	StepIndex       int                    `json:"step_index,omitempty"`
	Type            string                 `json:"type"` // "command" or "directory"
	Command         string                 `json:"command,omitempty"`
	CommandDigest   string                 `json:"command_digest,omitempty"`
	Directory       string                 `json:"directory,omitempty"` // for type=directory
	Workdir         string                 `json:"workdir,omitempty"`
	Host            string                 `json:"host,omitempty"`
	Security        string                 `json:"security,omitempty"`
	UserID          string                 `json:"user_id"`
	SessionID       string                 `json:"session_id,omitempty"`
	PolicySource    string                 `json:"policy_source,omitempty"`
	RiskLevel       string                 `json:"risk_level,omitempty"`
	BindingHash     string                 `json:"binding_hash,omitempty"`
	ReferencedPaths []string               `json:"referenced_paths,omitempty"`
	EnvKeys         []string               `json:"env_keys,omitempty"`
	PathSnapshots   []ApprovalPathSnapshot `json:"path_snapshots,omitempty"`
	Purpose         string                 `json:"purpose,omitempty"`
	RiskSummary     string                 `json:"risk_summary,omitempty"`
	ScopeSummary    string                 `json:"scope_summary,omitempty"`
	ExpectedEffects string                 `json:"expected_effects,omitempty"`
	AffectedTargets []string               `json:"affected_targets,omitempty"`
	ExpiresAt       int64                  `json:"expires_at"` // Unix ms
}

ApprovalRequest is the data sent to the frontend via SSE.

type ApprovalResolveStatus

type ApprovalResolveStatus int

ApprovalResolveStatus describes the outcome of resolving a pending exec approval.

const (
	ApprovalResolveNotFound ApprovalResolveStatus = iota
	ApprovalResolveBindingMismatch
	ApprovalResolveSuccess
)

type ApprovalRuntimeEvent

type ApprovalRuntimeEvent struct {
	RunID        string `json:"run_id,omitempty"`
	StepIndex    int    `json:"step_index,omitempty"`
	Kind         string `json:"kind,omitempty"`
	ID           string `json:"id,omitempty"`
	ToolName     string `json:"tool_name,omitempty"`
	ToolCallID   string `json:"tool_call_id,omitempty"`
	Command      string `json:"command,omitempty"`
	Directory    string `json:"directory,omitempty"`
	SessionID    string `json:"session_id,omitempty"`
	UserID       string `json:"user_id,omitempty"`
	PolicySource string `json:"policy_source,omitempty"`
	RiskLevel    string `json:"risk_level,omitempty"`
	BindingHash  string `json:"binding_hash,omitempty"`
	ExpiresAt    int64  `json:"expires_at,omitempty"`
	Decision     string `json:"decision,omitempty"`
	Error        string `json:"error,omitempty"`
}

type ArtifactEmitFunc

type ArtifactEmitFunc func(ctx context.Context, artifact ToolArtifact) error

type AskTool

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

AskTool is a first-class tool that asks the user questions.

func NewAskTool

func NewAskTool(mgr *QuestionManager) *AskTool

NewAskTool creates a new ask tool.

func (*AskTool) Definition

func (t *AskTool) Definition() ToolDefinition

Definition returns the tool definition. Supports both single question (q/mq + a) and multiple questions (questions array).

func (*AskTool) Execute

func (t *AskTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute asks the user one or more questions and returns their answers.

type BrowserA11yTreeResult

type BrowserA11yTreeResult struct {
	Tree     string      `json:"tree"`
	URL      string      `json:"url"`
	Title    string      `json:"title"`
	TargetID string      `json:"target_id"`
	RefMap   map[int]int `json:"ref_map,omitempty"`
}

BrowserA11yTreeResult represents an accessibility tree result.

type BrowserBackend

type BrowserBackend interface {
	Start(ctx context.Context) error
	Navigate(ctx context.Context, url string, targetID string) (BrowserNavResult, error)
	CookieHeader(ctx context.Context, targetID string, url string) (string, error)
	ObserveNetwork(ctx context.Context, targetID string, maxEntries int, clear bool) (BrowserObservedNetworkResult, error)
	WaitNetworkIdle(ctx context.Context, targetID string, idleMS int, timeoutMS int) error
	AccessibilityTree(ctx context.Context, targetID string, maxDepth int) (BrowserA11yTreeResult, error)
	InteractiveElements(ctx context.Context, targetID string) (BrowserInteractiveResult, error)
	CountInteractiveElements(ctx context.Context, targetID string) (int, error)
	ActByRef(ctx context.Context, targetID string, ref int, refMap map[int]int, action string, value string) error
	ActByInteractiveRef(ctx context.Context, targetID string, ref int, refMap map[int]string, action string, value string) error
	Screenshot(ctx context.Context, url string) (string, error)
	ScreenshotTab(ctx context.Context, targetID string) (string, error)
	CloseTab(ctx context.Context, targetID string) error
	Tabs(ctx context.Context) ([]BrowserTabResult, error)
	ExecuteRecipe(ctx context.Context, recipe string, params map[string]string) (BrowserRecipeResult, error)
	ListRecipes(ctx context.Context) []BrowserRecipeInfo
}

BrowserBackend defines the browser interface needed by the BrowserTool.

type BrowserCheckpointContext

type BrowserCheckpointContext struct {
	Kind         string                       `json:"kind"`
	CheckpointID string                       `json:"checkpoint_id"`
	Required     bool                         `json:"required"`
	RiskLevel    string                       `json:"risk_level"`
	Step         string                       `json:"step,omitempty"`
	Action       string                       `json:"action,omitempty"`
	URL          string                       `json:"url,omitempty"`
	Screenshot   *BrowserCheckpointScreenshot `json:"screenshot,omitempty"`
}

BrowserCheckpointContext is attached to ask-question payload for UI rendering.

type BrowserCheckpointDecision

type BrowserCheckpointDecision string

BrowserCheckpointDecision indicates how a checkpoint request is resolved.

const (
	BrowserCheckpointPending BrowserCheckpointDecision = "pending"
	BrowserCheckpointApprove BrowserCheckpointDecision = "approve"
	BrowserCheckpointDeny    BrowserCheckpointDecision = "deny"
	BrowserCheckpointTimeout BrowserCheckpointDecision = "timeout"
)

func ParseBrowserCheckpointDecision

func ParseBrowserCheckpointDecision(text string) (BrowserCheckpointDecision, bool)

ParseBrowserCheckpointDecision parses a free-text IM/voice reply into a decision.

type BrowserCheckpointFunc

type BrowserCheckpointFunc func(ctx context.Context, req BrowserCheckpointRequest) (BrowserCheckpointResult, error)

BrowserCheckpointFunc asks host application to resolve a browser checkpoint.

type BrowserCheckpointManager

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

BrowserCheckpointManager stores pending browser confirmations in memory. It enforces one pending checkpoint per session to prevent ambiguous replies.

func NewBrowserCheckpointManager

func NewBrowserCheckpointManager(timeout time.Duration) *BrowserCheckpointManager

NewBrowserCheckpointManager creates a manager with the given default timeout.

func (*BrowserCheckpointManager) CleanupExpired

func (m *BrowserCheckpointManager) CleanupExpired() []string

CleanupExpired removes expired checkpoints and returns removed IDs.

func (*BrowserCheckpointManager) Create

Create registers a new pending checkpoint.

func (*BrowserCheckpointManager) DefaultTimeout

func (m *BrowserCheckpointManager) DefaultTimeout() time.Duration

DefaultTimeout returns the manager default timeout.

func (*BrowserCheckpointManager) Get

Get returns checkpoint record by ID. Expired checkpoints are removed.

func (*BrowserCheckpointManager) GetPendingBySession

func (m *BrowserCheckpointManager) GetPendingBySession(sessionID string) *BrowserCheckpointRecord

GetPendingBySession returns the pending checkpoint for a session, if any.

func (*BrowserCheckpointManager) Resolve

Resolve resolves a pending checkpoint by ID.

func (*BrowserCheckpointManager) ResolveBySession

func (m *BrowserCheckpointManager) ResolveBySession(sessionID string, decision BrowserCheckpointDecision) (string, bool)

ResolveBySession resolves pending checkpoint by session ID.

func (*BrowserCheckpointManager) SetDefaultTimeout

func (m *BrowserCheckpointManager) SetDefaultTimeout(timeout time.Duration)

SetDefaultTimeout updates the manager default timeout.

func (*BrowserCheckpointManager) Wait

Wait blocks until checkpoint is resolved, timeout expires, or context cancels.

type BrowserCheckpointRecord

type BrowserCheckpointRecord struct {
	ID         string                       `json:"id"`
	SessionID  string                       `json:"session_id,omitempty"`
	UserID     string                       `json:"user_id,omitempty"`
	Channel    string                       `json:"channel,omitempty"`
	Required   bool                         `json:"required"`
	RiskLevel  string                       `json:"risk_level"`
	Step       string                       `json:"step,omitempty"`
	Action     string                       `json:"action,omitempty"`
	URL        string                       `json:"url,omitempty"`
	Screenshot *BrowserCheckpointScreenshot `json:"screenshot,omitempty"`
	CreatedAt  time.Time                    `json:"created_at"`
	ExpiresAt  time.Time                    `json:"expires_at"`
	Decision   BrowserCheckpointDecision    `json:"decision"`
	DecisionAt *time.Time                   `json:"decision_at,omitempty"`
}

BrowserCheckpointRecord represents a pending checkpoint.

type BrowserCheckpointRequest

type BrowserCheckpointRequest struct {
	ID         string
	SessionID  string
	UserID     string
	Channel    string
	Required   bool
	RiskLevel  string
	Step       string
	Action     string
	URL        string
	Screenshot *BrowserCheckpointScreenshot
	Timeout    time.Duration
}

BrowserCheckpointRequest represents a checkpoint request emitted by browser tool.

type BrowserCheckpointResult

type BrowserCheckpointResult struct {
	Decision     BrowserCheckpointDecision
	CheckpointID string
	Pending      bool
	Message      string
}

BrowserCheckpointResult is the host resolution for a checkpoint request.

func RequestBrowserCheckpoint

func RequestBrowserCheckpoint(ctx context.Context, req BrowserCheckpointRequest) (BrowserCheckpointResult, bool, error)

RequestBrowserCheckpoint asks the host to resolve a browser checkpoint. Returns ok=false when no requester exists in context.

type BrowserCheckpointScreenshot

type BrowserCheckpointScreenshot struct {
	MimeType string `json:"mime_type,omitempty"`
	Data     string `json:"data,omitempty"` // base64 data without prefix
	URL      string `json:"url,omitempty"`
}

BrowserCheckpointScreenshot carries optional screenshot context.

type BrowserInteractiveResult

type BrowserInteractiveResult struct {
	Tree     string         `json:"tree"`
	URL      string         `json:"url"`
	Title    string         `json:"title"`
	TargetID string         `json:"target_id"`
	RefMap   map[int]string `json:"ref_map,omitempty"`
	Count    int            `json:"count"`
}

BrowserInteractiveResult represents interactive elements.

type BrowserLaunchMode

type BrowserLaunchMode string

func GetBrowserLaunchMode

func GetBrowserLaunchMode(ctx context.Context) BrowserLaunchMode

GetBrowserLaunchMode extracts the browser launch hint from the context.

type BrowserNavResult

type BrowserNavResult struct {
	URL      string `json:"url"`
	Title    string `json:"title"`
	TargetID string `json:"target_id"`
}

BrowserNavResult represents a navigation result.

type BrowserNetworkEvent

type BrowserNetworkEvent struct {
	Method       string            `json:"method,omitempty"`
	URL          string            `json:"url,omitempty"`
	Status       int               `json:"status,omitempty"`
	ContentType  string            `json:"content_type,omitempty"`
	ResourceType string            `json:"resource_type,omitempty"`
	Initiator    string            `json:"initiator,omitempty"`
	DurationMS   int64             `json:"duration_ms,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	BodySample   string            `json:"body_sample,omitempty"`
}

BrowserNetworkEvent represents an observed request/response pair from a real browser session.

type BrowserObservedNetworkResult

type BrowserObservedNetworkResult struct {
	TargetID string                `json:"target_id,omitempty"`
	Events   []BrowserNetworkEvent `json:"events,omitempty"`
}

BrowserObservedNetworkResult summarizes recent network activity for a tab.

type BrowserRecipeInfo

type BrowserRecipeInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	KeepTab     bool   `json:"keep_tab"`
}

BrowserRecipeInfo describes an available recipe.

type BrowserRecipeResult

type BrowserRecipeResult struct {
	Success  bool                   `json:"success"`
	Data     map[string]interface{} `json:"data,omitempty"`
	TargetID string                 `json:"target_id,omitempty"`
	Message  string                 `json:"message"`
}

BrowserRecipeResult represents the result of a recipe execution.

type BrowserRouteHint

type BrowserRouteHint struct {
	Action           string
	FollowupAction   string
	Vision           bool
	RequiresImage    bool
	RequiresInteract bool
	RequiresRecipe   bool
}

BrowserRouteHint carries high-level browser intent so the backend can choose the right runtime before a request turns into engine-specific calls.

func GetBrowserRouteHint

func GetBrowserRouteHint(ctx context.Context) BrowserRouteHint

GetBrowserRouteHint extracts browser routing hints from context.

type BrowserSiteAllowlistEntry

type BrowserSiteAllowlistEntry struct {
	ID         string
	Origin     string
	AddedAt    time.Time
	LastUsed   time.Time
	ApprovedBy string
}

BrowserSiteAllowlistEntry represents a single approved browser origin.

type BrowserSiteAllowlistStore

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

BrowserSiteAllowlistStore persists approved browser origins per user.

func NewBrowserSiteAllowlistStore

func NewBrowserSiteAllowlistStore(db *sql.DB) (*BrowserSiteAllowlistStore, error)

NewBrowserSiteAllowlistStore creates the browser site allowlist table.

func NewBrowserSiteAllowlistStoreWithReadDB

func NewBrowserSiteAllowlistStoreWithReadDB(writeDB, readDB *sql.DB) (*BrowserSiteAllowlistStore, error)

NewBrowserSiteAllowlistStoreWithReadDB creates the browser site allowlist table with separate write and read database handles.

func (*BrowserSiteAllowlistStore) Add

func (s *BrowserSiteAllowlistStore) Add(rawURLOrOrigin, userID string) error

Add inserts an approved origin for a specific user.

func (*BrowserSiteAllowlistStore) Delete

func (s *BrowserSiteAllowlistStore) Delete(id string) error

Delete removes an approved browser origin by ID.

func (*BrowserSiteAllowlistStore) List

List returns all approved browser origins.

func (*BrowserSiteAllowlistStore) Match

func (s *BrowserSiteAllowlistStore) Match(rawURLOrOrigin, userID string) *BrowserSiteAllowlistEntry

Match returns the approved origin entry for a specific user, if any.

type BrowserTabResult

type BrowserTabResult struct {
	TargetID string `json:"target_id"`
	URL      string `json:"url"`
	Title    string `json:"title"`
	Active   bool   `json:"active"`
}

BrowserTabResult represents a browser tab.

type BrowserTool

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

BrowserTool provides browser automation as a native tool.

func GetBrowserTool

func GetBrowserTool(registry *Registry) *BrowserTool

GetBrowserTool retrieves the BrowserTool from the registry for dependency injection.

func NewBrowserTool

func NewBrowserTool() *BrowserTool

NewBrowserTool creates a new browser tool.

func (*BrowserTool) Backend

func (t *BrowserTool) Backend() BrowserBackend

Backend returns the current browser backend.

func (*BrowserTool) Definition

func (t *BrowserTool) Definition() ToolDefinition

func (*BrowserTool) Execute

func (t *BrowserTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*BrowserTool) SetBackend

func (t *BrowserTool) SetBackend(b BrowserBackend)

SetBackend injects the browser backend.

func (*BrowserTool) SetMediaDir

func (t *BrowserTool) SetMediaDir(dir string)

SetMediaDir configures the public media directory used for persisted screenshots.

type BuiltinRuntimeConfig

type BuiltinRuntimeConfig struct {
	DataDir                     string
	WorkspaceDir                string
	Ripgrep                     config.ToolCallingRipgrepConfig
	SkillDynamicExposureEnabled func() bool
}

type CalendarEvent

type CalendarEvent struct {
	ID           string    `json:"id"`
	Title        string    `json:"title"`
	Location     string    `json:"location,omitempty"`
	Notes        string    `json:"notes,omitempty"`
	CalendarName string    `json:"calendar_name,omitempty"`
	Status       string    `json:"status,omitempty"`
	StartAt      time.Time `json:"start_at"`
	EndAt        time.Time `json:"end_at"`
	AllDay       bool      `json:"all_day"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

CalendarEvent is a local calendar event.

type CalendarQueryOptions

type CalendarQueryOptions struct {
	Query string
	Start *time.Time
	End   *time.Time
	Limit int
}

CalendarQueryOptions captures list/search filters.

type CalendarStore

type CalendarStore interface {
	List(ctx context.Context, ownerID string, opts CalendarQueryOptions) ([]CalendarEvent, error)
	Get(ctx context.Context, ownerID, id string) (*CalendarEvent, error)
	Create(ctx context.Context, ownerID string, event CalendarEvent) (*CalendarEvent, error)
	Today(ctx context.Context, ownerID string, day time.Time) ([]CalendarEvent, error)
}

CalendarStore is the persistence interface used by CalendarTool.

func PreferredCalendarStore

func PreferredCalendarStore(local CalendarStore) CalendarStore

PreferredCalendarStore chooses the runtime-backed calendar store when one is available and otherwise falls back to the provided local store.

type CalendarTool

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

CalendarTool provides local event creation, lookup, and daily summaries.

func GetCalendarTool

func GetCalendarTool(registry *Registry) *CalendarTool

func NewCalendarTool

func NewCalendarTool(service CalendarStore) *CalendarTool

NewCalendarTool creates a native calendar tool.

func RegisterCalendarTool

func RegisterCalendarTool(registry *Registry, service CalendarStore) *CalendarTool

func (*CalendarTool) Definition

func (t *CalendarTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*CalendarTool) Execute

func (t *CalendarTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the selected calendar action.

func (*CalendarTool) SetCronService

func (t *CalendarTool) SetCronService(service CronService)

SetCronService wires scheduled job context into daily_summary.

func (*CalendarTool) SetEmailService

func (t *CalendarTool) SetEmailService(service EmailService)

SetEmailService wires inbox context into daily_summary.

func (*CalendarTool) SetNowFunc

func (t *CalendarTool) SetNowFunc(fn func() time.Time)

SetNowFunc overrides the clock, mainly for tests.

func (*CalendarTool) SetReminderService

func (t *CalendarTool) SetReminderService(service PushServiceInterface)

SetReminderService wires reminder context into daily_summary.

type CanvasTool

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

CanvasTool manages lightweight A2UI canvases.

func NewCanvasTool

func NewCanvasTool(manager *a2ui.Manager) *CanvasTool

NewCanvasTool creates a native canvas tool.

func (*CanvasTool) Definition

func (t *CanvasTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*CanvasTool) Execute

func (t *CanvasTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the requested canvas action.

type CardEmitFunc

type CardEmitFunc func(card map[string]interface{})

CardEmitFunc is a callback that tools can use to emit streaming typeless cards during execution. The card map is JSON-serialised and pushed to the client's SSE stream immediately.

type ChallengeState

type ChallengeState struct {
	Kind            string `json:"kind,omitempty"`
	Code            string `json:"code,omitempty"`
	Message         string `json:"message,omitempty"`
	ResumeAction    string `json:"resume_action,omitempty"`
	RequiresBrowser bool   `json:"requires_browser,omitempty"`
	RequiresHuman   bool   `json:"requires_human,omitempty"`
}

type CommandAnalysis

type CommandAnalysis struct {
	OK       bool
	Reason   string
	Segments []CommandSegment
}

CommandAnalysis is the result of parsing a shell command.

func AnalyzeCommand

func AnalyzeCommand(command, cwd string) *CommandAnalysis

AnalyzeCommand parses a shell command string into segments and resolves executable paths. It rejects commands with dangerous shell tokens.

type CommandSafetyMatch

type CommandSafetyMatch struct {
	Reason              string
	RequiresApproval    bool
	RiskLevel           RiskLevel
	SuppressRiskReasons []string
}

CommandSafetyMatch describes a dangerous command pattern match and whether it should be hard-blocked or routed through approval.

func MatchCommandSafety

func MatchCommandSafety(command string) *CommandSafetyMatch

MatchCommandSafety checks the raw command string against the dangerous command patterns and returns how the caller should handle the first match.

type CommandSegment

type CommandSegment struct {
	Raw            string
	Argv           []string
	ExecutableName string
	ResolvedPath   string
}

CommandSegment represents a parsed segment of a shell command.

type ContactRecord

type ContactRecord struct {
	ID             string    `json:"id"`
	FirstName      string    `json:"first_name,omitempty"`
	LastName       string    `json:"last_name,omitempty"`
	DisplayName    string    `json:"display_name"`
	Organization   string    `json:"organization,omitempty"`
	Title          string    `json:"title,omitempty"`
	Address        string    `json:"address,omitempty"`
	Birthday       string    `json:"birthday,omitempty"`
	Notes          string    `json:"notes,omitempty"`
	PhoneNumbers   []string  `json:"phone_numbers,omitempty"`
	EmailAddresses []string  `json:"email_addresses,omitempty"`
	CreatedAt      time.Time `json:"created_at,omitempty"`
	UpdatedAt      time.Time `json:"updated_at,omitempty"`
}

ContactRecord represents a native contact exposed through the contacts tool.

type ContactsQueryOptions

type ContactsQueryOptions struct {
	Query string
	Limit int
}

ContactsQueryOptions captures list/search filters.

type ContactsStore

type ContactsStore interface {
	List(ctx context.Context, ownerID string, opts ContactsQueryOptions) ([]ContactRecord, error)
	Get(ctx context.Context, ownerID, id string) (*ContactRecord, error)
	Create(ctx context.Context, ownerID string, contact ContactRecord) (*ContactRecord, error)
}

ContactsStore is the persistence interface used by ContactsTool.

func NewUnavailableContactsStore

func NewUnavailableContactsStore(reason string) ContactsStore

NewUnavailableContactsStore returns a runtime backend that reports native contacts as unavailable instead of silently falling back to app-local data.

func PreferredContactsStore

func PreferredContactsStore(fallback ContactsStore) ContactsStore

PreferredContactsStore chooses the runtime-backed contacts store when one is available and otherwise falls back to the provided backend.

type ContactsTool

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

ContactsTool provides native contacts lookup and creation workflows.

func GetContactsTool

func GetContactsTool(registry *Registry) *ContactsTool

func NewContactsTool

func NewContactsTool(service ContactsStore) *ContactsTool

NewContactsTool creates a native contacts tool.

func RegisterContactsTool

func RegisterContactsTool(registry *Registry, service ContactsStore) *ContactsTool

func (*ContactsTool) Definition

func (t *ContactsTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*ContactsTool) Execute

func (t *ContactsTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the selected contacts action.

func (*ContactsTool) SetNowFunc

func (t *ContactsTool) SetNowFunc(fn func() time.Time)

SetNowFunc overrides the clock, mainly for tests.

type ConvertTool

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

func NewConvertTool

func NewConvertTool(service *convertpkg.Service, approvals *ApprovalManager, dirStore *DirAllowlistStore, allowedPaths []string) *ConvertTool

func (*ConvertTool) Definition

func (t *ConvertTool) Definition() ToolDefinition

func (*ConvertTool) Execute

func (t *ConvertTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type CronConfigInfo

type CronConfigInfo struct {
	Enabled                 bool `json:"enabled"`
	MaxConcurrentJobs       int  `json:"max_concurrent_jobs"`
	JobTimeoutSeconds       int  `json:"job_timeout_seconds"`
	ExecutionRetentionHours int  `json:"execution_retention_hours"`
	MaxExecutionsPerJob     int  `json:"max_executions_per_job"`
}

CronConfigInfo exposes scheduler runtime limits and retention.

type CronExecutionInfo

type CronExecutionInfo struct {
	ID        string        `json:"id"`
	JobID     string        `json:"job_id"`
	StartedAt time.Time     `json:"started_at"`
	EndedAt   *time.Time    `json:"ended_at,omitempty"`
	Duration  time.Duration `json:"duration,omitempty"`
	Status    string        `json:"status"`
	Error     string        `json:"error,omitempty"`
	Result    interface{}   `json:"result,omitempty"`
}

CronExecutionInfo is the normalized job execution view.

type CronJobInfo

type CronJobInfo struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Schedule    string                 `json:"schedule"`
	Handler     string                 `json:"handler"`
	Payload     map[string]interface{} `json:"payload,omitempty"`
	Status      string                 `json:"status"`
	Enabled     bool                   `json:"enabled"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
	LastRunAt   *time.Time             `json:"last_run_at,omitempty"`
	NextRunAt   *time.Time             `json:"next_run_at,omitempty"`
	RunCount    int64                  `json:"run_count"`
	FailCount   int64                  `json:"fail_count"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

CronJobInfo is the normalized job view exposed by the cron tool.

type CronService

type CronService interface {
	Config(ctx context.Context) CronConfigInfo
	Handlers(ctx context.Context) []string
	ListJobs(ctx context.Context) ([]CronJobInfo, error)
	GetJob(ctx context.Context, id string) (*CronJobInfo, error)
	CreateJob(ctx context.Context, name, description, schedule, handler string, payload map[string]interface{}) (*CronJobInfo, error)
	UpdateJob(ctx context.Context, id, name, description, schedule string, payload map[string]interface{}) error
	DeleteJob(ctx context.Context, id string) error
	EnableJob(ctx context.Context, id string) error
	DisableJob(ctx context.Context, id string) error
	TriggerJob(ctx context.Context, id string) error
	GetExecutions(ctx context.Context, id string, limit int) ([]CronExecutionInfo, error)
}

CronService provides stable access to scheduler capabilities.

type CronTool

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

CronTool manages scheduled jobs.

func NewCronTool

func NewCronTool(service CronService) *CronTool

NewCronTool creates a native cron tool.

func (*CronTool) Definition

func (t *CronTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*CronTool) Execute

func (t *CronTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the requested cron action.

type DOCXTool

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

func NewDOCXTool

func NewDOCXTool(allowedPaths []string, approvals *ApprovalManager, dirStore *DirAllowlistStore) *DOCXTool

func (*DOCXTool) Definition

func (t *DOCXTool) Definition() ToolDefinition

func (*DOCXTool) Execute

func (t *DOCXTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type DeepResearchTool

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

func NewDeepResearchTool

func NewDeepResearchTool(service ResearchService) *DeepResearchTool

func (*DeepResearchTool) Definition

func (t *DeepResearchTool) Definition() ToolDefinition

func (*DeepResearchTool) Execute

func (t *DeepResearchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type DeferredToolExposureState

type DeferredToolExposureState struct {
	ActivatedTools          []string
	SelectedSkills          []string
	SelectedAgents          []string
	NeedExec                bool
	NeedAgentTools          bool
	ActivationRequested     bool
	ActivationApplied       bool
	ActivationFailureReason string
	RegistryVersion         uint64
	PromptPolicyHash        string
	SkillExposureStamp      string
	ExpiresAt               time.Time
}

type DeferredToolExposureStore

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

func NewDeferredToolExposureStore

func NewDeferredToolExposureStore(ttl time.Duration) *DeferredToolExposureStore

func (*DeferredToolExposureStore) Apply

func (*DeferredToolExposureStore) Delete

func (s *DeferredToolExposureStore) Delete(sessionID string) bool

func (*DeferredToolExposureStore) InvalidateIfStale

func (s *DeferredToolExposureStore) InvalidateIfStale(sessionID string, registryVersion uint64, promptPolicyHash, skillExposureStamp string) (bool, string)

func (*DeferredToolExposureStore) SetInvalidationCallback

func (s *DeferredToolExposureStore) SetInvalidationCallback(fn func(string))

func (*DeferredToolExposureStore) Snapshot

type DeferredToolExposureUpdate

type DeferredToolExposureUpdate struct {
	ActivatedTools          []string
	SelectedSkills          []string
	SelectedAgents          []string
	NeedExec                bool
	NeedAgentTools          bool
	ActivationRequested     *bool
	ActivationApplied       *bool
	ActivationFailureReason *string
	RegistryVersion         uint64
	PromptPolicyHash        string
	SkillExposureStamp      string
}

type DirAllowlistEntry

type DirAllowlistEntry struct {
	ID         string
	Path       string // absolute, cleaned
	AddedAt    time.Time
	LastUsed   time.Time
	ApprovedBy string // user ID
}

DirAllowlistEntry represents a single approved directory.

type DirAllowlistStore

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

DirAllowlistStore persists approved directories in a SQLite table.

func NewDirAllowlistStore

func NewDirAllowlistStore(db *sql.DB) (*DirAllowlistStore, error)

NewDirAllowlistStore creates the table and returns a store.

func NewDirAllowlistStoreWithReadDB

func NewDirAllowlistStoreWithReadDB(writeDB, readDB *sql.DB) (*DirAllowlistStore, error)

NewDirAllowlistStoreWithReadDB creates the table and returns a store with separate write and read database handles.

func (*DirAllowlistStore) Add

func (s *DirAllowlistStore) Add(absPath, userID string) error

Add inserts a directory. Does nothing if the exact path already exists. Parent/child entries are NOT merged — both are kept.

func (*DirAllowlistStore) Delete

func (s *DirAllowlistStore) Delete(id string) error

Delete removes an entry by ID.

func (*DirAllowlistStore) List

func (s *DirAllowlistStore) List() ([]DirAllowlistEntry, error)

List returns all approved directories.

func (*DirAllowlistStore) Match

func (s *DirAllowlistStore) Match(absDir string) *DirAllowlistEntry

Match checks if absDir is equal to or a subdirectory of any approved path. Returns the matching entry or nil.

type DocumentReadService

type DocumentReadService interface {
	ReadDocument(ctx context.Context, path string) (*convertpkg.DocumentReadResult, error)
}

DocumentReadService extracts readable text from local office-style documents.

type DomainStrategy

type DomainStrategy struct {
	Host                string    `json:"host,omitempty"`
	PreferredLane       string    `json:"preferred_lane,omitempty"`
	AdapterID           string    `json:"adapter_id,omitempty"`
	NeedsRealBrowser    bool      `json:"needs_real_browser,omitempty"`
	NeedsNetworkObserve bool      `json:"needs_network_observe,omitempty"`
	LoginRequired       bool      `json:"login_required,omitempty"`
	Confidence          float64   `json:"confidence,omitempty"`
	Hits                int       `json:"hits,omitempty"`
	UpdatedAt           time.Time `json:"updated_at,omitempty"`
}

type EditTool

type EditTool struct {
	Scope       *fsToolScope
	MaxFileSize int64
	// contains filtered or unexported fields
}

func NewEditTool

func NewEditTool(allowedPaths []string, maxFileSize int64) *EditTool

func (*EditTool) Definition

func (t *EditTool) Definition() ToolDefinition

func (*EditTool) Execute

func (t *EditTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*EditTool) SetSkillExposureManager

func (t *EditTool) SetSkillExposureManager(manager *skillmanifest.SkillExposureManager)

type EmailMessage

type EmailMessage struct {
	ID          string    `json:"id"`
	ThreadID    string    `json:"thread_id,omitempty"`
	Subject     string    `json:"subject"`
	SenderName  string    `json:"sender_name,omitempty"`
	SenderEmail string    `json:"sender_email"`
	Recipients  []string  `json:"recipients,omitempty"`
	Snippet     string    `json:"snippet,omitempty"`
	Body        string    `json:"body,omitempty"`
	Labels      []string  `json:"labels,omitempty"`
	Priority    string    `json:"priority,omitempty"`
	Unread      bool      `json:"unread"`
	Archived    bool      `json:"archived"`
	ReceivedAt  time.Time `json:"received_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

EmailMessage represents an inbox message managed by the local email tool and daily summary aggregation.

type EmailQueryOptions

type EmailQueryOptions struct {
	Query    string
	From     string
	Label    string
	Priority string
	Unread   *bool
	Archived *bool
	Limit    int
}

EmailQueryOptions describes list/search/filter constraints.

type EmailService

type EmailService interface {
	List(ctx context.Context, ownerID string, opts EmailQueryOptions) ([]EmailMessage, error)
	Get(ctx context.Context, ownerID, id string) (*EmailMessage, error)
	Archive(ctx context.Context, ownerID, id string, archived bool) (*EmailMessage, error)
	Label(ctx context.Context, ownerID, id string, add, remove []string) (*EmailMessage, error)
	Summarize(ctx context.Context, ownerID string, opts EmailQueryOptions) (*EmailSummary, error)
}

EmailService is the backing store used by the email tool and daily summary.

type EmailSummary

type EmailSummary struct {
	Total             int            `json:"total"`
	Unread            int            `json:"unread"`
	Archived          int            `json:"archived"`
	HighPriority      int            `json:"high_priority"`
	ActionableCount   int            `json:"actionable_count"`
	LabelCounts       map[string]int `json:"label_counts,omitempty"`
	TopActionItems    []string       `json:"top_action_items,omitempty"`
	HighlightMessages []EmailMessage `json:"highlight_messages,omitempty"`
}

EmailSummary captures a concise inbox overview.

type EmailTool

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

EmailTool provides inbox triage actions over an extensible email service.

func GetEmailTool

func GetEmailTool(registry *Registry) *EmailTool

func NewEmailTool

func NewEmailTool(service EmailService) *EmailTool

NewEmailTool creates a native inbox management tool.

func RegisterEmailTool

func RegisterEmailTool(registry *Registry, service EmailService) *EmailTool

func (*EmailTool) Definition

func (t *EmailTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*EmailTool) Execute

func (t *EmailTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs the requested inbox operation.

type EventEmitFunc

type EventEmitFunc func(ctx context.Context, event ToolEvent) error

type ExecAuditEntry

type ExecAuditEntry struct {
	ID         string        `json:"id"`
	Timestamp  time.Time     `json:"timestamp"`
	UserID     string        `json:"user_id"`
	Command    string        `json:"command"`
	Workdir    string        `json:"workdir"`
	RiskScore  int           `json:"risk_score"`
	RiskLevel  RiskLevel     `json:"risk_level"`
	PolicyMode string        `json:"policy_mode"`
	Decision   string        `json:"decision"` // "allowed", "blocked", "approved"
	ExitCode   *int          `json:"exit_code,omitempty"`
	Duration   time.Duration `json:"duration"`
	StdoutLen  int           `json:"stdout_len"`
	StderrLen  int           `json:"stderr_len"`
	Error      string        `json:"error,omitempty"`
}

ExecAuditEntry is a single audit record for an exec invocation.

type ExecAuditStore

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

ExecAuditStore persists exec audit entries in SQLite.

func NewExecAuditStore

func NewExecAuditStore(db *sql.DB) (*ExecAuditStore, error)

NewExecAuditStore creates the audit table and returns a store.

func NewExecAuditStoreWithReadDB

func NewExecAuditStoreWithReadDB(writeDB, readDB *sql.DB) (*ExecAuditStore, error)

NewExecAuditStoreWithReadDB creates the audit table and returns a store with separate write and read database handles.

func (*ExecAuditStore) Recent

func (s *ExecAuditStore) Recent(limit int) ([]ExecAuditEntry, error)

Recent returns the most recent N audit entries.

func (*ExecAuditStore) Record

func (s *ExecAuditStore) Record(entry ExecAuditEntry) error

Record inserts an audit entry.

type ExecConfig

type ExecConfig struct {
	Host           string        // "local" or "sandbox"
	Security       ExecSecurity  // "deny", "allowlist", "full"
	DefaultTimeout time.Duration // default per-command timeout
	MaxTimeout     time.Duration // maximum allowed timeout
	MaxOutput      int           // max output chars per stream
	SafeBins       []string      // auto-allowed binaries
	DataDir        string        // for allowlist JSON persistence
	ServiceHost    string        // host exposed to blue CLI subprocesses
	ServicePort    int           // port exposed to blue CLI subprocesses
	AllowPTY       bool          // whether PTY mode is available
	AllowedDirs    []string      // directories the exec tool may operate in; empty = unrestricted
	Shell          string        // override shell binary (empty = auto-detect via GetShellConfig)
	ShellArgs      []string      // override shell args (empty = auto-detect)
	Policy         *ExecPolicy   // runtime policy (nil = default)
}

ExecConfig configures the exec tool.

func DefaultExecConfig

func DefaultExecConfig() ExecConfig

DefaultExecConfig returns sensible defaults.

type ExecPathGuard

type ExecPathGuard interface {
	CheckExecWorkdir(ctx context.Context, absWorkdir string) error
	CheckExecPath(ctx context.Context, absPath string) error
}

ExecPathGuard enforces runtime-specific path restrictions for exec-style tools before directory approvals or host execution.

func GetExecPathGuard

func GetExecPathGuard(ctx context.Context) ExecPathGuard

GetExecPathGuard extracts the exec path guard from the context.

type ExecPolicy

type ExecPolicy struct {
	Mode             PolicyMode    `json:"mode"`
	MaxRiskThreshold int           `json:"max_risk_threshold"` // commands above this score are blocked
	MaxRetries       int           `json:"max_retries"`        // max times the same command can be retried
	RetryWindow      time.Duration `json:"retry_window"`       // window for counting retries
	MaxCommandLen    int           `json:"max_command_len"`    // max command string length (0 = unlimited)
}

ExecPolicy defines the runtime policy for exec commands.

func DefaultExecPolicy

func DefaultExecPolicy() ExecPolicy

DefaultExecPolicy returns sensible defaults.

func PolicyForMode

func PolicyForMode(mode PolicyMode) ExecPolicy

PolicyForMode returns a policy with thresholds appropriate for the given mode.

type ExecSecurity

type ExecSecurity string

ExecSecurity defines the security mode for command execution.

const (
	ExecSecurityDeny      ExecSecurity = "deny"
	ExecSecurityAllowlist ExecSecurity = "allowlist"
	ExecSecurityFull      ExecSecurity = "full"
)

type ExecSecurityDefaults

type ExecSecurityDefaults struct {
	Security ExecSecurity `json:"security,omitempty"`
}

ExecSecurityDefaults holds default security settings.

type ExecTool

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

ExecTool implements the Tool interface for shell command execution.

func GetExecTool

func GetExecTool(registry *Registry) *ExecTool

GetExecTool retrieves the ExecTool from the registry for dependency injection.

func NewExecTool

func NewExecTool(config ExecConfig, sessions *SessionRegistry, approvals *ApprovalManager, broker *sse.Broker, dirStore *DirAllowlistStore, sbx ...SandboxExecutor) *ExecTool

NewExecTool creates a new exec tool.

func (*ExecTool) Definition

func (t *ExecTool) Definition() ToolDefinition

Definition returns the tool definition for the LLM.

func (*ExecTool) Execute

func (t *ExecTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs the shell command.

func (*ExecTool) HasSandbox

func (t *ExecTool) HasSandbox() bool

HasSandbox returns true if sandbox execution is available.

func (*ExecTool) Policy

func (t *ExecTool) Policy() ExecPolicy

Policy returns the current exec policy (read-only).

func (*ExecTool) SetAuditStore

func (t *ExecTool) SetAuditStore(store *ExecAuditStore)

SetAuditStore sets the persistent audit log store. Call after construction when the DB is available (deferred wiring pattern).

func (*ExecTool) SetAutoConfirmFunc

func (t *ExecTool) SetAutoConfirmFunc(fn func() bool)

SetAutoConfirmFunc sets a dynamic auto-confirm getter for destructive skill gating.

func (*ExecTool) SetPinnedSkills

func (t *ExecTool) SetPinnedSkills(names []string)

SetPinnedSkills sets the pinned skill names for short-circuiting skill commands (e.g. "web_search query" → skill executor). Unlike tool auto-forward, this avoids registering skills as tools (which would consume extra prompt tokens).

func (*ExecTool) SetRegistry

func (t *ExecTool) SetRegistry(r *Registry)

SetRegistry sets the tool registry so exec can auto-forward commands that match a tool name (e.g. "web_search latest news") to the actual tool instead of returning an error.

func (*ExecTool) SetSkillExecutor

func (t *ExecTool) SetSkillExecutor(fn SkillExecFunc)

SetSkillExecutor sets the skill executor for short-circuiting `blue <skill>` commands.

func (*ExecTool) SetSkillSelector

func (t *ExecTool) SetSkillSelector(fn SkillSelectFunc)

SetSkillSelector sets the progressive selector for unknown skills.

func (*ExecTool) SetToolNames

func (t *ExecTool) SetToolNames(names []string)

SetToolNames sets the known tool names so exec can reject commands that look like tool invocations (e.g. "web_search query" instead of calling the web_search tool directly).

type ExecutionPlan

type ExecutionPlan struct {
	Kind           WebTaskKind       `json:"kind"`
	PrimaryRuntime string            `json:"primary_runtime"`
	Steps          []PlanStep        `json:"steps,omitempty"`
	ExtractorMode  string            `json:"extractor_mode,omitempty"`
	TraceLabels    map[string]string `json:"trace_labels,omitempty"`
}

func WebExecutionPlanFromContext

func WebExecutionPlanFromContext(ctx context.Context) (ExecutionPlan, bool)

type Executor

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

Executor handles tool execution.

func NewExecutor

func NewExecutor(registry *Registry) *Executor

NewExecutor creates a new tool executor.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, name string, args map[string]interface{}) (interface{}, error)

Execute runs a tool by name with the given arguments.

func (*Executor) ExecuteJSON

func (e *Executor) ExecuteJSON(ctx context.Context, name string, argsJSON string) (interface{}, error)

ExecuteJSON runs a tool by name with JSON-encoded arguments.

func (*Executor) SetTraceStore

func (e *Executor) SetTraceStore(store *ToolTraceStore)

SetTraceStore wires an optional in-memory trace sink for tool executions.

type FetchOrchestrator

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

func (*FetchOrchestrator) Fetch

type FetchRequest

type FetchRequest struct {
	URL               string
	Mode              string
	MaxChars          int
	PreferredLane     string
	Options           webFetchRequestOptions
	AllowBrowser      bool
	AllowProxy        bool
	AllowSession      bool
	AllowAutoFallback bool
	BrowserReasonCode string
	BrowserReason     string
}

type FetchResult

type FetchResult struct {
	Payload         webFetchPayload
	StrategyUsed    string
	SessionReused   bool
	AdapterID       string
	NetworkObserved bool
	ChallengeState  *ChallengeState
	BrowserTargetID string
	ObservedNetwork []BrowserNetworkEvent
}

type FetchSession

type FetchSession struct {
	Key              string    `json:"key,omitempty"`
	Host             string    `json:"host,omitempty"`
	BrowserTargetID  string    `json:"browser_target_id,omitempty"`
	LastLane         string    `json:"last_lane,omitempty"`
	SessionReusable  bool      `json:"session_reusable,omitempty"`
	NeedsRealBrowser bool      `json:"needs_real_browser,omitempty"`
	UpdatedAt        time.Time `json:"updated_at,omitempty"`
}

type Fetcher

type Fetcher interface {
	Name() string
	Fetch(context.Context, *FetchOrchestrator, FetchRequest) (FetchResult, error)
}

type FileDeleteTool

type FileDeleteTool struct {
	AllowedPaths []string
	// contains filtered or unexported fields
}

func NewFileDeleteTool

func NewFileDeleteTool(allowedPaths []string) *FileDeleteTool

func (*FileDeleteTool) Definition

func (f *FileDeleteTool) Definition() ToolDefinition

func (*FileDeleteTool) Execute

func (f *FileDeleteTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type FileReadTool

type FileReadTool struct {
	// AllowedPaths restricts file access to specific directories.
	// When empty, current working directory is treated as workspace root.
	AllowedPaths []string
	// MaxFileSize is the maximum file size to read (default 2 MiB).
	MaxFileSize int64
	// contains filtered or unexported fields
}

FileReadTool reads content from a file.

func NewFileReadTool

func NewFileReadTool(allowedPaths []string, maxFileSize int64) *FileReadTool

NewFileReadTool creates a new file read tool.

func (*FileReadTool) Definition

func (f *FileReadTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*FileReadTool) Execute

func (f *FileReadTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute reads the file content.

func (*FileReadTool) SetDocumentReadService

func (f *FileReadTool) SetDocumentReadService(service DocumentReadService)

SetDocumentReadService enables office-style document reads for local files.

func (*FileReadTool) SetPDFService

func (f *FileReadTool) SetPDFService(service PDFService)

SetPDFService enables PDF-aware reads for local PDF files.

func (*FileReadTool) SetSkillExposureManager

func (f *FileReadTool) SetSkillExposureManager(manager *skillmanifest.SkillExposureManager)

type FileWriteAbortTool

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

func NewFileWriteAbortTool

func NewFileWriteAbortTool(sessions *WriteSessionManager) *FileWriteAbortTool

func (*FileWriteAbortTool) Definition

func (t *FileWriteAbortTool) Definition() ToolDefinition

func (*FileWriteAbortTool) Execute

func (t *FileWriteAbortTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type FileWriteBeginTool

type FileWriteBeginTool struct {
	AllowedPaths []string
	// contains filtered or unexported fields
}

func NewFileWriteBeginTool

func NewFileWriteBeginTool(allowedPaths []string, sessions *WriteSessionManager) *FileWriteBeginTool

func (*FileWriteBeginTool) Definition

func (t *FileWriteBeginTool) Definition() ToolDefinition

func (*FileWriteBeginTool) Execute

func (t *FileWriteBeginTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type FileWriteChunkTool

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

func NewFileWriteChunkTool

func NewFileWriteChunkTool(sessions *WriteSessionManager) *FileWriteChunkTool

func (*FileWriteChunkTool) Definition

func (t *FileWriteChunkTool) Definition() ToolDefinition

func (*FileWriteChunkTool) Execute

func (t *FileWriteChunkTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type FileWriteCommitTool

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

func NewFileWriteCommitTool

func NewFileWriteCommitTool(sessions *WriteSessionManager) *FileWriteCommitTool

func (*FileWriteCommitTool) Definition

func (t *FileWriteCommitTool) Definition() ToolDefinition

func (*FileWriteCommitTool) Execute

func (t *FileWriteCommitTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type FileWriteTool

type FileWriteTool struct {
	// AllowedPaths restricts file access to specific directories.
	AllowedPaths []string
	// MaxFileSize is the maximum file size to write (default 2 MiB).
	MaxFileSize int64
	// contains filtered or unexported fields
}

FileWriteTool writes content to a file.

func NewFileWriteTool

func NewFileWriteTool(allowedPaths []string, maxFileSize int64) *FileWriteTool

NewFileWriteTool creates a new file write tool.

func (*FileWriteTool) Definition

func (f *FileWriteTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*FileWriteTool) Execute

func (f *FileWriteTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute writes content to the file.

func (*FileWriteTool) SetSkillExposureManager

func (f *FileWriteTool) SetSkillExposureManager(manager *skillmanifest.SkillExposureManager)

type FindTool

type FindTool struct {
	Scope   *fsToolScope
	Ripgrep ripgrepResolver
	// contains filtered or unexported fields
}

func NewFindTool

func NewFindTool(allowedPaths []string) *FindTool

func NewFindToolWithRipgrep

func NewFindToolWithRipgrep(allowedPaths []string, resolver ripgrepResolver) *FindTool

func (*FindTool) Definition

func (t *FindTool) Definition() ToolDefinition

func (*FindTool) Execute

func (t *FindTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type FinishedSession

type FinishedSession struct {
	ID         string
	Command    string
	Workdir    string
	StartedAt  time.Time
	EndedAt    time.Time
	Status     ProcessStatus
	ExitCode   *int
	ExitSignal string
	Output     string // aggregated stdout+stderr
	Truncated  bool
}

FinishedSession is a snapshot of a completed session.

type ForwardedResult

type ForwardedResult struct {
	ActualTool string
	Result     interface{}
}

ForwardedResult wraps a tool result that was auto-forwarded from exec. The ActualTool field indicates which tool actually executed the request, allowing the UI to display the correct tool name (e.g. "web_query" instead of "exec").

type GatewayConfigInfo

type GatewayConfigInfo struct {
	Enabled               bool  `json:"enabled"`
	ReadBufferSize        int   `json:"read_buffer_size"`
	WriteBufferSize       int   `json:"write_buffer_size"`
	MaxMessageSize        int64 `json:"max_message_size"`
	PingIntervalSeconds   int   `json:"ping_interval_seconds"`
	PongTimeoutSeconds    int   `json:"pong_timeout_seconds"`
	WriteTimeoutSeconds   int   `json:"write_timeout_seconds"`
	RequestTimeoutSeconds int   `json:"request_timeout_seconds"`
	MaxConnections        int   `json:"max_connections"`
}

GatewayConfigInfo is the normalized gateway runtime configuration exposed to tools.

type GatewayConnectionInfo

type GatewayConnectionInfo struct {
	ID               string                 `json:"id"`
	UserID           string                 `json:"user_id,omitempty"`
	ConnectedAt      time.Time              `json:"connected_at"`
	MessagesSent     int64                  `json:"messages_sent"`
	MessagesReceived int64                  `json:"messages_received"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

GatewayConnectionInfo is the normalized gateway connection view used by tools.

type GatewayService

type GatewayService interface {
	Stats(ctx context.Context) map[string]interface{}
	Config(ctx context.Context) GatewayConfigInfo
	Methods(ctx context.Context) []string
	ListConnections(ctx context.Context) ([]GatewayConnectionInfo, error)
	GetConnection(ctx context.Context, id string) (*GatewayConnectionInfo, error)
	CloseConnection(ctx context.Context, id string) error
}

GatewayService provides stable access to gateway runtime info and controls.

type GatewayTool

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

GatewayTool inspects and manages the local gateway runtime.

func NewGatewayTool

func NewGatewayTool(service GatewayService) *GatewayTool

NewGatewayTool creates a native gateway tool.

func (*GatewayTool) Definition

func (t *GatewayTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*GatewayTool) Execute

func (t *GatewayTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the requested gateway action.

func (*GatewayTool) SetRegistry

func (t *GatewayTool) SetRegistry(registry *Registry)

SetRegistry enables exec fallback for unsupported lifecycle actions.

type GenerateImageTool

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

func (*GenerateImageTool) Definition

func (t *GenerateImageTool) Definition() ToolDefinition

func (*GenerateImageTool) Execute

func (t *GenerateImageTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type GrepTool

type GrepTool struct {
	Scope       *fsToolScope
	MaxFileSize int64
	Name        string
	Description string
	Ripgrep     ripgrepResolver
	// contains filtered or unexported fields
}

func NewGrepTool

func NewGrepTool(allowedPaths []string, maxFileSize int64) *GrepTool

func NewGrepToolWithRipgrep

func NewGrepToolWithRipgrep(allowedPaths []string, maxFileSize int64, resolver ripgrepResolver) *GrepTool

func NewRgTool

func NewRgTool(allowedPaths []string, maxFileSize int64) *GrepTool

func NewRgToolWithRipgrep

func NewRgToolWithRipgrep(allowedPaths []string, maxFileSize int64, resolver ripgrepResolver) *GrepTool

func (*GrepTool) Definition

func (t *GrepTool) Definition() ToolDefinition

func (*GrepTool) Execute

func (t *GrepTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type HybridCapabilityBrowserBackend

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

HybridCapabilityBrowserBackend routes browser work by capability between Lightpanda read-only sessions and Chromium runtimes.

func NewHybridCapabilityBrowserBackend

func NewHybridCapabilityBrowserBackend(
	config *browser.Config,
	lightpanda *browser.LightpandaService,
	lightpandaBinary sessionBrowserBackend,
	managed sessionBrowserBackend,
	relay sessionBrowserBackend,
	preferRelay func(rawURL string) bool,
	relayReady func(ctx context.Context) bool,
) *HybridCapabilityBrowserBackend

NewHybridCapabilityBrowserBackend creates a hybrid browser router.

func (*HybridCapabilityBrowserBackend) AccessibilityTree

func (b *HybridCapabilityBrowserBackend) AccessibilityTree(ctx context.Context, targetID string, maxDepth int) (BrowserA11yTreeResult, error)

func (*HybridCapabilityBrowserBackend) ActByInteractiveRef

func (b *HybridCapabilityBrowserBackend) ActByInteractiveRef(ctx context.Context, targetID string, ref int, refMap map[int]string, action string, value string) error

func (*HybridCapabilityBrowserBackend) ActByRef

func (b *HybridCapabilityBrowserBackend) ActByRef(ctx context.Context, targetID string, ref int, refMap map[int]int, action string, value string) error

func (*HybridCapabilityBrowserBackend) ApplySessionState

func (b *HybridCapabilityBrowserBackend) ApplySessionState(ctx context.Context, targetID string, rawURL string, state SessionCoreState) error

func (*HybridCapabilityBrowserBackend) CaptureBrowserSessionMonitor

func (b *HybridCapabilityBrowserBackend) CaptureBrowserSessionMonitor(ctx context.Context, id string) (*browser.SessionMonitorResponse, error)

CaptureBrowserSessionMonitor captures either text or image monitor payloads.

func (*HybridCapabilityBrowserBackend) CaptureBrowserSessionScreenshot

func (b *HybridCapabilityBrowserBackend) CaptureBrowserSessionScreenshot(ctx context.Context, id string) (*browser.SessionScreenshotResponse, error)

CaptureBrowserSessionScreenshot preserves the legacy screenshot endpoint.

func (*HybridCapabilityBrowserBackend) CloseBrowserSession

func (b *HybridCapabilityBrowserBackend) CloseBrowserSession(ctx context.Context, id string) error

CloseBrowserSession closes an existing session.

func (*HybridCapabilityBrowserBackend) CloseTab

func (b *HybridCapabilityBrowserBackend) CloseTab(ctx context.Context, targetID string) error

func (*HybridCapabilityBrowserBackend) CookieHeader

func (b *HybridCapabilityBrowserBackend) CookieHeader(ctx context.Context, targetID string, rawURL string) (string, error)

func (*HybridCapabilityBrowserBackend) CountInteractiveElements

func (b *HybridCapabilityBrowserBackend) CountInteractiveElements(ctx context.Context, targetID string) (int, error)

func (*HybridCapabilityBrowserBackend) CreateBrowserSession

func (b *HybridCapabilityBrowserBackend) CreateBrowserSession(ctx context.Context) (*browser.SessionInfo, error)

CreateBrowserSession creates a Chromium-backed session for UI continuity.

func (*HybridCapabilityBrowserBackend) ExecuteRecipe

func (b *HybridCapabilityBrowserBackend) ExecuteRecipe(ctx context.Context, recipe string, params map[string]string) (BrowserRecipeResult, error)

func (*HybridCapabilityBrowserBackend) ExportSessionState

func (b *HybridCapabilityBrowserBackend) ExportSessionState(ctx context.Context, targetID string, rawURL string) (*SessionCoreState, error)

func (*HybridCapabilityBrowserBackend) ExtractText

func (b *HybridCapabilityBrowserBackend) ExtractText(ctx context.Context, targetID, selector string) (string, error)

func (*HybridCapabilityBrowserBackend) FocusTab

func (b *HybridCapabilityBrowserBackend) FocusTab(ctx context.Context, targetID string) error

func (*HybridCapabilityBrowserBackend) GetBrowserSession

func (b *HybridCapabilityBrowserBackend) GetBrowserSession(ctx context.Context, id string) (*browser.SessionInfo, error)

GetBrowserSession returns a single session summary.

func (*HybridCapabilityBrowserBackend) InteractiveElements

func (b *HybridCapabilityBrowserBackend) InteractiveElements(ctx context.Context, targetID string) (BrowserInteractiveResult, error)

func (*HybridCapabilityBrowserBackend) ListBrowserSessions

func (b *HybridCapabilityBrowserBackend) ListBrowserSessions(ctx context.Context) ([]browser.SessionInfo, error)

ListBrowserSessions aggregates sessions from Lightpanda and both Chromium runtimes.

func (*HybridCapabilityBrowserBackend) ListRecipes

func (*HybridCapabilityBrowserBackend) MirrorSessionState

func (b *HybridCapabilityBrowserBackend) MirrorSessionState(ctx context.Context, rawURL string, state SessionCoreState) error

func (*HybridCapabilityBrowserBackend) Navigate

func (b *HybridCapabilityBrowserBackend) Navigate(ctx context.Context, rawURL string, targetID string) (BrowserNavResult, error)

func (*HybridCapabilityBrowserBackend) NavigateBrowserSession

func (b *HybridCapabilityBrowserBackend) NavigateBrowserSession(ctx context.Context, id string, rawURL string) (*browser.NavigateResponse, error)

NavigateBrowserSession navigates within an existing session.

func (*HybridCapabilityBrowserBackend) ObserveNetwork

func (b *HybridCapabilityBrowserBackend) ObserveNetwork(ctx context.Context, targetID string, maxEntries int, clear bool) (BrowserObservedNetworkResult, error)

func (*HybridCapabilityBrowserBackend) PressKeys

func (b *HybridCapabilityBrowserBackend) PressKeys(ctx context.Context, targetID string, keys []string, holdMS int) error

func (*HybridCapabilityBrowserBackend) Screenshot

func (b *HybridCapabilityBrowserBackend) Screenshot(ctx context.Context, rawURL string) (string, error)

func (*HybridCapabilityBrowserBackend) ScreenshotTab

func (b *HybridCapabilityBrowserBackend) ScreenshotTab(ctx context.Context, targetID string) (string, error)

func (*HybridCapabilityBrowserBackend) Start

func (*HybridCapabilityBrowserBackend) Tabs

func (*HybridCapabilityBrowserBackend) UsesRelay

func (b *HybridCapabilityBrowserBackend) UsesRelay(ctx context.Context, targetID string) bool

UsesRelay reports whether the selected engine is relay/local Chrome.

func (*HybridCapabilityBrowserBackend) UsesRelayFor

func (b *HybridCapabilityBrowserBackend) UsesRelayFor(ctx context.Context, targetID, rawURL string) bool

UsesRelayFor reports whether the selected route for a URL will use relay/local Chrome.

func (*HybridCapabilityBrowserBackend) WaitNetworkIdle

func (b *HybridCapabilityBrowserBackend) WaitNetworkIdle(ctx context.Context, targetID string, idleMS int, timeoutMS int) error

type ImageAsset

type ImageAsset struct {
	URL           string `json:"url,omitempty"`
	ThumbnailURL  string `json:"thumbnail_url,omitempty"`
	RevisedPrompt string `json:"revised_prompt,omitempty"`
	ContentType   string `json:"content_type,omitempty"`
	Width         int    `json:"width,omitempty"`
	Height        int    `json:"height,omitempty"`
	DurationSec   int    `json:"duration_sec,omitempty"`
}

ImageAsset describes a generated image result.

type ImageCompatTool

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

ImageCompatTool exposes legacy image-generation aliases backed by the native image tool.

func (*ImageCompatTool) Definition

func (t *ImageCompatTool) Definition() ToolDefinition

func (*ImageCompatTool) Execute

func (t *ImageCompatTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type ImageGenerateFunc

type ImageGenerateFunc func(ctx context.Context, req ImageGenerateRequest) (*ImageTaskResult, error)

ImageGenerateFunc starts or waits on an image generation task.

type ImageGenerateRequest

type ImageGenerateRequest struct {
	Prompt               string
	NegativePrompt       string
	Model                string
	Size                 string
	Quality              string
	Style                string
	Category             string
	Count                int
	OutputPath           string
	ReferenceImageURL    string
	ReferenceImageBase64 string
	Extra                map[string]interface{}
	Wait                 bool
	WaitTimeout          time.Duration
}

ImageGenerateRequest is the normalized request shape used by the native image tool.

type ImageOCRResult

type ImageOCRResult struct {
	Text     string   `json:"text,omitempty"`
	Engine   string   `json:"engine,omitempty"`
	Model    string   `json:"model,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

ImageOCRResult is the normalized OCR output used by image fallback.

type ImageOCRService

type ImageOCRService interface {
	Extract(ctx context.Context, imagePNG []byte) (ImageOCRResult, error)
}

ImageOCRService extracts text from inline images as a local fallback.

type ImageReviewService

type ImageReviewService interface {
	Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)
}

ImageReviewService executes screenshot / URL review requests.

type ImageTaskLookupFunc

type ImageTaskLookupFunc func(ctx context.Context, taskID string) (*ImageTaskResult, error)

ImageTaskLookupFunc fetches the current state of a generation task.

type ImageTaskResult

type ImageTaskResult struct {
	ID        string                 `json:"id,omitempty"`
	Status    string                 `json:"status,omitempty"`
	Type      string                 `json:"type,omitempty"`
	Category  string                 `json:"category,omitempty"`
	Provider  string                 `json:"provider,omitempty"`
	Model     string                 `json:"model,omitempty"`
	Progress  float64                `json:"progress,omitempty"`
	Error     string                 `json:"error,omitempty"`
	Message   string                 `json:"message,omitempty"`
	CreatedAt time.Time              `json:"created_at,omitempty"`
	UpdatedAt time.Time              `json:"updated_at,omitempty"`
	Request   map[string]interface{} `json:"request,omitempty"`
	Outputs   []ImageAsset           `json:"outputs,omitempty"`
	Fallback  *MediaFallbackInfo     `json:"fallback_info,omitempty"`
}

ImageTaskResult is the normalized status/result payload for image generation.

type ImageTool

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

ImageTool provides a native compatibility surface for legacy image-style requests.

func NewImageTool

func NewImageTool(reviewer ImageReviewService, generate ImageGenerateFunc, lookup ImageTaskLookupFunc) *ImageTool

NewImageTool creates a new native image tool.

func (*ImageTool) Definition

func (t *ImageTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*ImageTool) Execute

func (t *ImageTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the requested image action.

func (*ImageTool) SetHTTPClient

func (t *ImageTool) SetHTTPClient(client *http.Client)

SetHTTPClient overrides the HTTP client used for remote direct-image downloads.

func (*ImageTool) SetOCRService

func (t *ImageTool) SetOCRService(svc ImageOCRService)

SetOCRService injects the local OCR fallback used for inline image recognition.

func (*ImageTool) SetPPTService

func (t *ImageTool) SetPPTService(svc PPTGenerateService)

SetPPTService injects the PPT slide-asset orchestration service.

func (*ImageTool) SetProviderVision

func (t *ImageTool) SetProviderVision(vision ProviderAwareImageVision)

SetProviderVision injects optional provider-aware image understanding.

func (*ImageTool) SetSmallModelEnabledFunc

func (t *ImageTool) SetSmallModelEnabledFunc(fn func() bool)

SetSmallModelEnabledFunc keeps legacy compatibility for callers that still provide small-model gates.

func (*ImageTool) SetSmallModelRuntime

func (t *ImageTool) SetSmallModelRuntime(rt smallmodel.Runtime)

SetSmallModelRuntime keeps legacy compatibility for callers that still provide a small-model runtime.

func (*ImageTool) SetVisionBridge

func (t *ImageTool) SetVisionBridge(bridge VLMBridge)

SetVisionBridge injects a generic vision model for raw image understanding.

type LLMBridge

type LLMBridge interface {
	Chat(ctx context.Context, prompt string, maxTokens int) (string, error)
}

LLMBridge defines the interface for making LLM calls from tools.

type LightpandaBinaryBrowserBackend

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

LightpandaBinaryBrowserBackend adapts the upstream Lightpanda binary into Blue's browser-lite session model.

func NewLightpandaBinaryBrowserBackend

func NewLightpandaBinaryBrowserBackend(runtime lightpandaBinaryRuntime) *LightpandaBinaryBrowserBackend

NewLightpandaBinaryBrowserBackend creates a browser-lite backend backed by a local upstream Lightpanda binary runtime.

func (*LightpandaBinaryBrowserBackend) AccessibilityTree

func (b *LightpandaBinaryBrowserBackend) AccessibilityTree(ctx context.Context, targetID string, maxDepth int) (BrowserA11yTreeResult, error)

func (*LightpandaBinaryBrowserBackend) ActByInteractiveRef

func (*LightpandaBinaryBrowserBackend) ActByRef

func (*LightpandaBinaryBrowserBackend) CaptureSessionMonitor

func (b *LightpandaBinaryBrowserBackend) CaptureSessionMonitor(ctx context.Context, targetID string) (*browser.SessionMonitorResponse, error)

func (*LightpandaBinaryBrowserBackend) CaptureSessionScreenshot

func (b *LightpandaBinaryBrowserBackend) CaptureSessionScreenshot(ctx context.Context, targetID string) (*browser.SessionScreenshotResponse, error)

func (*LightpandaBinaryBrowserBackend) CloseTab

func (b *LightpandaBinaryBrowserBackend) CloseTab(ctx context.Context, targetID string) error

func (*LightpandaBinaryBrowserBackend) CookieHeader

func (*LightpandaBinaryBrowserBackend) CountInteractiveElements

func (b *LightpandaBinaryBrowserBackend) CountInteractiveElements(ctx context.Context, targetID string) (int, error)

func (*LightpandaBinaryBrowserBackend) ExecuteRecipe

func (*LightpandaBinaryBrowserBackend) ExtractText

func (b *LightpandaBinaryBrowserBackend) ExtractText(ctx context.Context, targetID, selector string) (string, error)

func (*LightpandaBinaryBrowserBackend) FocusTab

func (b *LightpandaBinaryBrowserBackend) FocusTab(ctx context.Context, targetID string) error

func (*LightpandaBinaryBrowserBackend) GetSessionInfo

func (b *LightpandaBinaryBrowserBackend) GetSessionInfo(ctx context.Context, targetID string) (*browser.SessionInfo, error)

func (*LightpandaBinaryBrowserBackend) InteractiveElements

func (b *LightpandaBinaryBrowserBackend) InteractiveElements(ctx context.Context, targetID string) (BrowserInteractiveResult, error)

func (*LightpandaBinaryBrowserBackend) ListRecipes

func (*LightpandaBinaryBrowserBackend) ListSessionInfos

func (*LightpandaBinaryBrowserBackend) Navigate

func (*LightpandaBinaryBrowserBackend) ObserveNetwork

func (*LightpandaBinaryBrowserBackend) PressKeys

func (b *LightpandaBinaryBrowserBackend) PressKeys(ctx context.Context, targetID string, keys []string, holdMS int) error

func (*LightpandaBinaryBrowserBackend) Screenshot

func (*LightpandaBinaryBrowserBackend) ScreenshotTab

func (*LightpandaBinaryBrowserBackend) Start

func (*LightpandaBinaryBrowserBackend) Tabs

func (*LightpandaBinaryBrowserBackend) WaitNetworkIdle

type LocalCalendarService

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

LocalCalendarService stores events in SQLite.

func NewLocalCalendarService

func NewLocalCalendarService(db *sql.DB) (*LocalCalendarService, error)

NewLocalCalendarService creates the event table.

func NewLocalCalendarServiceWithReadDB

func NewLocalCalendarServiceWithReadDB(writeDB, readDB *sql.DB) (*LocalCalendarService, error)

NewLocalCalendarServiceWithReadDB creates the event table with separate write and read database handles.

func (*LocalCalendarService) Create

func (s *LocalCalendarService) Create(ctx context.Context, ownerID string, event CalendarEvent) (*CalendarEvent, error)

Create inserts a new event and returns the stored row.

func (*LocalCalendarService) Get

func (s *LocalCalendarService) Get(ctx context.Context, ownerID, id string) (*CalendarEvent, error)

Get fetches an event by ID.

func (*LocalCalendarService) List

List returns events for the user after applying filters.

func (*LocalCalendarService) SeedFixtures

func (s *LocalCalendarService) SeedFixtures(ctx context.Context, ownerID string, fixtures []CalendarEvent) error

SeedFixtures replaces an owner's events with the provided fixture set.

func (*LocalCalendarService) SetNowFunc

func (s *LocalCalendarService) SetNowFunc(fn func() time.Time)

SetNowFunc overrides the clock for deterministic tests.

func (*LocalCalendarService) Today

func (s *LocalCalendarService) Today(ctx context.Context, ownerID string, day time.Time) ([]CalendarEvent, error)

Today returns events overlapping the supplied day.

type LocalEmailService

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

LocalEmailService persists inbox messages in SQLite.

func NewLocalEmailService

func NewLocalEmailService(db *sql.DB) (*LocalEmailService, error)

NewLocalEmailService creates the email table and returns a local inbox service.

func NewLocalEmailServiceWithReadDB

func NewLocalEmailServiceWithReadDB(writeDB, readDB *sql.DB) (*LocalEmailService, error)

NewLocalEmailServiceWithReadDB creates the email table and returns a local inbox service with separate write and read database handles.

func (*LocalEmailService) Archive

func (s *LocalEmailService) Archive(ctx context.Context, ownerID, id string, archived bool) (*EmailMessage, error)

Archive toggles the archived flag for a message.

func (*LocalEmailService) Get

func (s *LocalEmailService) Get(ctx context.Context, ownerID, id string) (*EmailMessage, error)

Get retrieves a single message by ID.

func (*LocalEmailService) Label

func (s *LocalEmailService) Label(ctx context.Context, ownerID, id string, add, remove []string) (*EmailMessage, error)

Label adds/removes labels for a message and returns the updated row.

func (*LocalEmailService) List

func (s *LocalEmailService) List(ctx context.Context, ownerID string, opts EmailQueryOptions) ([]EmailMessage, error)

List returns messages for a user after applying search/filter options.

func (*LocalEmailService) SeedFixtures

func (s *LocalEmailService) SeedFixtures(ctx context.Context, ownerID string, fixtures []EmailMessage) error

SeedFixtures inserts an explicit fixture dataset for an owner.

func (*LocalEmailService) SetNowFunc

func (s *LocalEmailService) SetNowFunc(fn func() time.Time)

SetNowFunc overrides the clock, mainly for tests.

func (*LocalEmailService) Summarize

func (s *LocalEmailService) Summarize(ctx context.Context, ownerID string, opts EmailQueryOptions) (*EmailSummary, error)

Summarize returns a compact overview of the inbox slice described by opts.

type LsTool

type LsTool struct {
	Scope *fsToolScope
}

func NewLsTool

func NewLsTool(allowedPaths []string) *LsTool

func (*LsTool) Definition

func (t *LsTool) Definition() ToolDefinition

func (*LsTool) Execute

func (t *LsTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type MCPTool

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

MCPTool is a unified fallback dispatcher: - Prefer native built-in tool execution when available. - Fall back to existing executor behavior (unknown tool -> exec "blue <tool> ...").

func NewMCPTool

func NewMCPTool(registry *Registry) *MCPTool

NewMCPTool creates an MCP dispatcher bound to the given registry.

func (*MCPTool) Definition

func (t *MCPTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*MCPTool) Execute

func (t *MCPTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches to a target tool.

type MediaFallbackInfo

type MediaFallbackInfo struct {
	Used        bool     `json:"used"`
	Strategy    string   `json:"strategy"`
	DisplayName string   `json:"display_name"`
	SourceURLs  []string `json:"source_urls,omitempty"`
	SpaceURL    string   `json:"space_url,omitempty"`
	Disclosure  string   `json:"disclosure"`
	RenderMode  string   `json:"render_mode,omitempty"`
	TemplateID  string   `json:"template_id,omitempty"`
	StylePreset string   `json:"style_preset,omitempty"`
}

MediaFallbackInfo mirrors the backend fallback disclosure payload for native tool consumers.

type MemoryChunkResult

type MemoryChunkResult struct {
	ID        string
	Content   string
	Metadata  map[string]string
	CreatedAt time.Time
	UpdatedAt time.Time
}

MemoryChunkResult represents a memory chunk.

type MemoryCompatTool

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

MemoryCompatTool exposes legacy memory_* names as native wrappers.

func (*MemoryCompatTool) Definition

func (t *MemoryCompatTool) Definition() ToolDefinition

func (*MemoryCompatTool) Execute

func (t *MemoryCompatTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type MemorySearchResult

type MemorySearchResult struct {
	Chunk         MemoryChunkResult
	KeywordScore  float32
	CombinedScore float32
	MatchTypes    []string
}

MemorySearchResult represents a search result from memory service.

type MemoryServiceInterface

type MemoryServiceInterface interface {
	Recall(ctx context.Context, query string, limit int) ([]MemorySearchResult, error)
	Get(ctx context.Context, id string) (*MemoryChunkResult, error)
	Stats(ctx context.Context) (*MemoryStatsResult, error)
	Remember(ctx context.Context, content string, tags []string) (*MemoryChunkResult, error)
	Forget(ctx context.Context, id string) error
	GetActiveBackend() string
}

MemoryServiceInterface defines the interface for memory service used by tools. This avoids circular imports with the memory package.

type MemoryStatsResult

type MemoryStatsResult struct {
	TotalChunks    int
	TotalSizeBytes int64
	OldestChunk    string
	NewestChunk    string
	Backend        string
}

MemoryStatsResult represents memory statistics.

type MemoryTool

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

MemoryTool is a unified tool for memory operations: search, get, remember, forget, stats.

func GetMemoryTool

func GetMemoryTool(registry *Registry) *MemoryTool

GetMemoryTool retrieves the MemoryTool from the registry for dependency injection.

func NewMemoryTool

func NewMemoryTool(memoryService MemoryServiceInterface) *MemoryTool

NewMemoryTool creates a new unified memory tool.

func (*MemoryTool) Definition

func (m *MemoryTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*MemoryTool) Execute

func (m *MemoryTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches to the appropriate memory operation.

type MessageTool

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

MessageTool is a native compatibility wrapper around reminder/push delivery.

func NewMessageTool

func NewMessageTool(svc PushServiceInterface) *MessageTool

NewMessageTool creates a new message tool.

func (*MessageTool) Definition

func (t *MessageTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*MessageTool) Execute

func (t *MessageTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches message actions onto the push/reminder backend.

type MgmtTool

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

MgmtTool is the native config/admin tool for runtime system management. It provides a single entry point with action-based dispatch using dot notation (e.g. "providers.list", "settings.get").

func NewMgmtTool

func NewMgmtTool() *MgmtTool

NewMgmtTool creates a new management tool. Services are injected later via Set* methods.

func RegisterMgmtTool

func RegisterMgmtTool(registry *Registry) *MgmtTool

RegisterMgmtTool registers the management tool with the registry.

func (*MgmtTool) Definition

func (t *MgmtTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*MgmtTool) Execute

func (t *MgmtTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches to the appropriate handler based on the action parameter.

func (*MgmtTool) SetAPIKeys

func (t *MgmtTool) SetAPIKeys(svc AdminAPIKeyService)

func (*MgmtTool) SetChannels

func (t *MgmtTool) SetChannels(svc AdminChannelService)

func (*MgmtTool) SetProviders

func (t *MgmtTool) SetProviders(svc AdminProviderService)

func (*MgmtTool) SetProxy

func (t *MgmtTool) SetProxy(svc AdminProxyService)

func (*MgmtTool) SetSettings

func (t *MgmtTool) SetSettings(svc AdminSettingsService)

func (*MgmtTool) SetSkills

func (t *MgmtTool) SetSkills(svc AdminSkillService)

func (*MgmtTool) SetSystem

func (t *MgmtTool) SetSystem(svc AdminSystemService)

func (*MgmtTool) SetTools

func (t *MgmtTool) SetTools(svc AdminToolService)

func (*MgmtTool) SetUpgrade

func (t *MgmtTool) SetUpgrade(svc AdminUpgradeService)

func (*MgmtTool) SetUsers

func (t *MgmtTool) SetUsers(svc AdminUserService)

type MockTool

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

MockTool is a mock implementation of Tool for testing.

func NewMockTool

func NewMockTool(name, description string) *MockTool

NewMockTool creates a new mock tool.

func (*MockTool) Definition

func (m *MockTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*MockTool) Execute

func (m *MockTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs the mock tool.

func (*MockTool) SetDelay

func (m *MockTool) SetDelay(delay bool)

SetDelay sets whether Execute should wait for context cancellation.

func (*MockTool) SetError

func (m *MockTool) SetError(err error)

SetError sets the error to return from Execute.

func (*MockTool) SetResult

func (m *MockTool) SetResult(result interface{})

SetResult sets the result to return from Execute.

type NodesService

type NodesService interface {
	ListWorkflows(ctx context.Context, tenantID string, opts *workflow.ListOptions) ([]*workflow.Workflow, int, error)
	GetWorkflow(ctx context.Context, id string) (*workflow.Workflow, error)
	CreateWorkflow(ctx context.Context, workflow *workflow.Workflow) (*workflow.Workflow, error)
	UpdateWorkflow(ctx context.Context, workflow *workflow.Workflow) (*workflow.Workflow, error)
	DeleteWorkflow(ctx context.Context, id string) error
	ExecuteWorkflow(ctx context.Context, id string, triggerData map[string]interface{}) (*workflow.Execution, error)
	EnableWorkflow(ctx context.Context, id string) error
	DisableWorkflow(ctx context.Context, id string) error
	Templates(ctx context.Context) []workflow.WorkflowTemplateResponse
}

NodesService provides access to workflow/node management.

type NodesTool

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

NodesTool manages workflow graphs/nodes.

func NewNodesTool

func NewNodesTool(service NodesService) *NodesTool

NewNodesTool creates a native nodes tool.

func (*NodesTool) Definition

func (t *NodesTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*NodesTool) Execute

func (t *NodesTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the requested nodes action.

type OCRTool

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

func (*OCRTool) Definition

func (t *OCRTool) Definition() ToolDefinition

func (*OCRTool) Execute

func (t *OCRTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type OfficeTool

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

func NewOfficeTool

func NewOfficeTool(allowedPaths []string, approvals *ApprovalManager, dirStore *DirAllowlistStore) *OfficeTool

func (*OfficeTool) Definition

func (t *OfficeTool) Definition() ToolDefinition

func (*OfficeTool) Execute

func (t *OfficeTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type OutputBuffer

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

OutputBuffer is a capped ring buffer for process output.

func NewOutputBuffer

func NewOutputBuffer(cap int) *OutputBuffer

NewOutputBuffer creates a new output buffer with the given capacity.

func (*OutputBuffer) Append

func (b *OutputBuffer) Append(chunk string)

Append adds a chunk to the buffer, evicting old data if capacity is exceeded.

func (*OutputBuffer) Drain

func (b *OutputBuffer) Drain() string

Drain returns all buffered content and resets the buffer.

func (*OutputBuffer) Len

func (b *OutputBuffer) Len() int

Len returns the current buffer length.

func (*OutputBuffer) String

func (b *OutputBuffer) String() string

String returns all buffered content without draining.

func (*OutputBuffer) Tail

func (b *OutputBuffer) Tail(n int) string

Tail returns the last n characters of the buffer.

func (*OutputBuffer) Truncated

func (b *OutputBuffer) Truncated() bool

Truncated returns whether the buffer has been truncated.

type PDFService

PDFService provides PDF metadata and extraction support.

type PDFTool

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

PDFTool reads metadata and text from PDF documents.

func NewPDFTool

func NewPDFTool(service PDFService) *PDFTool

NewPDFTool creates a new PDF tool.

func (*PDFTool) Definition

func (t *PDFTool) Definition() ToolDefinition

Definition returns the PDF tool schema.

func (*PDFTool) Execute

func (t *PDFTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute performs the requested PDF action.

func (*PDFTool) SetHTTPClient

func (t *PDFTool) SetHTTPClient(client *http.Client)

SetHTTPClient overrides the HTTP client used for remote PDF downloads.

type PPTGenerateService

type PPTGenerateService interface {
	Generate(ctx context.Context, req PPTRequest) (*PPTResult, error)
}

PPTGenerateService orchestrates PPT slide-asset generation workflows.

type PPTRequest

type PPTRequest struct {
	Description       string   `json:"description,omitempty"`
	AspectRatio       string   `json:"aspect_ratio,omitempty"`
	ReferenceImages   []string `json:"reference_images,omitempty"`
	LayoutSpec        any      `json:"layout_spec,omitempty"`
	StylePreset       string   `json:"style_preset,omitempty"`
	Theme             string   `json:"style_theme,omitempty"`
	Source            string   `json:"source,omitempty"`
	ReviewThreshold   float64  `json:"review_threshold,omitempty"`
	ReviewRetryBudget int      `json:"review_retry_budget,omitempty"`
	QualityProfile    string   `json:"quality_profile,omitempty"`
	Lang              string   `json:"lang,omitempty"`
}

PPTRequest is the normalized PPT slide-asset request passed from tools to adapters.

type PPTResult

type PPTResult struct {
	Status         string      `json:"status,omitempty"`
	Skipped        bool        `json:"skipped,omitempty"`
	SkipReason     string      `json:"skip_reason,omitempty"`
	TaskID         string      `json:"task_id,omitempty"`
	Model          string      `json:"model,omitempty"`
	Mode           string      `json:"mode,omitempty"`
	FinalPrompt    string      `json:"final_prompt,omitempty"`
	ReviewScore    float64     `json:"review_score,omitempty"`
	ReviewSummary  string      `json:"review_summary,omitempty"`
	RetryCount     int         `json:"retry_count,omitempty"`
	ImageURLs      []string    `json:"image_urls,omitempty"`
	ThumbnailURLs  []string    `json:"thumbnail_urls,omitempty"`
	Review         interface{} `json:"review,omitempty"`
	UsedFallback   bool        `json:"used_fallback,omitempty"`
	QualityProfile string      `json:"quality_profile,omitempty"`
	StylePreset    string      `json:"style_preset,omitempty"`
	Source         string      `json:"source,omitempty"`
	Error          string      `json:"error,omitempty"`
	Threshold      float64     `json:"threshold,omitempty"`
	Description    string      `json:"description,omitempty"`
	ReferenceCount int         `json:"reference_count,omitempty"`
}

PPTResult is the normalized PPT slide-asset response shape returned by adapters.

type PPTTool

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

PPTTool exposes PPT slide-asset image orchestration.

func NewPPTTool

func NewPPTTool(service PPTGenerateService) *PPTTool

func (*PPTTool) Definition

func (t *PPTTool) Definition() ToolDefinition

func (*PPTTool) Execute

func (t *PPTTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type PPTXTool

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

func NewPPTXTool

func NewPPTXTool(allowedPaths []string, approvals *ApprovalManager, dirStore *DirAllowlistStore) *PPTXTool

func (*PPTXTool) Definition

func (t *PPTXTool) Definition() ToolDefinition

func (*PPTXTool) Execute

func (t *PPTXTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type PlanStep

type PlanStep struct {
	Kind     WebTaskKind `json:"kind"`
	Runtime  string      `json:"runtime"`
	Provider string      `json:"provider,omitempty"`
	Reason   string      `json:"reason,omitempty"`
}

type PolicyMode

type PolicyMode string

PolicyMode determines the enforcement level for exec commands.

const (
	// PolicyAudit logs all commands but does not block any (except Critical risk).
	PolicyAudit PolicyMode = "audit"
	// PolicyRestricted blocks high-risk commands, allows medium/low.
	PolicyRestricted PolicyMode = "restricted"
	// PolicyWorkspace only allows commands scoped to the project directory.
	PolicyWorkspace PolicyMode = "workspace"
	// PolicyFull allows all commands but still blocks Critical risk.
	PolicyFull PolicyMode = "full"
)

type ProcessSession

type ProcessSession struct {
	ID           string
	Command      string
	Workdir      string
	PID          int
	StartedAt    time.Time
	Stdout       *OutputBuffer
	Stderr       *OutputBuffer
	ExitCode     *int
	ExitSignal   string
	Status       ProcessStatus
	Backgrounded bool
}

ProcessSession represents a running or recently finished process.

type ProcessStatus

type ProcessStatus string

ProcessStatus represents the state of a process session.

const (
	ProcessRunning   ProcessStatus = "running"
	ProcessCompleted ProcessStatus = "completed"
	ProcessFailed    ProcessStatus = "failed"
	ProcessKilled    ProcessStatus = "killed"
)

type ProcessTool

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

ProcessTool implements the Tool interface for managing exec sessions.

func NewProcessTool

func NewProcessTool(sessions *SessionRegistry) *ProcessTool

NewProcessTool creates a new process management tool.

func (*ProcessTool) Definition

func (t *ProcessTool) Definition() ToolDefinition

Definition returns the tool definition for the LLM.

func (*ProcessTool) Execute

func (t *ProcessTool) Execute(_ context.Context, args map[string]interface{}) (interface{}, error)

Execute performs the requested process management action.

type ProviderAwareImageVision

type ProviderAwareImageVision interface {
	Analyze(ctx context.Context, prompt, imageBase64 string) (analysis string, handled bool, err error)
}

ProviderAwareImageVision optionally handles provider-specific image understanding.

func NewMiniMaxImageVision

func NewMiniMaxImageVision(pool *providerpool.Pool) ProviderAwareImageVision

NewMiniMaxImageVision creates a MiniMax-only direct image-understanding client.

type ProxyBridgeAdvisorAdapter

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

func NewProxyBridgeAdvisorAdapter

func NewProxyBridgeAdvisorAdapter(bridge *proxybridge.Bridge, pool *providerpool.Pool) *ProxyBridgeAdvisorAdapter

func (*ProxyBridgeAdvisorAdapter) AvailableCandidates

func (a *ProxyBridgeAdvisorAdapter) AvailableCandidates() []advisorModelCandidate

func (*ProxyBridgeAdvisorAdapter) Chat

type ProxyBridgeLLMAdapter

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

ProxyBridgeLLMAdapter adapts proxybridge.Bridge to the LLMBridge interface.

func NewProxyBridgeLLMAdapter

func NewProxyBridgeLLMAdapter(bridge *proxybridge.Bridge) *ProxyBridgeLLMAdapter

NewProxyBridgeLLMAdapter creates a new LLM adapter.

func (*ProxyBridgeLLMAdapter) Chat

func (a *ProxyBridgeLLMAdapter) Chat(ctx context.Context, prompt string, maxTokens int) (string, error)

type ProxyBridgeVLMAdapter

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

ProxyBridgeVLMAdapter adapts proxybridge.Bridge to the VLMBridge interface.

func NewProxyBridgeVLMAdapter

func NewProxyBridgeVLMAdapter(bridge *proxybridge.Bridge) *ProxyBridgeVLMAdapter

NewProxyBridgeVLMAdapter creates a new adapter.

func (*ProxyBridgeVLMAdapter) ChatWithVision

func (a *ProxyBridgeVLMAdapter) ChatWithVision(ctx context.Context, prompt string, imageBase64 string) (string, error)

type PushResult

type PushResult struct {
	ID        string     `json:"id"`
	Message   string     `json:"message"`
	FireAt    time.Time  `json:"fire_at"`
	Recurring string     `json:"recurring,omitempty"`
	UntilAt   *time.Time `json:"until_at,omitempty"`
	Status    string     `json:"status"`
	CreatedAt time.Time  `json:"created_at"`
}

PushResult is the data returned by the reminder delivery service.

type PushServiceInterface

type PushServiceInterface interface {
	Add(ctx context.Context, ownerID, message string, fireAt time.Time, recurring, sessionID string, untilAt *time.Time) (PushResult, error)
	List(ctx context.Context, ownerID string) ([]PushResult, error)
	Delete(ctx context.Context, ownerID, id string) error
	Clear(ctx context.Context, ownerID string) (int64, error)
}

PushServiceInterface defines the interface for the reminder delivery service. This avoids circular imports with the push package.

type PushTool

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

PushTool is a native tool for managing reminders.

func NewPushTool

func NewPushTool(svc PushServiceInterface) *PushTool

NewPushTool creates a new reminder tool.

func (*PushTool) Definition

func (t *PushTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*PushTool) Execute

func (t *PushTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches to the appropriate action.

type QuestionAnswerResult

type QuestionAnswerResult struct {
	QuestionID string   `json:"question_id"`
	Selected   []string `json:"selected"`             // selected option values
	OtherText  string   `json:"other_text,omitempty"` // free-text "Other" input
}

QuestionAnswerResult is the user's answer to one question.

type QuestionItem

type QuestionItem struct {
	ID          string           `json:"id"`
	Question    string           `json:"question"`
	Detail      string           `json:"detail,omitempty"` // optional extra detail shown with ❕ marker
	Header      string           `json:"header"`           // short tab label (max 12 chars)
	Options     []QuestionOption `json:"options,omitempty"`
	MultiSelect bool             `json:"multi_select,omitempty"`
}

QuestionItem describes a single question (one tab in the UI).

type QuestionManager

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

QuestionManager handles the ask-user-question flow via SSE.

func GetQuestionManager

func GetQuestionManager(registry *Registry) *QuestionManager

GetQuestionManager retrieves the QuestionManager via the registered tool.

func NewQuestionManager

func NewQuestionManager(broker *sse.Broker, silentFunc func() bool, timeout time.Duration) *QuestionManager

NewQuestionManager creates a new question manager.

func (*QuestionManager) AskQuestions

func (m *QuestionManager) AskQuestions(ctx context.Context, userID, sessionID string, questions []QuestionItem) ([]QuestionAnswerResult, bool, error)

AskQuestions sends questions to the user via SSE and blocks until answers arrive. In silent mode, returns default answers immediately (first option per question).

func (*QuestionManager) AskQuestionsWithContext

func (m *QuestionManager) AskQuestionsWithContext(ctx context.Context, userID, sessionID string, questions []QuestionItem, questionContext map[string]interface{}) ([]QuestionAnswerResult, bool, error)

AskQuestionsWithContext sends questions to the user via SSE with optional UI context payload. In silent mode, returns default answers immediately (first option per question).

func (*QuestionManager) CleanupExpired

func (m *QuestionManager) CleanupExpired() []string

CleanupExpired removes expired pending questions and returns removed request IDs.

func (*QuestionManager) DismissQuestion

func (m *QuestionManager) DismissQuestion(id string) bool

DismissQuestion is called when the user skips/dismisses a question. It sends default answers so the blocked AskQuestions call unblocks immediately.

func (*QuestionManager) GetPending

func (m *QuestionManager) GetPending(userID string) *QuestionRequest

GetPending returns the first pending QuestionRequest (if any). Used by the REST endpoint so the frontend can restore the dialog on page switch.

func (*QuestionManager) GetPendingByRun

func (m *QuestionManager) GetPendingByRun(runID string) *QuestionRequest

GetPendingByRun returns the most recent pending question request for a harness run.

func (*QuestionManager) GetPendingBySession

func (m *QuestionManager) GetPendingBySession(sessionID string) *QuestionRequest

GetPendingBySession returns the most recent pending QuestionRequest for sessionID. This is a fallback path when user-scoped matching is unavailable.

func (*QuestionManager) IsSilent

func (m *QuestionManager) IsSilent() bool

IsSilent returns true when unattended/silent mode is active.

func (*QuestionManager) PendingCount

func (m *QuestionManager) PendingCount() int

PendingCount returns the number of pending questions.

func (*QuestionManager) ResolveAnswer

func (m *QuestionManager) ResolveAnswer(id string, answers []QuestionAnswerResult) bool

ResolveAnswer is called by the REST endpoint when the user responds.

func (*QuestionManager) SetObserver

func (m *QuestionManager) SetObserver(observer RuntimeEventObserver)

SetObserver wires lifecycle notifications for question request/resolution.

func (*QuestionManager) SetSilentFunc

func (m *QuestionManager) SetSilentFunc(fn func() bool)

SetSilentFunc updates the silent mode function (for deferred wiring).

func (*QuestionManager) SetTimeoutActionFunc

func (m *QuestionManager) SetTimeoutActionFunc(fn func() string)

SetTimeoutActionFunc sets the timeout action getter. Supported values: - "default": return default answers on timeout (existing behavior) - "error": return timeout error

func (*QuestionManager) SetTimeoutFunc

func (m *QuestionManager) SetTimeoutFunc(fn func() time.Duration)

SetTimeoutFunc sets a dynamic timeout getter (takes precedence over static timeout when >0).

type QuestionOption

type QuestionOption struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	Value       string `json:"value,omitempty"` // defaults to label if empty
}

QuestionOption is a selectable option.

type QuestionRequest

type QuestionRequest struct {
	ID                    string                 `json:"id"`
	RunID                 string                 `json:"run_id,omitempty"`
	StepIndex             int                    `json:"step_index,omitempty"`
	Questions             []QuestionItem         `json:"questions"`
	UserID                string                 `json:"user_id"`
	SessionID             string                 `json:"session_id,omitempty"`
	ExpiresAt             int64                  `json:"expires_at"` // Unix ms, 0 means no auto-expiry
	RequireExplicitAnswer bool                   `json:"require_explicit_answer,omitempty"`
	Context               map[string]interface{} `json:"context,omitempty"`
}

QuestionRequest is the SSE payload sent to the frontend.

type QuestionRuntimeEvent

type QuestionRuntimeEvent struct {
	RunID     string                 `json:"run_id,omitempty"`
	StepIndex int                    `json:"step_index,omitempty"`
	ID        string                 `json:"id"`
	SessionID string                 `json:"session_id,omitempty"`
	UserID    string                 `json:"user_id,omitempty"`
	Questions []QuestionItem         `json:"questions,omitempty"`
	Answers   []QuestionAnswerResult `json:"answers,omitempty"`
	ExpiresAt int64                  `json:"expires_at,omitempty"`
	Context   map[string]interface{} `json:"context,omitempty"`
	Silent    bool                   `json:"silent,omitempty"`
	TimedOut  bool                   `json:"timed_out,omitempty"`
	Error     string                 `json:"error,omitempty"`
}

type Registry

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

Registry manages registered tools.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new tool registry.

func (*Registry) Definitions

func (r *Registry) Definitions() []ToolDefinition

Definitions returns all tool definitions sorted by name.

func (*Registry) DefinitionsForLocale

func (r *Registry) DefinitionsForLocale(locale string) []ToolDefinition

DefinitionsForLocale returns tool definitions with lang/locale parameter examples adjusted to the user's current locale.

func (*Registry) DefinitionsForRoute

func (r *Registry) DefinitionsForRoute(kind ToolRouteKind) []ToolDefinition

DefinitionsForRoute returns visible tool definitions for the given runtime route.

func (*Registry) DefinitionsForRouteAndLocale

func (r *Registry) DefinitionsForRouteAndLocale(kind ToolRouteKind, locale string) []ToolDefinition

DefinitionsForRouteAndLocale returns visible tool definitions for the given runtime route with locale-aware schema examples.

func (*Registry) Disable

func (r *Registry) Disable(name string) bool

Disable moves a tool from active to disabled. Disabled tools are hidden from Definitions() and List() (not sent to LLM) but still accessible via Get().

func (*Registry) Enable

func (r *Registry) Enable(name string) bool

Enable moves a tool from disabled back to active.

func (*Registry) ExposeDefinition

func (r *Registry) ExposeDefinition(def ToolDefinition)

ExposeDefinition registers a tool definition that is visible to the model/UI but is not backed by a native Tool implementation in this registry.

func (*Registry) Get

func (r *Registry) Get(name string) Tool

Get retrieves a tool by name. Returns both active and disabled tools.

func (*Registry) IsDisabled

func (r *Registry) IsDisabled(name string) bool

IsDisabled returns true if the tool exists but is disabled.

func (*Registry) List

func (r *Registry) List() []string

List returns all active (enabled) tool names sorted alphabetically.

func (*Registry) ListDisabled

func (r *Registry) ListDisabled() []string

ListDisabled returns all disabled tool names sorted alphabetically.

func (*Registry) LookupDefinition

func (r *Registry) LookupDefinition(name string) (ToolDefinition, bool)

LookupDefinition returns the visible tool definition for a tool name.

func (*Registry) LookupDefinitionForRoute

func (r *Registry) LookupDefinitionForRoute(name string, kind ToolRouteKind) (ToolDefinition, bool)

LookupDefinitionForRoute returns the visible tool definition for a tool name scoped to a runtime route.

func (*Registry) Register

func (r *Registry) Register(tool Tool)

Register adds a tool to the registry.

func (*Registry) Version

func (r *Registry) Version() uint64

Version returns the current mutation version of the registry. It increments on every Register, ExposeDefinition, Disable, or Enable call.

type ResearchBudget

type ResearchBudget struct {
	MaxSources int
	MaxSeconds int
}

type ResearchCreateJobRequest

type ResearchCreateJobRequest struct {
	Query            string
	Mode             string
	ResearchDepth    string
	RouteMode        string
	RetrievalProfile string
	Lang             string
	Budget           *ResearchBudget
	StrictEntity     *bool
	TimeWindows      []string
	ReportStyle      string
	Topic            string
	URLs             []string
	Text             string
	SearchQueries    []string
	OutputMode       string
	Question         string
	Category         string
	DecisionMode     string
	Candidates       []string
	Context          map[string]interface{}
	Constraints      map[string]interface{}
	Grounding        string
	Depth            string
	Output           string
	ScorecardPack    string
	ScorecardWeights map[string]float64
	Action           string
	URL              string
	Image            string
	Device           string
	Channel          string
	WaitMS           int
	Threshold        float64
	Format           string
	Profile          string
	UserID           string
	ConversationID   string
}

type ResearchJob

type ResearchJob struct {
	ID                 string
	ConversationID     string
	Status             string
	Query              string
	Mode               string
	ResearchDepth      string
	RetrievalProfile   string
	RequestedRouteMode string
	EffectiveRouteMode string
	RouteReason        string
	Progress           int
	EvidenceCount      int
	Answer             string
	Confidence         float64
	Error              string
	Report             map[string]interface{}
}

type ResearchRunTool

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

func NewResearchRunTool

func NewResearchRunTool(service ResearchService) *ResearchRunTool

func (*ResearchRunTool) Definition

func (t *ResearchRunTool) Definition() ToolDefinition

func (*ResearchRunTool) Execute

func (t *ResearchRunTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type ResearchService

type ResearchService interface {
	CreateJob(ctx context.Context, req ResearchCreateJobRequest) (*ResearchJob, error)
	GetJobForUser(id, userID string) (*ResearchJob, error)
}

type ResearchStatusTool

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

func NewResearchStatusTool

func NewResearchStatusTool(service ResearchService) *ResearchStatusTool

func (*ResearchStatusTool) Definition

func (t *ResearchStatusTool) Definition() ToolDefinition

func (*ResearchStatusTool) Execute

func (t *ResearchStatusTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

type RetryLimitError

type RetryLimitError struct {
	Command string
	Count   int
	Max     int
	LastErr string
}

RetryLimitError is returned when a command has been retried too many times.

func (*RetryLimitError) Error

func (e *RetryLimitError) Error() string

type RetryTracker

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

RetryTracker prevents the LLM from retrying the same failing command in a tight loop. It tracks normalized command strings within a time window.

func NewRetryTracker

func NewRetryTracker(maxRetries int, window time.Duration) *RetryTracker

NewRetryTracker creates a new retry tracker.

func (*RetryTracker) Check

func (rt *RetryTracker) Check(normalizedCmd string) error

Check returns an error if the command has been retried too many times within the window. Call Record() after execution to track it.

func (*RetryTracker) Record

func (rt *RetryTracker) Record(normalizedCmd string, failed bool, errMsg string)

Record tracks a command execution. Only call for failed commands (successful commands reset the counter).

type RipgrepManager

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

func NewRipgrepManager

func NewRipgrepManager(cfg config.ToolCallingRipgrepConfig, dataDir string) (*RipgrepManager, error)

func (*RipgrepManager) Resolve

func (m *RipgrepManager) Resolve(ctx context.Context) (*ripgrepBinary, error)

type RiskCategory

type RiskCategory string

RiskCategory classifies the type of risk a command poses.

const (
	RiskDestructive RiskCategory = "destructive"
	RiskPrivilege   RiskCategory = "privilege"
	RiskNetwork     RiskCategory = "network"
	RiskPersistence RiskCategory = "persistence"
	RiskSystem      RiskCategory = "system"
)

type RiskLevel

type RiskLevel string

RiskLevel is a human-readable risk classification.

const (
	RiskLevelLow      RiskLevel = "low"
	RiskLevelMedium   RiskLevel = "medium"
	RiskLevelHigh     RiskLevel = "high"
	RiskLevelCritical RiskLevel = "critical"
)

type RiskScore

type RiskScore struct {
	Total       int       `json:"total"`
	Destructive int       `json:"destructive"`
	Privilege   int       `json:"privilege"`
	Network     int       `json:"network"`
	Persistence int       `json:"persistence"`
	System      int       `json:"system"`
	Reasons     []string  `json:"reasons"`
	Level       RiskLevel `json:"level"`
}

RiskScore is the result of analyzing a command's risk profile.

func AnalyzeRisk

func AnalyzeRisk(command string) RiskScore

AnalyzeRisk scores a command string against the risk rules. Scores are additive but capped per category to avoid double-counting.

func AnalyzeRiskWithSuppressedReasons

func AnalyzeRiskWithSuppressedReasons(command string, suppressedReasons []string) RiskScore

AnalyzeRiskWithSuppressedReasons scores a command while omitting selected risk reasons that have already been explicitly approved at runtime.

type RodBrowserAdapter

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

RodBrowserAdapter adapts browser.RodService to the UIReviewBrowser interface. Supports lazy initialization via a resolve function.

func NewLazyRodBrowserAdapter

func NewLazyRodBrowserAdapter(resolve func() *browser.RodService) *RodBrowserAdapter

NewLazyRodBrowserAdapter creates a lazy adapter that resolves the service on demand.

func NewLeaseAwareRodBrowserAdapter

func NewLeaseAwareRodBrowserAdapter(acquire rodServiceAcquireFunc) *RodBrowserAdapter

NewLeaseAwareRodBrowserAdapter creates a lazy adapter that keeps a managed browser instance alive for the duration of each UI review call.

func NewRodBrowserAdapter

func NewRodBrowserAdapter(svc *browser.RodService) *RodBrowserAdapter

NewRodBrowserAdapter creates a new adapter with a direct service reference.

func (*RodBrowserAdapter) CloseTab

func (a *RodBrowserAdapter) CloseTab(ctx context.Context, targetID string) error

func (*RodBrowserAdapter) GetAccessibilityTree

func (a *RodBrowserAdapter) GetAccessibilityTree(ctx context.Context, targetID string, maxDepth int) (UIReviewA11yResult, error)

func (*RodBrowserAdapter) NavigateURL

func (a *RodBrowserAdapter) NavigateURL(ctx context.Context, url string) (UIReviewNavResult, error)

func (*RodBrowserAdapter) PageDimensions

func (a *RodBrowserAdapter) PageDimensions(ctx context.Context, targetID string) (int, int, error)

func (*RodBrowserAdapter) ScreenshotTab

func (a *RodBrowserAdapter) ScreenshotTab(ctx context.Context, targetID string) (string, error)

func (*RodBrowserAdapter) ScreenshotViewportRaw

func (a *RodBrowserAdapter) ScreenshotViewportRaw(ctx context.Context, targetID string) ([]byte, error)

func (*RodBrowserAdapter) ScrollTo

func (a *RodBrowserAdapter) ScrollTo(ctx context.Context, targetID string, x, y int) error

func (*RodBrowserAdapter) SetViewport

func (a *RodBrowserAdapter) SetViewport(ctx context.Context, targetID string, width, height int) error

func (*RodBrowserAdapter) Start

func (a *RodBrowserAdapter) Start(ctx context.Context) error

type RodBrowserBackend

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

RodBrowserBackend adapts browser.RodService to the BrowserBackend interface. Supports lazy initialization and mode-aware routing via context.

func NewLazyRodBrowserBackend

func NewLazyRodBrowserBackend(resolve func() *browser.RodService) *RodBrowserBackend

NewLazyRodBrowserBackend creates a lazy adapter that resolves the default service on demand.

func NewLeaseAwareRodBrowserBackend

func NewLeaseAwareRodBrowserBackend(acquireDefault, acquireVisible rodServiceAcquireFunc) *RodBrowserBackend

NewLeaseAwareRodBrowserBackend creates an adapter that keeps a managed browser instance alive for the duration of each backend call.

func NewModeAwareRodBrowserBackend

func NewModeAwareRodBrowserBackend(resolveDefault, resolveVisible func() *browser.RodService) *RodBrowserBackend

NewModeAwareRodBrowserBackend creates an adapter that can route requests to different browser services based on per-request context or tab affinity.

func NewPeekLeaseAwareRodBrowserBackend

func NewPeekLeaseAwareRodBrowserBackend(
	resolveDefault func() *browser.RodService,
	acquireDefault rodServiceAcquireFunc,
	resolveVisible func() *browser.RodService,
	acquireVisible rodServiceAcquireFunc,
) *RodBrowserBackend

NewPeekLeaseAwareRodBrowserBackend creates an adapter that can both peek at live services without warming them and acquire leases for active work.

func NewRodBrowserBackend

func NewRodBrowserBackend(svc *browser.RodService) *RodBrowserBackend

NewRodBrowserBackend creates a new adapter with a direct service reference.

func (*RodBrowserBackend) AccessibilityTree

func (a *RodBrowserBackend) AccessibilityTree(ctx context.Context, targetID string, maxDepth int) (BrowserA11yTreeResult, error)

func (*RodBrowserBackend) ActByInteractiveRef

func (a *RodBrowserBackend) ActByInteractiveRef(ctx context.Context, targetID string, ref int, refMap map[int]string, action string, value string) error

func (*RodBrowserBackend) ActByRef

func (a *RodBrowserBackend) ActByRef(ctx context.Context, targetID string, ref int, refMap map[int]int, action string, value string) error

func (*RodBrowserBackend) ApplySessionState

func (a *RodBrowserBackend) ApplySessionState(ctx context.Context, targetID string, rawURL string, state SessionCoreState) error

func (*RodBrowserBackend) CaptureSessionMonitor

func (a *RodBrowserBackend) CaptureSessionMonitor(ctx context.Context, targetID string) (*browser.SessionMonitorResponse, error)

CaptureSessionMonitor returns the screenshot-based monitor payload for a Chromium session.

func (*RodBrowserBackend) CaptureSessionScreenshot

func (a *RodBrowserBackend) CaptureSessionScreenshot(ctx context.Context, targetID string) (*browser.SessionScreenshotResponse, error)

CaptureSessionScreenshot returns the legacy screenshot compatibility payload.

func (*RodBrowserBackend) CloseTab

func (a *RodBrowserBackend) CloseTab(ctx context.Context, targetID string) error

func (*RodBrowserBackend) CookieHeader

func (a *RodBrowserBackend) CookieHeader(ctx context.Context, targetID string, url string) (string, error)

func (*RodBrowserBackend) CountInteractiveElements

func (a *RodBrowserBackend) CountInteractiveElements(ctx context.Context, targetID string) (int, error)

func (*RodBrowserBackend) ExecuteRecipe

func (a *RodBrowserBackend) ExecuteRecipe(ctx context.Context, recipe string, params map[string]string) (BrowserRecipeResult, error)

func (*RodBrowserBackend) ExportSessionState

func (a *RodBrowserBackend) ExportSessionState(ctx context.Context, targetID string, rawURL string) (*SessionCoreState, error)

func (*RodBrowserBackend) ExtractText

func (a *RodBrowserBackend) ExtractText(ctx context.Context, targetID, selector string) (string, error)

func (*RodBrowserBackend) FocusTab

func (a *RodBrowserBackend) FocusTab(ctx context.Context, targetID string) error

func (*RodBrowserBackend) GetSessionInfo

func (a *RodBrowserBackend) GetSessionInfo(ctx context.Context, targetID string) (*browser.SessionInfo, error)

GetSessionInfo returns a single Chromium session summary.

func (*RodBrowserBackend) InteractiveElements

func (a *RodBrowserBackend) InteractiveElements(ctx context.Context, targetID string) (BrowserInteractiveResult, error)

func (*RodBrowserBackend) ListRecipes

func (a *RodBrowserBackend) ListRecipes(ctx context.Context) []BrowserRecipeInfo

func (*RodBrowserBackend) ListSessionInfos

func (a *RodBrowserBackend) ListSessionInfos(ctx context.Context) ([]browser.SessionInfo, error)

ListSessionInfos returns active Chromium sessions without warming cold runtimes.

func (*RodBrowserBackend) Navigate

func (a *RodBrowserBackend) Navigate(ctx context.Context, url string, targetID string) (BrowserNavResult, error)

func (*RodBrowserBackend) ObserveNetwork

func (a *RodBrowserBackend) ObserveNetwork(ctx context.Context, targetID string, maxEntries int, clear bool) (BrowserObservedNetworkResult, error)

func (*RodBrowserBackend) PressKeys

func (a *RodBrowserBackend) PressKeys(ctx context.Context, targetID string, keys []string, holdMS int) error

func (*RodBrowserBackend) Screenshot

func (a *RodBrowserBackend) Screenshot(ctx context.Context, url string) (string, error)

func (*RodBrowserBackend) ScreenshotTab

func (a *RodBrowserBackend) ScreenshotTab(ctx context.Context, targetID string) (string, error)

func (*RodBrowserBackend) Start

func (a *RodBrowserBackend) Start(ctx context.Context) error

func (*RodBrowserBackend) Tabs

func (*RodBrowserBackend) UsesRelay

func (a *RodBrowserBackend) UsesRelay(ctx context.Context, targetID string) bool

UsesRelay reports whether the selected browser service is running in relay/CDP attach mode.

func (*RodBrowserBackend) WaitNetworkIdle

func (a *RodBrowserBackend) WaitNetworkIdle(ctx context.Context, targetID string, idleMS int, timeoutMS int) error

type RuntimeEventObserver

type RuntimeEventObserver interface {
	OnToolRequested(event ToolRuntimeEvent)
	OnToolFinished(event ToolRuntimeEvent)
	OnApprovalRequested(event ApprovalRuntimeEvent)
	OnApprovalResolved(event ApprovalRuntimeEvent)
	OnQuestionRequested(event QuestionRuntimeEvent)
	OnQuestionResolved(event QuestionRuntimeEvent)
}

RuntimeEventObserver receives normalized runtime lifecycle notifications. Implementations may ignore events that do not belong to a tracked run.

type RuntimeExecutor

type RuntimeExecutor interface {
	ExecuteStep(context.Context, PlanStep, WebTask) (any, error)
}

type RuntimeSessionActionHandler

type RuntimeSessionActionHandler interface {
	HandleRuntimeSessionAction(ctx context.Context, action string, args map[string]interface{}) (interface{}, error)
}

RuntimeSessionActionHandler optionally routes explicit runtime-aware session requests to the external agent sessions control plane.

type SandboxExecutor

type SandboxExecutor interface {
	// RunInSandbox executes a shell command in an isolated environment.
	// Returns stdout, stderr, exit code, and any error.
	RunInSandbox(ctx context.Context, command, workdir string, env map[string]string, timeout time.Duration) (stdout, stderr string, exitCode int, err error)
}

SandboxExecutor is the interface for sandbox execution, decoupled from the sandbox package to avoid pulling in heavy transitive dependencies.

type SandboxTier

type SandboxTier string

SandboxTier describes the isolation level selected for a sandboxed exec.

const (
	SandboxTierLight  SandboxTier = "light"
	SandboxTierStrong SandboxTier = "strong"
)

type SearchProvider

type SearchProvider interface {
	Name() string
	Search(ctx context.Context, query string, maxResults int, region string) (*WebSearchResponse, error)
}

type SessionCoreState

type SessionCoreState struct {
	ID             string                       `json:"id"`
	UserAgent      string                       `json:"user_agent,omitempty"`
	Headers        map[string]string            `json:"headers,omitempty"`
	Cookies        []browser.Cookie             `json:"cookies,omitempty"`
	LocalStorage   map[string]map[string]string `json:"local_storage,omitempty"`
	SessionStorage map[string]map[string]string `json:"session_storage,omitempty"`
	PrimaryRuntime string                       `json:"primary_runtime,omitempty"`
	MirrorTargets  []string                     `json:"mirror_targets,omitempty"`
	UpdatedAt      time.Time                    `json:"updated_at,omitempty"`
}

type SessionMessage

type SessionMessage struct {
	ID         string    `json:"id"`
	Role       string    `json:"role"`
	Content    string    `json:"content"`
	ToolCallID string    `json:"tool_call_id,omitempty"`
	ToolName   string    `json:"tool_name,omitempty"`
	Provider   string    `json:"provider,omitempty"`
	Model      string    `json:"model,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
}

SessionMessage is the normalized message view used by session tools.

type SessionRegistry

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

SessionRegistry manages running and finished process sessions.

func NewSessionRegistry

func NewSessionRegistry() *SessionRegistry

NewSessionRegistry creates a new session registry with a background sweeper.

func (*SessionRegistry) Add

func (r *SessionRegistry) Add(s *ProcessSession)

Add registers a new running session.

func (*SessionRegistry) Cleanup

func (r *SessionRegistry) Cleanup()

Cleanup stops the sweeper and clears all sessions.

func (*SessionRegistry) Delete

func (r *SessionRegistry) Delete(id string)

Delete removes a session from both running and finished maps.

func (*SessionRegistry) Get

Get retrieves a running session by ID.

func (*SessionRegistry) GetFinished

func (r *SessionRegistry) GetFinished(id string) *FinishedSession

GetFinished retrieves a finished session by ID.

func (*SessionRegistry) ListFinished

func (r *SessionRegistry) ListFinished() []*FinishedSession

ListFinished returns all finished sessions.

func (*SessionRegistry) ListRunning

func (r *SessionRegistry) ListRunning() []*ProcessSession

ListRunning returns all running sessions.

func (*SessionRegistry) MarkBackgrounded

func (r *SessionRegistry) MarkBackgrounded(id string)

MarkBackgrounded marks a session as backgrounded.

func (*SessionRegistry) MarkExited

func (r *SessionRegistry) MarkExited(id string, exitCode *int, exitSignal string, status ProcessStatus)

MarkExited transitions a running session to finished.

type SessionStatusTool

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

SessionStatusTool reads current session metadata.

func NewSessionStatusTool

func NewSessionStatusTool(service SessionsService) *SessionStatusTool

NewSessionStatusTool creates a native session_status tool.

func (*SessionStatusTool) Definition

func (t *SessionStatusTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*SessionStatusTool) Execute

func (t *SessionStatusTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute returns summary metadata and recent messages for a session.

type SessionSummary

type SessionSummary struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	UserID    string    `json:"user_id,omitempty"`
	Pinned    bool      `json:"pinned"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

SessionSummary is the normalized lightweight session view exposed to tools.

type SessionsHistoryTool

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

SessionsHistoryTool reads session history.

func NewSessionsHistoryTool

func NewSessionsHistoryTool(service SessionsService) *SessionsHistoryTool

NewSessionsHistoryTool creates a native sessions_history tool.

func (*SessionsHistoryTool) Definition

func (t *SessionsHistoryTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*SessionsHistoryTool) Execute

func (t *SessionsHistoryTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute returns recent messages for a session.

type SessionsListTool

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

SessionsListTool lists recent sessions/conversations.

func NewSessionsListTool

func NewSessionsListTool(service SessionsService) *SessionsListTool

NewSessionsListTool creates a native sessions_list tool.

func (*SessionsListTool) Definition

func (t *SessionsListTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*SessionsListTool) Execute

func (t *SessionsListTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute returns recent sessions.

type SessionsSendTool

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

SessionsSendTool appends a message to an existing session.

func NewSessionsSendTool

func NewSessionsSendTool(service SessionsService) *SessionsSendTool

NewSessionsSendTool creates a native sessions_send tool.

func (*SessionsSendTool) Definition

func (t *SessionsSendTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*SessionsSendTool) Execute

func (t *SessionsSendTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute appends a message to an existing session.

type SessionsService

type SessionsService interface {
	ListSessions(ctx context.Context, limit, offset int, userID string) ([]SessionSummary, error)
	GetSession(ctx context.Context, sessionID string) (*SessionSummary, error)
	GetSessionMessages(ctx context.Context, sessionID string, limit, offset int) ([]SessionMessage, error)
	CreateSession(ctx context.Context, title, userID string, pinned bool) (*SessionSummary, error)
	AppendSessionMessage(ctx context.Context, sessionID string, msg SessionMessage) (*SessionMessage, error)
}

SessionsService provides list/read/write access without importing the memory package.

type SessionsSpawnTool

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

SessionsSpawnTool creates a new session.

func NewSessionsSpawnTool

func NewSessionsSpawnTool(service SessionsService) *SessionsSpawnTool

NewSessionsSpawnTool creates a native sessions_spawn tool.

func (*SessionsSpawnTool) Definition

func (t *SessionsSpawnTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*SessionsSpawnTool) Execute

func (t *SessionsSpawnTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute creates a new session.

type SessionsTool

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

SessionsTool provides a unified action-based surface for session operations.

func NewSessionsTool

func NewSessionsTool(service SessionsService) *SessionsTool

NewSessionsTool creates a unified sessions tool.

func (*SessionsTool) Definition

func (t *SessionsTool) Definition() ToolDefinition

Definition returns the unified sessions tool schema.

func (*SessionsTool) Execute

func (t *SessionsTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches to the appropriate session action.

type SitePolicyBrowserBackend

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

SitePolicyBrowserBackend routes browser actions between the default browser backend and optional managed/relay alternates using a URL policy.

func NewSitePolicyBrowserBackend

func NewSitePolicyBrowserBackend(defaultBackend, managedBackend, relayBackend BrowserBackend, preferRelay func(rawURL string) bool, fallbackDriver string) *SitePolicyBrowserBackend

NewSitePolicyBrowserBackend wraps browser backends with per-site relay preference.

func (*SitePolicyBrowserBackend) AccessibilityTree

func (b *SitePolicyBrowserBackend) AccessibilityTree(ctx context.Context, targetID string, maxDepth int) (BrowserA11yTreeResult, error)

func (*SitePolicyBrowserBackend) ActByInteractiveRef

func (b *SitePolicyBrowserBackend) ActByInteractiveRef(ctx context.Context, targetID string, ref int, refMap map[int]string, action string, value string) error

func (*SitePolicyBrowserBackend) ActByRef

func (b *SitePolicyBrowserBackend) ActByRef(ctx context.Context, targetID string, ref int, refMap map[int]int, action string, value string) error

func (*SitePolicyBrowserBackend) CloseTab

func (b *SitePolicyBrowserBackend) CloseTab(ctx context.Context, targetID string) error

func (*SitePolicyBrowserBackend) CookieHeader

func (b *SitePolicyBrowserBackend) CookieHeader(ctx context.Context, targetID string, rawURL string) (string, error)

func (*SitePolicyBrowserBackend) CountInteractiveElements

func (b *SitePolicyBrowserBackend) CountInteractiveElements(ctx context.Context, targetID string) (int, error)

func (*SitePolicyBrowserBackend) ExecuteRecipe

func (b *SitePolicyBrowserBackend) ExecuteRecipe(ctx context.Context, recipe string, params map[string]string) (BrowserRecipeResult, error)

func (*SitePolicyBrowserBackend) ExtractText

func (b *SitePolicyBrowserBackend) ExtractText(ctx context.Context, targetID, selector string) (string, error)

func (*SitePolicyBrowserBackend) FocusTab

func (b *SitePolicyBrowserBackend) FocusTab(ctx context.Context, targetID string) error

func (*SitePolicyBrowserBackend) InteractiveElements

func (b *SitePolicyBrowserBackend) InteractiveElements(ctx context.Context, targetID string) (BrowserInteractiveResult, error)

func (*SitePolicyBrowserBackend) ListRecipes

func (*SitePolicyBrowserBackend) Navigate

func (b *SitePolicyBrowserBackend) Navigate(ctx context.Context, rawURL string, targetID string) (BrowserNavResult, error)

func (*SitePolicyBrowserBackend) ObserveNetwork

func (b *SitePolicyBrowserBackend) ObserveNetwork(ctx context.Context, targetID string, maxEntries int, clear bool) (BrowserObservedNetworkResult, error)

func (*SitePolicyBrowserBackend) PressKeys

func (b *SitePolicyBrowserBackend) PressKeys(ctx context.Context, targetID string, keys []string, holdMS int) error

func (*SitePolicyBrowserBackend) Screenshot

func (b *SitePolicyBrowserBackend) Screenshot(ctx context.Context, rawURL string) (string, error)

func (*SitePolicyBrowserBackend) ScreenshotTab

func (b *SitePolicyBrowserBackend) ScreenshotTab(ctx context.Context, targetID string) (string, error)

func (*SitePolicyBrowserBackend) Start

func (*SitePolicyBrowserBackend) Tabs

func (*SitePolicyBrowserBackend) UsesRelay

func (b *SitePolicyBrowserBackend) UsesRelay(ctx context.Context, targetID string) bool

func (*SitePolicyBrowserBackend) UsesRelayFor

func (b *SitePolicyBrowserBackend) UsesRelayFor(ctx context.Context, targetID, rawURL string) bool

func (*SitePolicyBrowserBackend) WaitNetworkIdle

func (b *SitePolicyBrowserBackend) WaitNetworkIdle(ctx context.Context, targetID string, idleMS int, timeoutMS int) error

type SkillExecFunc

type SkillExecFunc func(ctx context.Context, skillID string, input map[string]any) (map[string]string, error)

SkillExecFunc executes a skill by ID with the given input. Returns (map[string]string, error) matching the IPC SkillExecutor interface.

type SkillSelectFunc

type SkillSelectFunc func(ctx context.Context, query string) SkillSelectionDecision

SkillSelectFunc is called when exec receives an unknown/disabled skill command.

type SkillSelectionDecision

type SkillSelectionDecision struct {
	SelectedSkill string
	Confidence    float64
	NeedClarify   bool
	Candidates    []string
	Reason        string
}

SkillSelectionDecision is the lightweight selector output consumed by exec fallback.

type SkillToolAdapter

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

SkillToolAdapter wraps a skill.Skill as a tools.Tool so the LLM can call it.

func NewSkillToolAdapter

func NewSkillToolAdapter(s skill.Skill) *SkillToolAdapter

NewSkillToolAdapter creates a Tool that delegates to the given Skill.

func (*SkillToolAdapter) Definition

func (a *SkillToolAdapter) Definition() ToolDefinition

Definition converts the skill manifest into a ToolDefinition.

func (*SkillToolAdapter) Execute

func (a *SkillToolAdapter) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute delegates to the underlying skill and returns JSON.

type SmallModelStatsRecorder

type SmallModelStatsRecorder interface {
	RecordDocExtractAttempt()
	RecordDocExtractSuccess()
	RecordLatency(time.Duration)
	RecordLatencyWithScene(string, time.Duration)
	RecordFallback(reason string)
	RecordAutoRollback()
}

SmallModelStatsRecorder records small-model scene-level observability counters.

type SubagentExecutor

type SubagentExecutor interface {
	ExecuteSubagent(ctx context.Context, req SubagentRequest) (*SubagentResult, error)
}

SubagentExecutor executes harness-backed child runs for the subagents tool.

func GetSubagentExecutor

func GetSubagentExecutor(ctx context.Context) SubagentExecutor

GetSubagentExecutor extracts the child-run executor from the context.

type SubagentRequest

type SubagentRequest struct {
	Goal          string                 `json:"goal"`
	AgentID       string                 `json:"agent_id,omitempty"`
	Model         string                 `json:"model,omitempty"`
	Context       string                 `json:"context,omitempty"`
	Wait          bool                   `json:"wait"`
	MaxDuration   time.Duration          `json:"max_duration,omitempty"`
	MaxSteps      int                    `json:"max_steps,omitempty"`
	MaxToolRounds int                    `json:"max_tool_rounds,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
}

SubagentRequest describes a child-agent execution request initiated by the subagents tool.

type SubagentResult

type SubagentResult struct {
	RunID           string `json:"run_id"`
	RootRunID       string `json:"root_run_id,omitempty"`
	ParentRunID     string `json:"parent_run_id,omitempty"`
	Status          string `json:"status"`
	Goal            string `json:"goal,omitempty"`
	Result          string `json:"result,omitempty"`
	Error           string `json:"error,omitempty"`
	AgentID         string `json:"agent_id,omitempty"`
	Model           string `json:"model,omitempty"`
	Depth           int    `json:"depth,omitempty"`
	Waited          bool   `json:"waited,omitempty"`
	Terminal        bool   `json:"terminal,omitempty"`
	Completed       bool   `json:"completed,omitempty"`
	ContextIsolated bool   `json:"context_isolated,omitempty"`
}

SubagentResult is the normalized child-run payload returned to tools.

type SubagentsTool

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

SubagentsTool inspects subagent availability and policy.

func NewSubagentsTool

func NewSubagentsTool(cfg *config.Config) *SubagentsTool

NewSubagentsTool creates a native subagents tool.

func (*SubagentsTool) Definition

func (t *SubagentsTool) Definition() ToolDefinition

Definition returns the tool schema.

func (*SubagentsTool) Execute

func (t *SubagentsTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute returns effective subagent policy information.

type TTSAudioResult

type TTSAudioResult struct {
	Audio           []byte
	Format          string
	ContentType     string
	DurationSeconds float64
	Provider        string
	Voice           string
}

TTSAudioResult is the normalized synthesis response used by the tts tool.

type TTSBackend

type TTSBackend interface {
	Status(ctx context.Context) interface{}
	Config(ctx context.Context) map[string]interface{}
	ListVoices(ctx context.Context) ([]TTSVoiceInfo, error)
	Synthesize(ctx context.Context, req TTSSynthesizeRequest) (*TTSAudioResult, error)
	SpeakLocally(ctx context.Context, text string) (bool, error)
	StopSpeaking(ctx context.Context) error
}

TTSBackend exposes the speech capabilities used by the tts tool.

type TTSSynthesizeRequest

type TTSSynthesizeRequest struct {
	Text     string
	Format   string
	Voice    string
	Provider string
	Speed    *float32
	Pitch    *float32
	Volume   *float32
}

TTSSynthesizeRequest is the normalized synthesis request used by the tts tool.

type TTSTool

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

TTSTool provides a native compatibility surface for legacy text-to-speech usage.

func NewTTSTool

func NewTTSTool(backend TTSBackend) *TTSTool

NewTTSTool creates a new native tts tool.

func (*TTSTool) Definition

func (t *TTSTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*TTSTool) Execute

func (t *TTSTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute dispatches the requested tts action.

type TTSVoiceInfo

type TTSVoiceInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Language    string `json:"language,omitempty"`
	Gender      string `json:"gender,omitempty"`
	Description string `json:"description,omitempty"`
	Provider    string `json:"provider,omitempty"`
	Quality     string `json:"quality,omitempty"`
}

TTSVoiceInfo is the normalized voice descriptor exposed by the tts tool.

type Tool

type Tool interface {
	// Definition returns the tool's definition.
	Definition() ToolDefinition

	// Execute runs the tool with the given arguments.
	Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)
}

Tool is the interface that all tools must implement.

func NewPublicBashTool

func NewPublicBashTool(registry *Registry) Tool

func NewPublicReadTool

func NewPublicReadTool(registry *Registry) Tool

func NewPublicWriteTool

func NewPublicWriteTool(registry *Registry) Tool

type ToolApprovalDecision

type ToolApprovalDecision struct {
	Allowed  bool                 `json:"allowed"`
	Approval ToolApprovalEnvelope `json:"approval"`
}

ToolApprovalDecision is the normalized response from an approval backend.

type ToolApprovalEnvelope

type ToolApprovalEnvelope struct {
	Required     bool   `json:"required"`
	Mode         string `json:"mode,omitempty"`
	Reason       string `json:"reason,omitempty"`
	ID           string `json:"id,omitempty"`
	BindingHash  string `json:"binding_hash,omitempty"`
	PolicySource string `json:"policy_source,omitempty"`
	RiskLevel    string `json:"risk_level,omitempty"`
	ExpiresAt    int64  `json:"expires_at,omitempty"`
}

ToolApprovalEnvelope captures approval details for a tool run.

type ToolApprovalRequest

type ToolApprovalRequest struct {
	ToolName     string                 `json:"tool_name"`
	ToolCallID   string                 `json:"tool_call_id,omitempty"`
	Arguments    map[string]interface{} `json:"arguments,omitempty"`
	Provider     string                 `json:"provider,omitempty"`
	ProviderID   string                 `json:"provider_id,omitempty"`
	Model        string                 `json:"model,omitempty"`
	AgentID      string                 `json:"agent_id,omitempty"`
	SessionID    string                 `json:"session_id,omitempty"`
	RouteKind    ToolRouteKind          `json:"route_kind,omitempty"`
	UserID       string                 `json:"user_id,omitempty"`
	RiskLevel    string                 `json:"risk_level,omitempty"`
	PolicySource string                 `json:"policy_source,omitempty"`
	BindingHash  string                 `json:"binding_hash,omitempty"`
}

ToolApprovalRequest carries runtime context for approval policy evaluation.

type ToolApprover

type ToolApprover interface {
	AuthorizeToolCall(ctx context.Context, req ToolApprovalRequest) (ToolApprovalDecision, error)
}

ToolApprover decides whether a tool call may proceed at runtime.

type ToolArtifact

type ToolArtifact struct {
	Kind      string
	Label     string
	PathOrURL string
	MimeType  string
	SizeBytes int64
	Metadata  map[string]interface{}
}

type ToolCostEnvelope

type ToolCostEnvelope struct {
	InputTokens  int     `json:"input_tokens,omitempty"`
	OutputTokens int     `json:"output_tokens,omitempty"`
	USD          float64 `json:"usd,omitempty"`
}

ToolCostEnvelope captures normalized token / cost accounting.

type ToolDefinition

type ToolDefinition struct {
	Name                string                 `json:"name"`
	Description         string                 `json:"description"`
	Icon                string                 `json:"icon,omitempty"`
	Parameters          map[string]interface{} `json:"parameters,omitempty"`
	RiskLevel           string                 `json:"risk_level,omitempty"`
	Aliases             []string               `json:"aliases,omitempty"`
	SearchHints         []string               `json:"search_hints,omitempty"`
	ShouldDefer         bool                   `json:"should_defer,omitempty"`
	AlwaysLoad          bool                   `json:"always_load,omitempty"`
	VisibilityAllowlist []string               `json:"visibility_allowlist,omitempty"`
}

ToolDefinition describes a tool that can be called by an LLM.

type ToolEvent

type ToolEvent struct {
	Type           string
	Message        string
	StepIndex      int
	ToolName       string
	CapabilityKind string
	Payload        map[string]interface{}
}

type ToolGateway

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

ToolGateway centralizes tool validation, approval, execution, and output shaping.

func NewToolGateway

func NewToolGateway(registry *Registry, executor *Executor) *ToolGateway

NewToolGateway creates a new shared tool execution gateway.

func (*ToolGateway) Execute

Execute validates and executes a tool call through the shared runtime gateway.

func (*ToolGateway) SetApprover

func (g *ToolGateway) SetApprover(approver ToolApprover)

SetApprover wires an approval backend used for non-exec runtime enforcement.

func (*ToolGateway) SetEventObserver

func (g *ToolGateway) SetEventObserver(observer RuntimeEventObserver)

SetEventObserver wires runtime lifecycle observation into the gateway.

func (*ToolGateway) SetMetricsRecorder

func (g *ToolGateway) SetMetricsRecorder(recorder toolGatewayMetricsRecorder)

SetMetricsRecorder wires a lightweight counter recorder for runtime events.

func (*ToolGateway) SetToolSurfaceAuditState

func (g *ToolGateway) SetToolSurfaceAuditState(state *ToolSurfaceAuditState)

SetToolSurfaceAuditState wires a shared tool-surface audit counter sink into the gateway.

type ToolGatewayCall

type ToolGatewayCall struct {
	ToolCallID    string                 `json:"tool_call_id,omitempty"`
	ToolName      string                 `json:"tool_name"`
	Arguments     map[string]interface{} `json:"arguments,omitempty"`
	ArgumentsJSON string                 `json:"arguments_json"`
}

ToolGatewayCall is the normalized tool call shape after parsing/validation.

type ToolGatewayError

type ToolGatewayError struct {
	Code    string                 `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

ToolGatewayError is a structured runtime error for tool-call normalization/execution.

func (*ToolGatewayError) Error

func (e *ToolGatewayError) Error() string

func (*ToolGatewayError) ToolRuntimeCode

func (e *ToolGatewayError) ToolRuntimeCode() string

func (*ToolGatewayError) ToolRuntimeDetails

func (e *ToolGatewayError) ToolRuntimeDetails() map[string]interface{}

type ToolGatewayRequest

type ToolGatewayRequest struct {
	ToolCallID   string
	ToolName     string
	Arguments    string
	Provider     string
	ProviderID   string
	Model        string
	AgentID      string
	SessionID    string
	RouteKind    ToolRouteKind
	UserID       string
	PolicySource string
	RiskLevel    string
}

ToolGatewayRequest describes a tool execution request flowing through the shared gateway.

type ToolGatewayResult

type ToolGatewayResult struct {
	NormalizedCall        ToolGatewayCall       `json:"normalized_call"`
	ExecutionResult       interface{}           `json:"execution_result,omitempty"`
	CompactLLMPayload     interface{}           `json:"compact_llm_payload,omitempty"`
	CompactLLMContent     string                `json:"compact_llm_content,omitempty"`
	AuditPayload          interface{}           `json:"audit_payload,omitempty"`
	AuditContent          string                `json:"audit_content,omitempty"`
	Approval              *ToolApprovalEnvelope `json:"approval,omitempty"`
	GroundingEvidenceRefs []string              `json:"grounding_evidence_refs,omitempty"`
}

ToolGatewayResult contains normalized tool execution outputs for audit and LLM use.

type ToolImageInput

type ToolImageInput struct {
	Name     string
	MimeType string
	Data     string
}

ToolImageInput carries an inline image attachment through tool execution context so review-style tools can recover the original image input even when the model omits it from structured arguments.

func GetImageInputs

func GetImageInputs(ctx context.Context) []ToolImageInput

GetImageInputs extracts inline image inputs from tool execution context.

type ToolLoopDetection

type ToolLoopDetection struct {
	Abort     bool   `json:"abort"`
	Reason    string `json:"reason,omitempty"`
	Streak    int    `json:"streak,omitempty"`
	Signature string `json:"signature,omitempty"`
}

type ToolLoopDetector

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

ToolLoopDetector tracks recent tool rounds to detect loop patterns at runtime.

func (*ToolLoopDetector) Observe

func (d *ToolLoopDetector) Observe(toolSignature, assistantDecision string, toolSummaries []string, progressMarkers ...string) ToolLoopDetection

Observe records one completed tool round and reports whether the loop should abort.

type ToolPolicyRequest

type ToolPolicyRequest struct {
	Provider                       string
	ProviderID                     string
	Model                          string
	AgentID                        string
	SessionID                      string
	RouteKind                      ToolRouteKind
	DeepResearchEnabled            *bool
	SkipDefaultChatDirectAllowlist bool
}

ToolPolicyRequest carries runtime selection hints.

type ToolPolicyResolver

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

ToolPolicyResolver narrows the visible tool surface before selection/routing.

func NewToolPolicyResolver

func NewToolPolicyResolver(cfg *config.Config) *ToolPolicyResolver

NewToolPolicyResolver creates a resolver from app config.

func (*ToolPolicyResolver) Filter

Filter narrows tool definitions according to configured policy.

type ToolResultEnvelope

type ToolResultEnvelope struct {
	Status   string                `json:"status"`
	TraceID  string                `json:"trace_id,omitempty"`
	AuditID  string                `json:"audit_id,omitempty"`
	Warnings []string              `json:"warnings,omitempty"`
	Approval *ToolApprovalEnvelope `json:"approval,omitempty"`
	Cost     *ToolCostEnvelope     `json:"cost,omitempty"`
	Data     interface{}           `json:"data,omitempty"`
}

ToolResultEnvelope is the normalized response shape for future native tools.

type ToolRouteKind

type ToolRouteKind string

func GetRouteKind

func GetRouteKind(ctx context.Context) ToolRouteKind

GetRouteKind extracts the execution route kind from the context.

type ToolRouter

type ToolRouter struct {
	// DynamicExposure enables query-driven tool visibility rules.
	DynamicExposure bool
	// SchemaCompression removes non-essential JSON-schema fields to reduce prompt tokens.
	SchemaCompression bool
	// AlwaysInclude tools that must stay visible regardless of routing rules.
	AlwaysInclude []string
	// contains filtered or unexported fields
}

ToolRouter applies dynamic tool exposure rules and optional schema compression.

func DefaultToolRouter

func DefaultToolRouter() *ToolRouter

DefaultToolRouter returns a tool router with conservative defaults.

func (*ToolRouter) Route

func (tr *ToolRouter) Route(query, model string, defs []ToolDefinition) []ToolDefinition

Route returns routed tool definitions for a single request.

func (*ToolRouter) Stats

func (tr *ToolRouter) Stats() ToolRouterStats

Stats returns current cumulative router stats.

type ToolRouterStats

type ToolRouterStats struct {
	Requests          int64 `json:"requests"`
	ToolsTotal        int64 `json:"tools_total"`
	ToolsExposed      int64 `json:"tools_exposed"`
	ToolsHidden       int64 `json:"tools_hidden"`
	SchemaBytesBefore int64 `json:"schema_bytes_before"`
	SchemaBytesAfter  int64 `json:"schema_bytes_after"`
}

ToolRouterStats holds cumulative stats for tool routing and schema compression.

type ToolRuntimeError

type ToolRuntimeError interface {
	error
	ToolRuntimeCode() string
	ToolRuntimeDetails() map[string]interface{}
}

ToolRuntimeError exposes stable machine-readable error semantics across tool execution, approvals, and harness-backed runtime adapters.

type ToolRuntimeEvent

type ToolRuntimeEvent struct {
	RunID          string                 `json:"run_id,omitempty"`
	StepIndex      int                    `json:"step_index,omitempty"`
	ToolCallID     string                 `json:"tool_call_id,omitempty"`
	ToolName       string                 `json:"tool_name"`
	CapabilityKind string                 `json:"capability_kind,omitempty"`
	SessionID      string                 `json:"session_id,omitempty"`
	RouteKind      ToolRouteKind          `json:"route_kind,omitempty"`
	UserID         string                 `json:"user_id,omitempty"`
	Provider       string                 `json:"provider,omitempty"`
	ProviderID     string                 `json:"provider_id,omitempty"`
	Model          string                 `json:"model,omitempty"`
	AgentID        string                 `json:"agent_id,omitempty"`
	Arguments      map[string]interface{} `json:"arguments,omitempty"`
	Result         interface{}            `json:"result,omitempty"`
	Error          string                 `json:"error,omitempty"`
}

type ToolSearchActivated

type ToolSearchActivated struct {
	Tools      []string                   `json:"tools,omitempty"`
	Exec       bool                       `json:"exec,omitempty"`
	AgentTools bool                       `json:"agent_tools,omitempty"`
	Skipped    []ToolSearchActivationSkip `json:"skipped,omitempty"`
}

type ToolSearchActivationSkip

type ToolSearchActivationSkip struct {
	ID     string `json:"id,omitempty"`
	Name   string `json:"name,omitempty"`
	Kind   string `json:"kind,omitempty"`
	Reason string `json:"reason,omitempty"`
}

type ToolSearchMatch

type ToolSearchMatch struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Kind         string   `json:"kind"`
	Description  string   `json:"description,omitempty"`
	Availability string   `json:"availability,omitempty"`
	Activation   string   `json:"activation,omitempty"`
	CallTool     string   `json:"call_tool,omitempty"`
	CallHint     string   `json:"call_hint,omitempty"`
	WhyMatched   []string `json:"why_matched,omitempty"`
}

type ToolSearchResult

type ToolSearchResult struct {
	Matches   []ToolSearchMatch   `json:"matches"`
	Activated ToolSearchActivated `json:"activated"`
}

type ToolSearchRuntimeInfo

type ToolSearchRuntimeInfo struct {
	PromptPolicyHash    string
	WebSearchEnabled    bool
	DeepResearchEnabled bool
}

type ToolSearchRuntimeInfoSource

type ToolSearchRuntimeInfoSource func(sessionID string) ToolSearchRuntimeInfo

type ToolSearchTool

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

func GetToolSearchTool

func GetToolSearchTool(registry *Registry) *ToolSearchTool

GetToolSearchTool retrieves the ToolSearchTool from the registry for dependency injection.

func NewToolSearchTool

func NewToolSearchTool(registry *Registry) *ToolSearchTool

func (*ToolSearchTool) Definition

func (t *ToolSearchTool) Definition() ToolDefinition

func (*ToolSearchTool) Execute

func (t *ToolSearchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*ToolSearchTool) SetAgentsConfig

func (t *ToolSearchTool) SetAgentsConfig(cfg *config.AgentsConfig)

func (*ToolSearchTool) SetDeferredExposureStore

func (t *ToolSearchTool) SetDeferredExposureStore(store *DeferredToolExposureStore)

func (*ToolSearchTool) SetRuntimeInfoSource

func (t *ToolSearchTool) SetRuntimeInfoSource(fn ToolSearchRuntimeInfoSource)

func (*ToolSearchTool) SetSkillExposureManager

func (t *ToolSearchTool) SetSkillExposureManager(manager *skillmanifest.SkillExposureManager)

func (*ToolSearchTool) SetToolPolicyResolver

func (t *ToolSearchTool) SetToolPolicyResolver(resolver *ToolPolicyResolver)

type ToolSelectionCandidateDebug

type ToolSelectionCandidateDebug struct {
	Name             string   `json:"name"`
	Score            float64  `json:"score"`
	MatchedSignals   []string `json:"matched_signals,omitempty"`
	ConflictFlags    []string `json:"conflict_flags,omitempty"`
	ConfidenceReason string   `json:"confidence_reason,omitempty"`
}

ToolSelectionCandidateDebug captures selector signals for one candidate.

type ToolSelectionDebug

type ToolSelectionDebug struct {
	QuerySignals selectorSignals               `json:"query_signals"`
	GatingFlags  []string                      `json:"gating_flags,omitempty"`
	Candidates   []ToolSelectionCandidateDebug `json:"candidates,omitempty"`
}

ToolSelectionDebug is returned by dry-run APIs for selector inspection.

type ToolSelectionResult

type ToolSelectionResult struct {
	Selected []ToolDefinition   `json:"selected"`
	Debug    ToolSelectionDebug `json:"debug"`
}

ToolSelectionResult returns selected tools plus optional debug details.

type ToolSelector

type ToolSelector struct {
	MinScore      float64
	MaxTools      int
	AlwaysInclude []string
	// contains filtered or unexported fields
}

ToolSelector performs heuristic tool selection, filtering tool definitions to only those relevant to the user's query.

func DefaultToolSelector

func DefaultToolSelector() *ToolSelector

DefaultToolSelector returns a ToolSelector with conservative defaults.

func (*ToolSelector) Select

func (ts *ToolSelector) Select(query string, allDefs []ToolDefinition) []ToolDefinition

Select filters tool definitions to those relevant to the user query.

func (*ToolSelector) SelectDetailed

func (ts *ToolSelector) SelectDetailed(query string, allDefs []ToolDefinition) ToolSelectionResult

SelectDetailed returns selected definitions plus debugging details.

func (*ToolSelector) SelectFromRegistry

func (ts *ToolSelector) SelectFromRegistry(query string, registry *Registry) []ToolDefinition

SelectFromRegistry is a convenience method that gets definitions from a registry and filters them based on the query.

func (*ToolSelector) Stats

func (ts *ToolSelector) Stats() ToolSelectorStats

Stats returns a snapshot of cumulative selection statistics.

type ToolSelectorStats

type ToolSelectorStats struct {
	Requests     int64 `json:"requests"`
	ToolsTotal   int64 `json:"tools_total"`
	ToolsSent    int64 `json:"tools_sent"`
	ToolsSkipped int64 `json:"tools_skipped"`
	TokensSaved  int64 `json:"tokens_saved"`
}

ToolSelectorStats holds cumulative statistics for smart tool selection.

type ToolSurfaceAuditSnapshot

type ToolSurfaceAuditSnapshot struct {
	AliasRewriteCount      uint64 `json:"tool_surface_alias_rewrite_count"`
	CacheInvalidationCount uint64 `json:"tool_surface_cache_invalidation_count"`
	ExecCutoverCount       uint64 `json:"tool_surface_exec_cutover_count"`
}

type ToolSurfaceAuditState

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

func NewToolSurfaceAuditState

func NewToolSurfaceAuditState() *ToolSurfaceAuditState

func (*ToolSurfaceAuditState) RecordAliasRewrite

func (s *ToolSurfaceAuditState) RecordAliasRewrite()

func (*ToolSurfaceAuditState) RecordCacheInvalidation

func (s *ToolSurfaceAuditState) RecordCacheInvalidation()

func (*ToolSurfaceAuditState) RecordExecCutover

func (s *ToolSurfaceAuditState) RecordExecCutover()

func (*ToolSurfaceAuditState) Snapshot

type ToolSurfaceMetrics

type ToolSurfaceMetrics struct {
	ToolCount   int `json:"tool_count"`
	SchemaBytes int `json:"schema_bytes"`
}

ToolSurfaceMetrics describes the LLM-visible native tool surface after routing/localization/schema normalization.

func MeasureLLMToolSurface

func MeasureLLMToolSurface(defs []ToolDefinition) ToolSurfaceMetrics

MeasureLLMToolSurface returns the normalized schema footprint for the given tool definitions using the same schema normalization path the chat layer uses before exposing tools to providers.

type ToolTraceRecord

type ToolTraceRecord struct {
	ID             string    `json:"id"`
	RunID          string    `json:"run_id,omitempty"`
	StepIndex      int       `json:"step_index,omitempty"`
	CapabilityKind string    `json:"capability_kind,omitempty"`
	RequestedTool  string    `json:"requested_tool"`
	ActualTool     string    `json:"actual_tool"`
	StartedAt      time.Time `json:"started_at"`
	FinishedAt     time.Time `json:"finished_at"`
	DurationMs     int64     `json:"duration_ms"`
	Success        bool      `json:"success"`
	Error          string    `json:"error,omitempty"`
	InputSummary   string    `json:"input_summary,omitempty"`
	OutputSummary  string    `json:"output_summary,omitempty"`
}

ToolTraceRecord captures one tool execution summary.

type ToolTraceStore

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

ToolTraceStore keeps recent in-memory tool traces.

func NewToolTraceStore

func NewToolTraceStore(limit int) *ToolTraceStore

NewToolTraceStore creates a bounded in-memory trace store.

func (*ToolTraceStore) List

func (s *ToolTraceStore) List(limit int) []ToolTraceRecord

List returns the most recent traces, newest first.

func (*ToolTraceStore) Record

func (s *ToolTraceStore) Record(ctx context.Context, startedAt time.Time, requestedTool, actualTool string, args map[string]interface{}, result interface{}, err error) string

Record appends a finished tool trace.

type UIReviewA11yResult

type UIReviewA11yResult struct {
	Tree string
}

UIReviewA11yResult is the result of an accessibility tree query.

type UIReviewBrowser

type UIReviewBrowser interface {
	Start(ctx context.Context) error
	NavigateURL(ctx context.Context, url string) (UIReviewNavResult, error)
	GetAccessibilityTree(ctx context.Context, targetID string, maxDepth int) (UIReviewA11yResult, error)
	ScreenshotTab(ctx context.Context, targetID string) (string, error)
	CloseTab(ctx context.Context, targetID string) error
	SetViewport(ctx context.Context, targetID string, width, height int) error
	ScrollTo(ctx context.Context, targetID string, x, y int) error
	PageDimensions(ctx context.Context, targetID string) (viewportH, scrollH int, err error)
	ScreenshotViewportRaw(ctx context.Context, targetID string) ([]byte, error)
}

UIReviewBrowser defines the browser interface needed by the UI reviewer.

type UIReviewImageOptions

type UIReviewImageOptions struct {
	Threshold float64
	Format    string
	Lang      i18n.Language
	Profile   UIReviewProfile
}

type UIReviewIssue

type UIReviewIssue struct {
	Severity    string `json:"severity"`
	Category    string `json:"category"`
	Rule        string `json:"rule,omitempty"`
	Element     string `json:"element,omitempty"`
	Description string `json:"description"`
	Location    string `json:"location,omitempty"`
}

UIReviewIssue represents a single issue found during review.

type UIReviewNavResult

type UIReviewNavResult struct {
	URL      string
	Title    string
	TargetID string
}

UIReviewNavResult is the result of a browser navigation.

type UIReviewProfile

type UIReviewProfile string
const (
	UIReviewProfileUIScreenshot UIReviewProfile = "ui_screenshot"
	UIReviewProfilePPT          UIReviewProfile = "ppt"
)

type UIReviewResult

type UIReviewResult struct {
	URL           string          `json:"url,omitempty"`
	Visual        UIScoreDetail   `json:"visual"`
	Functional    UIScoreDetail   `json:"functional"`
	Accessibility UIScoreDetail   `json:"accessibility"`
	Overall       float64         `json:"overall"`
	Pass          bool            `json:"pass"`
	Threshold     float64         `json:"threshold"`
	Issues        []UIReviewIssue `json:"issues"`
	Suggestions   []string        `json:"suggestions,omitempty"`
	Viewports     []string        `json:"viewports,omitempty"`
	Steps         []UIReviewStep  `json:"steps,omitempty"`
	Screenshot    string          `json:"screenshot,omitempty"`
	MediaURL      string          `json:"media_url,omitempty"`
	ThumbnailURL  string          `json:"thumbnail_url,omitempty"`
	Screenshots   []string        `json:"screenshots,omitempty"`
	Device        string          `json:"device,omitempty"`
	Channel       string          `json:"channel,omitempty"`
	Human         string          `json:"human,omitempty"`
}

UIReviewResult is the top-level output of a UI review.

type UIReviewStep

type UIReviewStep struct {
	ID      string  `json:"id"`
	Name    string  `json:"name"`
	Status  string  `json:"status"`
	Score   float64 `json:"score,omitempty"`
	Message string  `json:"message,omitempty"`
	Issues  int     `json:"issues,omitempty"`
}

UIReviewStep records one phase of the review pipeline.

type UIReviewerTool

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

UIReviewerTool performs automated UI quality review.

func GetUIReviewerTool

func GetUIReviewerTool(registry *Registry) *UIReviewerTool

GetUIReviewerTool retrieves the UIReviewerTool from the registry for dependency injection.

func NewUIReviewerTool

func NewUIReviewerTool() *UIReviewerTool

NewUIReviewerTool creates a new UI reviewer tool.

func (*UIReviewerTool) Definition

func (t *UIReviewerTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*UIReviewerTool) Execute

func (t *UIReviewerTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute runs the UI review tool.

func (*UIReviewerTool) ReviewImage

func (t *UIReviewerTool) ReviewImage(ctx context.Context, imageB64 string, opts UIReviewImageOptions) (*UIReviewResult, error)

func (*UIReviewerTool) SetBrowser

func (t *UIReviewerTool) SetBrowser(svc UIReviewBrowser)

SetBrowser injects the browser service.

func (*UIReviewerTool) SetMediaDir

func (t *UIReviewerTool) SetMediaDir(dir string)

SetMediaDir sets the directory for persisting screenshots.

func (*UIReviewerTool) SetVLMBridge

func (t *UIReviewerTool) SetVLMBridge(bridge VLMBridge)

SetVLMBridge injects the VLM bridge for visual review.

type UIScoreDetail

type UIScoreDetail struct {
	Score   float64            `json:"score"`
	Details map[string]float64 `json:"details,omitempty"`
}

UIScoreDetail holds a category score and its sub-scores.

type VLMBridge

type VLMBridge interface {
	ChatWithVision(ctx context.Context, prompt string, imageBase64 string) (string, error)
}

VLMBridge defines the interface for making VLM (vision language model) calls.

type WebCapability

type WebCapability struct {
	NeedsRawHTML        bool
	NeedsJS             bool
	NeedsLogin          bool
	NeedsInteraction    bool
	NeedsNetworkObserve bool
	HasBrowserSession   bool
	AntiBotLevel        int
}

type WebCrawlTool

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

func GetWebCrawlTool

func GetWebCrawlTool(registry *Registry) *WebCrawlTool

func NewWebCrawlTool

func NewWebCrawlTool(config WebFetchConfig) *WebCrawlTool

func (*WebCrawlTool) Definition

func (t *WebCrawlTool) Definition() ToolDefinition

func (*WebCrawlTool) Execute

func (t *WebCrawlTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebCrawlTool) SetPDFService

func (t *WebCrawlTool) SetPDFService(service PDFService)

type WebExtractTool

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

func GetWebExtractTool

func GetWebExtractTool(registry *Registry) *WebExtractTool

func NewWebExtractTool

func NewWebExtractTool(config WebFetchConfig) *WebExtractTool

func (*WebExtractTool) Definition

func (t *WebExtractTool) Definition() ToolDefinition

func (*WebExtractTool) Execute

func (t *WebExtractTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebExtractTool) SetBrowser

func (t *WebExtractTool) SetBrowser(browser BrowserBackend)

func (*WebExtractTool) SetLightpandaShim

func (t *WebExtractTool) SetLightpandaShim(service *browser.LightpandaService)

func (*WebExtractTool) SetPDFService

func (t *WebExtractTool) SetPDFService(service PDFService)

type WebFetchConfig

type WebFetchConfig struct {
	Timeout               time.Duration
	MaxChars              int
	MaxCharsCap           int
	MaxResponseBytes      int64
	MaxRedirects          int
	CacheTTL              time.Duration
	UserAgent             string
	AllowPrivateHosts     bool
	LayeredFetchEnabled   bool
	SessionMemoryEnabled  bool
	DomainStrategyEnabled bool
	AdapterMemoryEnabled  bool
	NetworkObserveEnabled bool
	MaxExploreAttempts    int
	AutoFallbackHosts     []string
	ChallengePolicy       string

	HTTPNativeEnabled     bool
	HTTPNativeLibrary     string
	HTTPNativePreferHosts []string

	FirecrawlEnabled         bool
	FirecrawlAPIKey          string
	FirecrawlBaseURL         string
	FirecrawlTimeout         time.Duration
	FirecrawlOnlyMainContent bool

	JinaReaderEnabled bool
	JinaReaderAPIKey  string
	JinaReaderBaseURL string
	JinaReaderTimeout time.Duration

	ProxyFetcherProviders []string
}

WebFetchConfig configures the web_fetch tool runtime behavior.

type WebFetchTool

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

WebFetchTool fetches and extracts readable content from a URL.

func GetWebFetchTool

func GetWebFetchTool(registry *Registry) *WebFetchTool

GetWebFetchTool retrieves the WebFetchTool from the registry for dependency injection.

func NewWebFetchTool

func NewWebFetchTool(config WebFetchConfig) *WebFetchTool

NewWebFetchTool creates a new web fetch tool.

func (*WebFetchTool) Definition

func (w *WebFetchTool) Definition() ToolDefinition

Definition returns the tool definition.

func (*WebFetchTool) Execute

func (w *WebFetchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute performs URL fetch + content extraction.

func (*WebFetchTool) SetBrowser

func (w *WebFetchTool) SetBrowser(browser BrowserBackend)

SetBrowser injects the browser backend used for session-cookie handoff.

func (*WebFetchTool) SetDocumentReadService

func (w *WebFetchTool) SetDocumentReadService(service DocumentReadService)

SetDocumentReadService injects the office-style document reader used for remote document extraction.

func (*WebFetchTool) SetLightpandaShim

func (w *WebFetchTool) SetLightpandaShim(service *browser.LightpandaService)

SetLightpandaShim injects the read-layer Lightpanda shim used by layered fetch routing before full-browser escalation.

func (*WebFetchTool) SetPDFService

func (w *WebFetchTool) SetPDFService(service PDFService)

SetPDFService injects the PDF extraction service for PDF responses.

type WebQueryLLMCompactionMode

type WebQueryLLMCompactionMode string
const (
	WebQueryLLMCompactionDefault WebQueryLLMCompactionMode = "default"
	WebQueryLLMCompactionSummary WebQueryLLMCompactionMode = "summary"
	WebQueryLLMCompactionMinimal WebQueryLLMCompactionMode = "minimal"
)

type WebQueryLLMCompactionOptions

type WebQueryLLMCompactionOptions struct {
	ByteBudget           int
	Mode                 WebQueryLLMCompactionMode
	ResultLimit          int
	FactLimit            int
	WarningLimit         int
	Materialize          bool
	ToolCallID           string
	ConversationID       string
	SearchRound          int
	OmittedFromLLM       bool
	OmittedReason        string
	ToolName             string
	ForceMaterialization bool
}

type WebReadTool

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

func GetWebReadTool

func GetWebReadTool(registry *Registry) *WebReadTool

func NewWebReadTool

func NewWebReadTool(config WebFetchConfig) *WebReadTool

func (*WebReadTool) Definition

func (t *WebReadTool) Definition() ToolDefinition

func (*WebReadTool) Execute

func (t *WebReadTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebReadTool) SetBrowser

func (t *WebReadTool) SetBrowser(browser BrowserBackend)

func (*WebReadTool) SetDocumentReadService

func (t *WebReadTool) SetDocumentReadService(service DocumentReadService)

func (*WebReadTool) SetLightpandaShim

func (t *WebReadTool) SetLightpandaShim(service *browser.LightpandaService)

func (*WebReadTool) SetPDFService

func (t *WebReadTool) SetPDFService(service PDFService)

type WebSearchBrowserFallbackConfig

type WebSearchBrowserFallbackConfig struct {
	Enabled           *bool
	Engine            string
	TriggerMode       string
	QualityThreshold  float64
	MaxBrowserRetries int
}

WebSearchBrowserFallbackConfig controls browser-backed search rescue.

type WebSearchConfig

type WebSearchConfig struct {
	// Provider specifies the search provider to use.
	// Supported: "duckduckgo", "bing", "searxng", "brave", "tavily"
	Provider string

	// Providers specifies a prioritized provider list for fallback (high availability).
	// If empty, Provider is used.
	Providers []string

	// APIKey is the API key for providers that require authentication.
	APIKey string

	// BaseURL is the base URL for self-hosted search engines (e.g., SearXNG).
	BaseURL string

	// MaxResults is the maximum number of results to return.
	MaxResults int

	// Timeout is the HTTP request timeout.
	Timeout time.Duration

	// SafeSearch enables safe search filtering.
	SafeSearch bool

	// Region specifies the search region (e.g., "us-en", "wt-wt" for worldwide).
	Region string

	// CacheTTL controls the in-memory public search result cache.
	// CacheTTL=0 uses the default TTL; CacheTTL<0 disables caching.
	CacheTTL time.Duration

	// CacheMaxEntries limits the number of cached search queries.
	// Values <= 0 use the default limit.
	CacheMaxEntries int

	// BrowserFallback controls browser-backed public SERP rescue for web_query.
	BrowserFallback WebSearchBrowserFallbackConfig

	// ProviderSettings stores provider-specific advanced configuration overrides.
	ProviderSettings map[string]WebSearchProviderSetting
}

WebSearchConfig holds configuration for the web search tool.

type WebSearchProviderSetting

type WebSearchProviderSetting struct {
	APIKey  string
	BaseURL string
	Enabled *bool
}

WebSearchProviderSetting stores provider-specific advanced settings.

type WebSearchResponse

type WebSearchResponse struct {
	Query      string            `json:"query"`
	Results    []WebSearchResult `json:"results"`
	TotalCount int               `json:"total_count"`
	Provider   string            `json:"provider"`
}

WebSearchResponse represents the search response.

type WebSearchResult

type WebSearchResult struct {
	Title       string `json:"title"`
	URL         string `json:"url"`
	Description string `json:"description"`
	Source      string `json:"source,omitempty"`
}

WebSearchResult represents a single search result.

type WebSearchTool

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

WebSearchTool performs web searches using various search providers.

func NewWebSearchTool

func NewWebSearchTool(config WebSearchConfig) *WebSearchTool

NewWebSearchTool creates a new web search tool.

func (*WebSearchTool) Definition

func (w *WebSearchTool) Definition() ToolDefinition

Definition returns the tool's definition.

func (*WebSearchTool) Execute

func (w *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Execute performs the web search.

func (*WebSearchTool) SetHTTPClientForTest

func (w *WebSearchTool) SetHTTPClientForTest(c *http.Client)

SetHTTPClientForTest overrides the HTTP client used by this tool. Intended for use in tests outside this package.

type WebTask

type WebTask struct {
	Kind       WebTaskKind
	Query      string
	URL        string
	Action     string
	MaxResults int
	MaxChars   int
	Capability WebCapability
	SessionID  string
	TargetID   string
}

type WebTaskKind

type WebTaskKind string
const (
	WebTaskKindSearch   WebTaskKind = "search"
	WebTaskKindRetrieve WebTaskKind = "retrieve"
	WebTaskKindOperate  WebTaskKind = "operate"
)

type WebTool

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

WebTool provides a single public web-query surface with internal orchestration plus compatibility routing for the legacy web_* tools.

func GetWebQueryTool

func GetWebQueryTool(registry *Registry) *WebTool

func GetWebTool

func GetWebTool(registry *Registry) *WebTool

func NewWebQueryTool

func NewWebQueryTool(search, fetch, read, extract, crawl Tool) *WebTool

NewWebQueryTool creates the primary visible web_query tool.

func (*WebTool) Definition

func (t *WebTool) Definition() ToolDefinition

func (*WebTool) Execute

func (t *WebTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

func (*WebTool) SetBrowser

func (t *WebTool) SetBrowser(browser BrowserBackend)

func (*WebTool) SetDocumentReadService

func (t *WebTool) SetDocumentReadService(service DocumentReadService)

func (*WebTool) SetImageTool

func (t *WebTool) SetImageTool(tool Tool)

func (*WebTool) SetLightpandaShim

func (t *WebTool) SetLightpandaShim(service *browser.LightpandaService)

func (*WebTool) SetPDFService

func (t *WebTool) SetPDFService(service PDFService)

func (*WebTool) SetSTTService

func (t *WebTool) SetSTTService(service stt.Service)

type WritePathGuard

type WritePathGuard interface {
	CheckWritePath(ctx context.Context, absPath string) error
}

WritePathGuard enforces runtime-specific direct-write restrictions for file mutation tools after workspace/approval path resolution.

func GetWritePathGuard

func GetWritePathGuard(ctx context.Context) WritePathGuard

GetWritePathGuard extracts the direct-write guard from the context.

type WriteSessionManager

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

func NewWriteSessionManager

func NewWriteSessionManager(maxFileSize int64) *WriteSessionManager

func (*WriteSessionManager) Abort

func (m *WriteSessionManager) Abort(sessionID, ownerID string) (*writeSession, error)

func (*WriteSessionManager) Append

func (m *WriteSessionManager) Append(sessionID, ownerID, content string) (*writeSession, error)

func (*WriteSessionManager) Begin

func (m *WriteSessionManager) Begin(absPath, relPath, originalPath, ownerID string, createDirs bool) (*writeSession, error)

func (*WriteSessionManager) Commit

func (m *WriteSessionManager) Commit(sessionID, ownerID string, expectedBytes int64, expectedSHA256 string) (*writeSession, string, error)

func (*WriteSessionManager) Preview

func (m *WriteSessionManager) Preview(sessionID, ownerID string) (*writeSession, error)

type XLSXTool

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

func NewXLSXTool

func NewXLSXTool(allowedPaths []string, approvals *ApprovalManager, dirStore *DirAllowlistStore) *XLSXTool

func (*XLSXTool) Definition

func (t *XLSXTool) Definition() ToolDefinition

func (*XLSXTool) Execute

func (t *XLSXTool) Execute(ctx context.Context, args map[string]interface{}) (interface{}, error)

Source Files

Jump to

Keyboard shortcuts

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