delegate

package
v0.9.0-rc Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package delegate implements the thane_delegate meta-tool for split-model execution. A calling model delegates subtasks to cheaper/local models that run with minimal context and a filtered tool set.

Index

Constants

View Source
const (
	ExhaustMaxIterations = iterate.ExhaustMaxIterations
	ExhaustTokenBudget   = iterate.ExhaustTokenBudget
	ExhaustWallClock     = iterate.ExhaustWallClock
	ExhaustNoOutput      = iterate.ExhaustNoOutput
	ExhaustIllegalTool   = iterate.ExhaustIllegalTool
)

Exhaustion reason constants are defined in the iterate package. These aliases preserve backward compatibility for consumers that reference them via the delegate package.

Variables

ToolDescription is the LLM-facing description for the thane_delegate tool.

Functions

func ExtractToolsCalled added in v0.5.2

func ExtractToolsCalled(messages []llm.Message) map[string]int

ExtractToolsCalled scans a message history and returns a map of tool names to invocation counts.

func ToolDefinition

func ToolDefinition() map[string]any

ToolDefinition returns the JSON schema parameters for the thane_delegate tool.

func ToolHandler

func ToolHandler(exec *Executor) func(ctx context.Context, args map[string]any) (string, error)

ToolHandler returns a tool handler function bound to the given executor. Errors from the delegate are returned as tool result strings (not Go errors) so the calling model can decide what to do.

Types

type Executor

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

Executor runs delegate sub-agent tasks.

func NewExecutor

func NewExecutor(logger *slog.Logger, llmClient llm.Client, rtr *router.Router, parentReg *tools.Registry, defaultModel string) *Executor

NewExecutor creates a delegate executor.

func (*Executor) ApplyProfileOverrides added in v0.8.4

func (e *Executor) ApplyProfileOverrides(overrides map[string]ProfileOverride)

ApplyProfileOverrides applies configuration overrides to builtin profiles. Only positive fields in each override replace the builtin defaults. Negative values are logged as warnings and ignored. Unknown profile names are silently ignored (config may reference profiles that don't exist yet).

func (*Executor) ConfigureLoopCompletionSink added in v0.9.1

func (e *Executor) ConfigureLoopCompletionSink(sink looppkg.CompletionSink)

ConfigureLoopCompletionSink configures the detached completion sink used by background delegate launches that report back into a conversation.

func (*Executor) ConfigureLoopExecution added in v0.9.1

func (e *Executor) ConfigureLoopExecution(runner looppkg.Runner, registry *looppkg.Registry)

ConfigureLoopExecution configures loop-backed delegate execution. When both runner and registry are set, Execute launches a one-shot child loop through the shared loops-ng path, giving delegates the same telemetry path as other loop-driven work.

func (*Executor) ConfigureSessionLifecycle added in v0.9.1

func (e *Executor) ConfigureSessionLifecycle(archiver agent.SessionArchiver, store *memory.SQLiteStore)

ConfigureSessionLifecycle configures archival and cleanup for loop-backed delegate conversations. The archiver preserves parent session linkage and archived transcripts; the conversation store is cleared after completion so ephemeral delegate turns do not accumulate in working memory.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, task, profileName, guidance string, tags []string, pathPrefixes map[string]string) (*Result, error)

Execute runs a delegated task with the given profile and guidance. When tags is non-empty, the delegate's tool registry is scoped to only tools belonging to the given capability tags (plus any always-active tags). When tags is nil, the profile's AllowedTools controls tool selection (existing behavior).

func (*Executor) ProfileNames

func (e *Executor) ProfileNames() []string

ProfileNames returns the names of all registered profiles.

func (*Executor) SetAlwaysActiveTags added in v0.8.0

func (e *Executor) SetAlwaysActiveTags(tags []string)

SetAlwaysActiveTags configures the capability tags that are automatically included in every tag-scoped delegation, regardless of which tags the caller requests. This mirrors the agent loop's always_active tag behavior.

func (*Executor) SetArchiver added in v0.8.0

func (e *Executor) SetArchiver(a *memory.ArchiveStore)

SetArchiver configures the archive store for session lifecycle tracking. When set, each Executor.Execute call creates a first-class archive session with parent linkage, and archives its messages and tool calls for inspection in the web dashboard.

func (*Executor) SetEventBus added in v0.8.4

func (e *Executor) SetEventBus(bus *events.Bus)

SetEventBus configures the event bus for delegate lifecycle events. When set, each Execute call publishes spawn and complete events so the dashboard can render delegates as ephemeral child nodes.

func (*Executor) SetForgeContext added in v0.8.0

func (e *Executor) SetForgeContext(ctx string)

