Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyMessageToolPersist(m *Message, s string) error
- func BuildOutputHeader(h OutputHeader) string
- func FormatToolResult(result interface{}) string
- func IsFatalToolError(err error) bool
- func MarshalMessageToolPersist(m Message) (string, error)
- func NormalizeToolError(err error, maxLen int) string
- func RoughTokenEstimate(text string) int
- func RoughTokensForMessage(m Message) int
- func SanitizeToolResult(result interface{}, maxTextLen int) interface{}
- func SerializeMessageParts(parts []MessagePart) (string, error)
- func TruncateMiddle(s string, maxBytes int) (out string, omitted int)
- func TruncateString(s string, maxLen int) string
- type ActionMetadata
- type ActionResponse
- type AgentConfig
- type AgentInput
- type AgentResult
- type AgentStopCause
- type EngineRequest
- type EngineResponse
- type FatalToolError
- type FatalToolErrorKind
- type ImageDataPart
- type ImageURLPart
- type LLMProvider
- type LangChainToolWrapper
- type MemoryProvider
- type MemoryReplay
- type Message
- type MessagePart
- type ModelMetadata
- type OutputHeader
- type OutputParser
- type PromptCacheConfigurer
- type PromptCacheOptions
- type ReasoningMessage
- type RequestResponseMetadata
- type StreamEvent
- type StreamMessage
- type StreamResult
- type TextPart
- type Tool
- type ToolAction
- type ToolActionStep
- type ToolCacheEntry
- type ToolCall
- type ToolCallData
- type ToolCallRequest
- type ToolCallback
- type ToolCallbackFunc
- func (f *ToolCallbackFunc) OnToolCall(toolName string, toolCallID string, input map[string]interface{})
- func (f *ToolCallbackFunc) OnToolError(toolName string, toolCallID string, err error)
- func (f *ToolCallbackFunc) OnToolInputEnd(toolName string, toolCallID string, input map[string]interface{})
- func (f *ToolCallbackFunc) OnToolInputStart(toolName string, toolCallID string, input map[string]interface{})
- func (f *ToolCallbackFunc) OnToolResult(toolName string, toolCallID string, output interface{})
- type ToolEvent
- type ToolExposure
- type ToolFunction
- type ToolMetadata
- type TruncationMeta
- type Usage
Constants ¶
const ( // Cache-related constants DefaultCacheSize = 100 // default tool cache size CacheExpirationTime = 5 * time.Minute // cache expiration time // Execution-related constants DefaultChannelBuffer = 50 // default channel buffer size MaxTruncationLength = 2048 // maximum truncation length MinChannelBuffer = 10 // minimum channel buffer size // Performance-related constants DefaultBufferPoolSize = 1024 // default buffer pool size (1KB) IterationDelay = 100 * time.Millisecond // inter-iteration delay )
Constant definitions
const ( ToolStatePending = "pending" ToolStateRunning = "running" ToolStateCompleted = "completed" ToolStateError = "error" ToolEmptyResultMessage = "Tool executed successfully but returned no result" )
Tool state constants (aligned with OpenCode)
const ( StreamEventToolCall = "tool_call" StreamEventToolInputStart = "tool_input_start" StreamEventToolInputEnd = "tool_input_end" StreamEventToolResult = "tool_result" StreamEventToolError = "tool_error" )
StreamResult tool event types
const ( ContextKeyTemperature = "temperature" ContextKeyMaxTokens = "max_tokens" ContextKeyTopP = "top_p" ContextKeyMaxCompletionTokens = "max_completion_tokens" ContextKeyReasoningEffort = "reasoning_effort" )
Context keys
const DefaultHistoryBreakpointBudget = 2
DefaultHistoryBreakpointBudget is the default number of breakpoints the history segment may consume (keeps total = system 1 + tool 1 + history 2 = 4).
const HeaderBudget = 512
HeaderBudget caps how many bytes the structured header (including the "Output:" guide line) may occupy. maxLen*0.25 is a floor below which the header yields to the body, so a tiny per-tool budget (e.g. 256) still leaves the bulk of the budget to the body rather than to the header.
const MaxAnthropicCacheBreakpoints = 4
MaxAnthropicCacheBreakpoints is the hard per-request limit enforced by the Anthropic Messages API. Clients must never exceed it.
const ToolErrorMaxLen = 400
Variables ¶
var BufferPool = sync.Pool{ New: func() interface{} { return make([]byte, 0, DefaultBufferPoolSize) }, }
BufferPool for reusing byte buffers to reduce GC pressure
Functions ¶
func ApplyMessageToolPersist ¶ added in v1.8.7
ApplyMessageToolPersist restores ToolCalls and ToolCallID from storage.
func BuildOutputHeader ¶ added in v1.10.0
func BuildOutputHeader(h OutputHeader) string
BuildOutputHeader renders the structured header as text. One line per non-zero field, then a final "Output:" guide line separating header from body (mirrors Codex's response_header). It is the only place that builds the header, so byte accounting for the budget happens once.
func FormatToolResult ¶ added in v1.6.13
func FormatToolResult(result interface{}) string
FormatToolResult formats tool execution result to string Uses JSON marshaling for better representation of complex data structures
func IsFatalToolError ¶ added in v1.10.0
IsFatalToolError reports whether err is a fatal tool error. The schema validation failure at agent_execution.go:407 is already wrapped in FatalToolError; dino-side veto/loop errors implement FatalToolErrorKind.
func MarshalMessageToolPersist ¶ added in v1.8.7
MarshalMessageToolPersist JSON for DB/redis; empty string if no tool fields.
func NormalizeToolError ¶ added in v1.7.0
func RoughTokenEstimate ¶ added in v1.8.11
func RoughTokensForMessage ¶ added in v1.8.11
func SanitizeToolResult ¶ added in v1.7.0
func SanitizeToolResult(result interface{}, maxTextLen int) interface{}
func SerializeMessageParts ¶ added in v1.6.14
func SerializeMessageParts(parts []MessagePart) (string, error)
SerializeMessageParts serializes message parts to JSON string
func TruncateMiddle ¶ added in v1.10.0
TruncateMiddle keeps the head and tail of s, joining them with an omission marker, so the model sees both ends of a large output instead of only the head. It is UTF-8 safe (never splits a multi-byte rune) and respects a byte budget including the marker.
The marker itself is counted inside the budget; the body share for head/tail is what remains. A minimum of minKeep bytes is given to each of head and tail; if the budget is too small for both, the head wins (the marker is shortened only as a last resort).
func TruncateString ¶ added in v1.6.13
TruncateString truncates a string to the specified length, keeping the head (a UTF-8-safe convenience used for logging and short labels). For tool-output truncation that preserves the middle, use TruncateMiddle.
Types ¶
type ActionMetadata ¶
type ActionMetadata struct {
ItemIndex int `json:"itemIndex"`
}
ActionMetadata action metadata
type ActionResponse ¶
type ActionResponse struct {
Action *ToolAction `json:"action"`
Data interface{} `json:"data"`
Error string `json:"error,omitempty"`
}
ActionResponse action response
type AgentConfig ¶
type AgentConfig struct {
MaxIterations int `json:"maxIterations"`
SystemMessage string `json:"systemMessage"`
ChatMessageRole string `json:"chatMessageRole,omitempty"`
Temperature float32 `json:"temperature"`
MaxTokens int `json:"maxTokens,omitempty"`
MaxCompletionTokens int `json:"maxCompletionTokens,omitempty"`
TopP float32 `json:"topP"`
FrequencyPenalty float32 `json:"frequencyPenalty"`
PresencePenalty float32 `json:"presencePenalty"`
StopSequences []string `json:"stopSequences"`
Timeout time.Duration `json:"timeout"`
ToolExecutionTimeout time.Duration `json:"toolExecutionTimeout"`
ToolTimeouts map[string]time.Duration `json:"toolTimeouts"`
RetryAttempts int `json:"retryAttempts"`
RetryDelay time.Duration `json:"retryDelay"`
EnableToolRetry bool `json:"enableToolRetry"`
MaxHistoryMessages int `json:"maxHistoryMessages"`
MaxBudgetTokens int `json:"maxBudgetTokens"`
RemainPromptTokens func() int `json:"-"`
EnableMemoryCompress bool `json:"enableMemoryCompress"`
MemoryCompressThreshold int `json:"memoryCompressThreshold"` // message count incl. each assistant + tool row from tool rounds
CompactAfterTurns int `json:"compactAfterTurns"` // completed Execute/ExecuteStream saves before compress; 0=off
MemoryCompressRatio float32 `json:"memoryCompressRatio"`
LogSilent bool `json:"logSilent"`
LogFile string `json:"logFile"`
DoomLoopThreshold int `json:"doomLoopThreshold"`
OnDoomLoop func(toolName string, input map[string]interface{}) bool `json:"-"`
ToolTimeoutCalculator func(toolName string, input map[string]interface{}) time.Duration `json:"-"`
MaxToolCallsPerIteration int `json:"maxToolCallsPerIteration"`
ToolResultWriteDir string `json:"toolResultWriteDir"`
DefaultToolResultMaxLen int `json:"defaultToolResultMaxLen"`
ToolErrorMaxLen int `json:"toolErrorMaxLen"`
ReasoningEffort string `json:"reasoningEffort"`
// PromptCaching enables provider prompt caching (Anthropic cache_control
// breakpoints) and cache usage backfill. Default on: it is a pure cost
// optimization with no correctness impact. Set false for providers/proxies
// that choke on cache_control (R9 escape hatch).
PromptCaching bool `json:"promptCaching,omitempty"`
ToolParallelismLimit int `json:"toolParallelismLimit,omitempty"` // 0=默认 max(4, GOMAXPROCS*2) 封顶 32;>0 用该值
StreamBufferSize int `json:"streamBufferSize,omitempty"` // 0=默认 50;>0 用该值
// ChunkMergeFlushInterval batches consecutive stream "chunk" results and
// flushes them as one merged chunk. 0=default 50ms. Disable merging by
// setting a value <0 (each fragment is sent immediately). Merging never
// affects end/error/tool_event delivery — those bypass the buffer.
ChunkMergeFlushInterval time.Duration `json:"chunkMergeFlushInterval,omitempty"` // 0=默认 50ms;<0 禁用合并;>0 用该值
// CompactionPrefix enables prefix-preserving compaction: trimHistoryToTokenBudget
// keeps a head cache anchor, replaces the middle with a tail summary, and
// preserves the recent tail verbatim, so prompt-cache breakpoints 1-2
// (system+tools) survive compaction (P3.1, prompt caching Step 4).
// Default off: with it off, trimHistoryToTokenBudget keeps today's behavior
// and the GetSummary head injection is unchanged (byte-identical).
CompactionPrefix bool `json:"compactionPrefix,omitempty"`
// CacheAnchorTokens caps the head-cache-anchor budget (tokens): the head of
// history, counted from index 0, is kept verbatim up to this many tokens so
// it participates in the cache prefix. 0 = no anchor (the head is trimmed
// like today, the middle is still replaced by the summary). Default 0.
CacheAnchorTokens int `json:"cacheAnchorTokens,omitempty"`
}
AgentConfig agent configuration
func NewAgentConfig ¶
func NewAgentConfig() *AgentConfig
func (*AgentConfig) EffectiveMaxCompletionTokens ¶ added in v1.8.12
func (c *AgentConfig) EffectiveMaxCompletionTokens() int
type AgentInput ¶ added in v1.6.13
type AgentInput struct {
Text string `json:"text,omitempty"`
Parts []MessagePart `json:"parts,omitempty"`
}
AgentInput agent execution input
func ConvertToAgentInput ¶ added in v1.6.13
func ConvertToAgentInput(input interface{}) (AgentInput, error)
ConvertToAgentInput converts input to AgentInput Supports string and AgentInput types
func NewAgentInput ¶ added in v1.6.13
func NewAgentInput(text string) AgentInput
NewAgentInput creates a new agent input with text
func NewAgentInputWithParts ¶ added in v1.6.13
func NewAgentInputWithParts(parts []MessagePart) AgentInput
NewAgentInputWithParts creates a new agent input with message parts
func (AgentInput) String ¶ added in v1.6.13
func (i AgentInput) String() string
String returns the string representation of the input
func (AgentInput) ToMessage ¶ added in v1.6.13
func (i AgentInput) ToMessage(role string) Message
ToMessage converts AgentInput to Message
type AgentResult ¶ added in v1.6.13
type AgentResult struct {
Output string `json:"output"`
ToolCalls []ToolCallRequest `json:"tool_calls"`
IntermediateSteps []ToolCallData `json:"intermediate_steps"`
Usage Usage `json:"usage"`
StopCause AgentStopCause `json:"stop_cause,omitempty"`
}
==================== Data Structures and Type Definitions ==================== AgentResult agent execution result
type AgentStopCause ¶ added in v1.9.0
type AgentStopCause string
const ( AgentStopCauseNone AgentStopCause = "" AgentStopCauseMaxIterations AgentStopCause = "max_iterations" AgentStopCauseContextWindow AgentStopCause = "context_window" AgentStopCauseDoomLoop AgentStopCause = "doom_loop" )
func StopCauseFromChatError ¶ added in v1.9.0
func StopCauseFromChatError(err error) AgentStopCause
type EngineRequest ¶
type EngineRequest struct {
Actions []ToolAction `json:"actions"`
Metadata RequestResponseMetadata `json:"metadata"`
}
EngineRequest engine request
type EngineResponse ¶
type EngineResponse struct {
ActionResponses []ActionResponse `json:"actionResponses"`
Metadata RequestResponseMetadata `json:"metadata"`
}
EngineResponse engine response
type FatalToolError ¶ added in v1.10.0
FatalToolError marks a tool error that is NOT recoverable by feeding it back to the model: retrying the same input cannot succeed. Fatal errors should surface to the engine and stop (or restructure) the current iteration rather than being converted into a recoverable {ok:false} result.
Examples: schema/input validation failures, permission/approval vetoes, a tool that does not exist. nonFatalTool passes these through as real errors.
func (*FatalToolError) Error ¶ added in v1.10.0
func (e *FatalToolError) Error() string
func (*FatalToolError) FatalToolErrorKind ¶ added in v1.10.0
func (e *FatalToolError) FatalToolErrorKind()
FatalToolErrorKind implements agent/types.FatalToolErrorKind.
func (*FatalToolError) Unwrap ¶ added in v1.10.0
func (e *FatalToolError) Unwrap() error
type FatalToolErrorKind ¶ added in v1.10.0
type FatalToolErrorKind interface {
error
FatalToolErrorKind()
}
FatalToolErrorKind is implemented by every error type the tool pipeline treats as FATAL (F3/P4.2): an error that cannot be fixed by retrying the same input, so it must surface to the engine and unwind the iteration instead of being fed back to the model as a recoverable {ok:false} result. Engine code recognizes fatal errors via FatalToolErrorKindOf/IsFatalToolError without importing dino; dino/tools errors (ApprovalRejectedError, LoopDetectedError) implement it so a user veto or a loop also short-circuits the errgroup like a schema failure.
Errors that are NOT fatal but still carry error codes (EC_TOOL_INPUT_ERROR, EC_TOOL_AUTH_ERROR, MCP 11xxx, EC_TOOL_EXECUTION_TIMEOUT, …) are recoverable: the model can change arguments or retry later, so they are fed back.
func FatalToolErrorKindOf ¶ added in v1.10.0
func FatalToolErrorKindOf(err error) FatalToolErrorKind
FatalToolErrorKindOf classifies an error as fatal (FatalToolErrorKind) or recoverable (nil). It unwraps %w-wrapped errors.
type ImageDataPart ¶
ImageDataPart image data part
type ImageURLPart ¶
type ImageURLPart struct {
URL string `json:"url"`
Detail string `json:"detail,omitempty"` // "low", "high", "auto"
}
ImageURLPart image URL part
type LLMProvider ¶
type LLMProvider interface {
// Basic chat functionality
Chat(ctx context.Context, messages []Message) (Message, error)
ChatStream(ctx context.Context, messages []Message) (<-chan StreamMessage, error)
// Tool call support
ChatWithTools(ctx context.Context, messages []Message, tools []Tool) (Message, error)
ChatWithToolsStream(ctx context.Context, messages []Message, tools []Tool) (<-chan StreamMessage, error)
// Model information
GetModelName() string
GetModelMetadata() ModelMetadata
}
LLMProvider defines LLM provider interface
type LangChainToolWrapper ¶
type LangChainToolWrapper struct {
// contains filtered or unexported fields
}
LangChainToolWrapper LangChain tool wrapper
func NewLangChainToolWrapper ¶
func NewLangChainToolWrapper(tool Tool) *LangChainToolWrapper
NewLangChainToolWrapper creates a new LangChain tool wrapper
func (*LangChainToolWrapper) Description ¶
func (w *LangChainToolWrapper) Description() string
Description returns tool description
func (*LangChainToolWrapper) Name ¶
func (w *LangChainToolWrapper) Name() string
Name returns tool name
type MemoryProvider ¶
type MemoryProvider interface {
// Load memory variables
LoadMemoryVariables(ctx context.Context) (map[string]interface{}, error)
// Save context
SaveContext(ctx context.Context, input, output map[string]interface{}) error
// Clear memory
Clear(ctx context.Context) error
// GetChatHistory returns history sized for LLM context: implementations MUST window (e.g. match GetMessages(limit<=0): maxHistoryMessages cap + optional summary). Returning the full unbounded store will blow prompts; the engine does not apply a second message-count cut. Optional: implement StoredMessageCount(ctx) for compress gating (see agent/engine).
GetChatHistory(ctx context.Context) ([]Message, error)
// Compress memory (optional, for memory compression)
CompressMemory(ctx context.Context, llm LLMProvider, maxMessages int) error
}
MemoryProvider memory system interface
type MemoryReplay ¶ added in v1.8.11
type Message ¶
type Message struct {
Role string `json:"role"` // "system", "user", "assistant", "tool"
Content string `json:"content"`
Name string `json:"name,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
Parts []MessagePart `json:"parts,omitempty"` // Multi-modal content support
Usage Usage `json:"usage,omitempty"` // Token usage information
}
Message message structure
func MessagesFromToolSteps ¶ added in v1.8.7
func MessagesFromToolSteps(assistantContent string, steps []ToolCallData) []Message
MessagesFromToolSteps builds assistant (with tool_calls) and tool messages for one model turn.
type MessagePart ¶
type MessagePart interface {
// contains filtered or unexported methods
}
MessagePart message part interface
func DeserializeMessageParts ¶ added in v1.6.14
func DeserializeMessageParts(data string) ([]MessagePart, error)
DeserializeMessageParts deserializes JSON string to message parts
type ModelMetadata ¶
type ModelMetadata struct {
Name string `json:"name"`
Version string `json:"version"`
MaxTokens int `json:"maxTokens"`
Tools []Tool `json:"tools,omitempty"`
Extra map[string]interface{} `json:"extra,omitempty"`
}
ModelMetadata model metadata
type OutputHeader ¶ added in v1.10.0
type OutputHeader struct {
ChunkID string `json:"chunk_id,omitempty"`
WallTime time.Duration `json:"wall_time,omitempty"` // execution duration
ExitCode *int `json:"exit_code,omitempty"` // bash etc. when available
OriginalBytes int `json:"original_bytes,omitempty"` // raw output bytes before truncation
OriginalTokens int `json:"original_tokens,omitempty"` // approximate, via RoughTokenEstimate
TotalLines int `json:"total_lines,omitempty"` // line count of the raw output
SavedPath string `json:"saved_path,omitempty"` // when output was written to disk instead
OmittedCharCount int `json:"omitted_chars,omitempty"` // chars elided by TruncateMiddle
}
OutputHeader is the structured header prepended to a truncated tool output. Any field with a zero value omits its line (mirroring Codex's response_header).
type OutputParser ¶
type OutputParser interface {
Parse(output string) (interface{}, error)
GetFormatInstructions() string
}
OutputParser output parser interface
type PromptCacheConfigurer ¶ added in v1.10.0
type PromptCacheConfigurer interface {
SetPromptCacheOptions(PromptCacheOptions)
PromptCacheOptions() PromptCacheOptions
}
PromptCacheConfigurer is implemented by LLM providers that support prompt cache breakpoint injection (e.g. NativeAnthropicProvider). Defined here in agent/types (B3) so the engine can assert it without importing agent/llm.
The getter lets the engine merge AgentConfig.PromptCaching (Enabled) onto whatever sub-field options the provider was already configured with (e.g. dino's PromptCachingConfig overrides), instead of rebuilding from defaults and silently dropping them.
type PromptCacheOptions ¶ added in v1.10.0
type PromptCacheOptions struct {
Enabled bool // master switch; when false the request body is byte-identical to pre-caching
SystemBreakpoint bool // 1 breakpoint on the system block
ToolsBreakpoint bool // 1 breakpoint on the LAST tool only
HistoryEveryN int // history breakpoint budget (0 = no history breakpoints)
MinCacheTokens int // history segment below this (estimated tokens) gets no history breakpoint
}
PromptCacheOptions controls provider prompt caching (Anthropic cache_control breakpoints) and cache usage backfill.
B2 (review): Anthropic enforces a hard limit of MaxAnthropicCacheBreakpoints (4) cache_control breakpoints per request; exceeding it returns HTTP 400. The layout is therefore budget-based:
system (≤1) + last tool (≤1) + history (≤ HistoryEveryN, capped to 4 total)
HistoryEveryN is a *budget* for the history segment (how many breakpoints the history may consume), NOT an "every N messages" interval. When the budget would exceed the hard cap, the layout degrades by dropping history breakpoints rather than risking a 400.
func DefaultPromptCacheOptions ¶ added in v1.10.0
func DefaultPromptCacheOptions() PromptCacheOptions
DefaultPromptCacheOptions returns the default prompt caching behavior.
R2 (review): MinCacheTokens defaults to 4096 because newer models (Opus 4.x, Sonnet 4.6+) require a 2048-4096 token minimum prefix before a breakpoint is honored; 1024 would silently not cache on those models.
type ReasoningMessage ¶ added in v1.8.0
type ReasoningMessage struct {
Content string `json:"content"`
Reasoning string `json:"reasoning,omitempty"`
}
ReasoningMessage represents a message with reasoning/thinking content
type RequestResponseMetadata ¶
type RequestResponseMetadata struct {
ItemIndex int `json:"itemIndex,omitempty"`
PreviousRequests []ToolCallData `json:"previousRequests,omitempty"`
IterationCount int `json:"iterationCount,omitempty"`
}
RequestResponseMetadata request response metadata
type StreamEvent ¶
type StreamEvent struct {
Type string `json:"type"`
Content string `json:"content,omitempty"`
ToolResult interface{} `json:"toolResult,omitempty"`
EventName string `json:"eventName,omitempty"`
Data interface{} `json:"data,omitempty"`
}
StreamEvent stream event
type StreamMessage ¶
type StreamMessage struct {
Type string `json:"type"` // "chunk", "end", "error", "tool_calls", "reasoning"
Content string `json:"content,omitempty"`
Reasoning string `json:"reasoning,omitempty"` // Thinking/reasoning content
Error string `json:"error,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Usage *Usage `json:"usage,omitempty"`
}
StreamMessage streaming message
type StreamResult ¶ added in v1.6.13
type StreamResult struct {
Type string
Content string
Result *AgentResult
Error error
// Tool event fields
ToolEvent *ToolEvent
// StopCause classifies Error (e.g. context_window) for harness consumers.
StopCause AgentStopCause
}
StreamResult streaming result
type Tool ¶
type Tool interface {
// Tool basic information
Name() string
Description() string
Schema() map[string]interface{}
// Tool execution
Execute(ctx context.Context, input map[string]interface{}) (interface{}, error)
// Tool metadata
Metadata() ToolMetadata
}
Tool defines tool interface
type ToolAction ¶
type ToolAction struct {
NodeName string `json:"nodeName"`
Input map[string]interface{} `json:"input"`
Type string `json:"type"`
ID string `json:"id"`
Metadata ActionMetadata `json:"metadata"`
}
ToolAction tool action
type ToolActionStep ¶
type ToolActionStep struct {
Tool string `json:"tool"`
ToolInput interface{} `json:"toolInput"`
Log interface{} `json:"log"`
ToolCallID interface{} `json:"toolCallId"`
Type interface{} `json:"type"`
}
ToolActionStep tool action step
type ToolCacheEntry ¶ added in v1.6.13
type ToolCacheEntry struct {
Result interface{}
Err error
Timestamp time.Time
Prev *ToolCacheEntry
Next *ToolCacheEntry
Key string
}
ToolCacheEntry tool cache entry with LRU support
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function ToolFunction `json:"function"`
}
ToolCall tool call
type ToolCallData ¶
type ToolCallData struct {
Action ToolActionStep `json:"action"`
Observation string `json:"observation"`
}
ToolCallData tool call data
type ToolCallRequest ¶
type ToolCallRequest struct {
Tool string `json:"tool"`
ToolInput map[string]interface{} `json:"toolInput"`
ToolCallID string `json:"toolCallId"`
Type string `json:"type,omitempty"`
Log string `json:"log,omitempty"`
MessageLog []interface{} `json:"messageLog,omitempty"`
}
ToolCallRequest tool call request
type ToolCallback ¶ added in v1.7.3
type ToolCallback interface {
OnToolCall(toolName string, toolCallID string, input map[string]interface{})
OnToolInputStart(toolName string, toolCallID string, input map[string]interface{})
OnToolInputEnd(toolName string, toolCallID string, input map[string]interface{})
OnToolResult(toolName string, toolCallID string, output interface{})
OnToolError(toolName string, toolCallID string, err error)
}
ToolCallback is an interface for receiving tool execution events in real-time
type ToolCallbackFunc ¶ added in v1.7.3
type ToolCallbackFunc struct {
// contains filtered or unexported fields
}
ToolCallbackFunc is a functional adapter for ToolCallback
func (*ToolCallbackFunc) OnToolCall ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolCall(toolName string, toolCallID string, input map[string]interface{})
func (*ToolCallbackFunc) OnToolError ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolError(toolName string, toolCallID string, err error)
func (*ToolCallbackFunc) OnToolInputEnd ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolInputEnd(toolName string, toolCallID string, input map[string]interface{})
func (*ToolCallbackFunc) OnToolInputStart ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolInputStart(toolName string, toolCallID string, input map[string]interface{})
func (*ToolCallbackFunc) OnToolResult ¶ added in v1.7.3
func (f *ToolCallbackFunc) OnToolResult(toolName string, toolCallID string, output interface{})
type ToolEvent ¶ added in v1.7.3
type ToolEvent struct {
Event string // Event type: tool_call, tool_input_start, tool_input_end, tool_result, tool_error
ToolName string // Tool name
ToolCallID string // Tool call ID
State string // State: pending, running, completed, error
Input map[string]interface{} // Tool input arguments
Output interface{} // Tool execution result
Error string // Error message if failed
Duration time.Duration // Execution duration
}
ToolEvent represents a tool execution lifecycle event
type ToolExposure ¶ added in v1.10.0
type ToolExposure string
ToolExposure controls a tool's visibility in the model's initial tool list (E1). Registration and model-visibility are decoupled: a tool stays registered (dispatchable) regardless of its exposure.
- ExposureDirect: registered AND visible in the initial list (current default).
- ExposureDeferred: registered but NOT in the initial list; the model finds it via tool_search, and it is injected into ae.tools the next iteration.
- ExposureHidden: registered and dispatchable by the engine, never visible to the model (reserved for escape-hatch / internal orchestration tools).
const ( // ExposureDirect 默认:注册即对模型可见(现状行为)。空值等价于 Direct。 ExposureDirect ToolExposure = "direct" // ExposureDeferred 注册可分发但初始列表不可见;模型通过 tool_search 发现后 // 下一轮才注入为正式工具。 ExposureDeferred ToolExposure = "deferred" // ExposureHidden 完全不可见(但仍可被引擎内部分发)。 ExposureHidden ToolExposure = "hidden" )
func (ToolExposure) IsDeferred ¶ added in v1.10.0
func (e ToolExposure) IsDeferred() bool
IsDeferred reports whether the exposure is deferred.
func (ToolExposure) IsDirect ¶ added in v1.10.0
func (e ToolExposure) IsDirect() bool
IsDirect reports whether the exposure yields initial-list visibility. The empty value is treated as Direct (zero migration: tools that never set Exposure keep current behavior).
func (ToolExposure) IsHidden ¶ added in v1.10.0
func (e ToolExposure) IsHidden() bool
IsHidden reports whether the exposure is hidden.
type ToolFunction ¶
type ToolFunction struct {
Name string `json:"name"`
Arguments map[string]interface{} `json:"arguments"`
}
ToolFunction tool function
type ToolMetadata ¶
type ToolMetadata struct {
SourceNodeName string `json:"sourceNodeName"`
IsFromToolkit bool `json:"isFromToolkit"`
ToolType string `json:"toolType"` // "mcp","http","builtin"
Priority int `json:"priority,omitempty"` // 优先级,数字越大优先级越高
Dependencies []string `json:"dependencies,omitempty"` // 依赖的工具名称列表
MaxTruncationLength int `json:"maxTruncationLength,omitempty"` // 工具结果截断长度,0表示使用默认值
Exposure ToolExposure `json:"exposure,omitempty"` // E1:模型可见性;空值=direct(向后兼容)
SearchKeywords []string `json:"searchKeywords,omitempty"` // E2:tool_search 索引关键词;空则用 Name+Description 分词
Extra map[string]interface{} `json:"extra,omitempty"`
}
ToolMetadata tool metadata
type TruncationMeta ¶ added in v1.10.0
TruncationMeta reports what a truncation did so the caller can record it.
func TruncateToolResult ¶ added in v1.7.0
func TruncateToolResult(content string, maxLen int, writeDir string, header OutputHeader) (display string, meta TruncationMeta)
TruncateToolResult is the single truncation entry point. It guarantees the returned display string is at most maxLen bytes (header + marker + body all within budget) and is UTF-8 safe.
When writeDir is non-empty and the raw output is huge (OriginalBytes > maxLen*8), the full output is written to a file and the display becomes just the header + a "saved to" hint — the body does not enter the context at all. Otherwise the display is header + "Output:" guide + TruncateMiddle result.
type Usage ¶ added in v1.6.10
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
ReasoningTokens int `json:"reasoning_tokens,omitempty"` // Thinking tokens (o1, o3 series etc.)
CachedTokens int `json:"cached_tokens,omitempty"` // Cache read tokens (0.1x price)
CacheCreationTokens int `json:"cache_creation_tokens,omitempty"` // Cache write tokens (1.25x price)
}
Usage token usage information
B1 (review): PromptTokens/TotalTokens must reflect the *total* input (uncached + cached read + cache creation), because Anthropic's `input_tokens` is the uncached remainder only. CachedTokens/CacheCreationTokens are a split *within* the input.