SetForgeContext configures the forge account context block that is appended to delegate system prompts. This gives delegates immediate knowledge of configured forge accounts so they don't waste iterations guessing account names.

func (*Executor) SetLensProvider added in v0.9.1

func (e *Executor) SetLensProvider(fn func() []string)

SetLensProvider configures a function that returns the currently active global lenses. These are merged into every delegate execution's effective tag set so lens-tagged KB articles and talents apply.

func (*Executor) SetRequestRecorder added in v0.9.1

func (e *Executor) SetRequestRecorder(recorder logging.RequestRecordFunc)

SetRequestRecorder configures request detail recording for delegate executions.

func (*Executor) SetTagContextFunc added in v0.9.1

func (e *Executor) SetTagContextFunc(fn tagContextFunc)

SetTagContextFunc configures the tag context builder function for injecting capability context (static files, tagged KB articles, and live providers) into delegate system prompts. When set, this replaces the ad-hoc forge context injection.

func (*Executor) SetTempFileStore added in v0.7.1

func (e *Executor) SetTempFileStore(tfs interface {
	ExpandLabels(convID, text string) string
})

SetTempFileStore configures temp file label expansion for delegate task descriptions. When set, occurrences of "temp:LABEL" in the task and guidance strings are replaced with actual file paths before the delegate LLM sees the message.

func (*Executor) SetTimezone

func (e *Executor) SetTimezone(tz string)

SetTimezone configures the IANA timezone for Current Conditions in the delegate system prompt.

func (*Executor) SetUsageRecorder added in v0.7.1

func (e *Executor) SetUsageRecorder(store *usage.Store, pricing map[string]config.PricingEntry, cat *models.Catalog)

SetUsageRecorder configures persistent token usage recording for delegate executions. When set, every delegate completion is persisted for cost attribution.

func (*Executor) StartBackground added in v0.9.1

func (e *Executor) StartBackground(ctx context.Context, task, profileName, guidance string, tags []string, pathPrefixes map[string]string) (string, error)

StartBackground launches a detached delegate loop that reports its completion back into the current conversation.

func (*Executor) UseLiveRequestRecorder added in v0.9.1

func (e *Executor) UseLiveRequestRecorder(recorder logging.RequestRecordFunc)

UseLiveRequestRecorder configures live request detail recording for in-flight delegate turns.

func (*Executor) UseModelRegistry added in v0.9.1

func (e *Executor) UseModelRegistry(registry *models.Registry)

UseModelRegistry configures the live model registry used for runtime usage attribution and deployment metadata resolution.

type Profile

type Profile struct {
	// Name is the profile identifier (e.g., "general", "ha").
	Name string

	// Description is a human-readable summary for logging.
	Description string

	// AllowedTools lists the tool names available to the delegate.
	// An empty list means all tools (minus thane_delegate).
	AllowedTools []string

	// SystemPrompt is the profile-specific system prompt for the delegate.
	SystemPrompt string

	// RouterHints are passed to the router for model selection.
	RouterHints map[string]string

	// MaxIter is the maximum number of tool-calling iterations.
	MaxIter int

	// MaxTokens is the maximum cumulative output tokens before budget exhaustion.
	MaxTokens int

	// MaxDuration is the maximum wall clock time for the delegation loop.
	MaxDuration time.Duration

	// ToolTimeout is the maximum time a single tool call may run before
	// being cancelled. Zero means defaultToolTimeout.
	ToolTimeout time.Duration
}

Profile defines the configuration for a delegation context.

type ProfileOverride added in v0.8.4

type ProfileOverride struct {
	ToolTimeout time.Duration
	MaxDuration time.Duration
	MaxIter     int
	MaxTokens   int
}

ProfileOverride holds optional overrides for a delegate profile. Only positive values are applied; zero and negative fields are ignored.

type Result

type Result struct {
	Content                  string            `json:"content"`
	Model                    string            `json:"model"`
	Iterations               int               `json:"iterations"`
	InputTokens              int               `json:"input_tokens"`
	OutputTokens             int               `json:"output_tokens"`
	CacheCreationInputTokens int               `json:"cache_creation_input_tokens"`
	CacheReadInputTokens     int               `json:"cache_read_input_tokens"`
	Exhausted                bool              `json:"exhausted"`
	ExhaustReason            string            `json:"exhaust_reason,omitempty"`
	ToolCalls                []ToolCallOutcome `json:"tool_calls,omitempty"`
	Duration                 time.Duration     `json:"duration"`
}

Result is the outcome of a delegated task execution.

type ToolCallOutcome added in v0.7.0

type ToolCallOutcome struct {
	Name    string `json:"name"`
	Success bool   `json:"success"`
}

ToolCallOutcome records the name and success/failure of a single tool invocation during delegate execution.

Jump to

Keyboard shortcuts

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