Documentation
¶
Overview ¶
Package agentloop implements EdgeFetch's vendor-neutral BYO-LLM configuration, origin/path-prefix API key isolation, SSRF validation, log redaction, provider wire codecs (OpenAI/OpenRouter/Compatible, Anthropic, Gemini, Ollama, Workers AI), JSON Schema validation, <1ms dynamic BM25 adapter intent routing, remote MCP tool schema sanitization, and the callback-driven /v1/agent research loop engine.
The package has zero net/http or crypto/tls dependencies so it compiles cleanly to both WASI WASM (GOOS=wasip1 GOARCH=wasm) and native Go binaries (--mode=hub).
Index ¶
- Constants
- func AppendEndpointToBaseURL(baseURL, suffixPath, alreadyEndsWith string) string
- func BuildDeterministicSummary(markdown, title string) string
- func BuildWorkersAIInput(params LLMProviderTurnParams) map[string]any
- func CapStepToolResults(ins []ToolResultInput, b ToolResultBudget) []string
- func CapToolResult(in ToolResultInput, b ToolResultBudget) string
- func DefaultTotalIndexedAdapters() int
- func DoesMCPServerSelectorMatchRow(rawSelector, rowID, rowSlug string) bool
- func ExtractJSONWithOptionalLLM(ctx context.Context, markdown, title, urlStr, prompt string, ...) (data map[string]any, viaLLM bool)
- func FilterSafeAgentBrowserActions(rawActions []any) []map[string]any
- func FormatFenceSafeUntrustedMCPEnvelope(tag string, attrs map[string]string, content string, maxChars int) string
- func FormatPublicAgentResponse(rec AgentRunRecord, includeTrace bool) map[string]any
- func IsClaudeModelID(model string) bool
- func IsSafeMCPIdentifier(raw string) bool
- func IsURLAllowedByConstraint(candidateURL string, allowedSeeds []string, strictConstrain bool) bool
- func IsValidMCPConnectorSlug(raw string) bool
- func MatchesTrustedBaseURLPrefix(candidateURLStr, trustedURLStr string) bool
- func ParseAgentLocation(rawCountry string, rawLanguages []string) (country string, languages []string, acceptLanguage string)
- func ParseLooseJSONObject(raw string) map[string]any
- func RedactHeadersForLog(rawHeaders map[string]string) map[string]string
- func RedactLLMConfigForLog(cfg *LoggableLLMConfigInput) map[string]any
- func RedactLLMURLForLog(rawURL string) string
- func SanitizeMCPMarkdownOutput(rawMarkdown, baseURL string, maxChars int) string
- func SanitizeRemoteMCPText(raw string, maxChars int) (text string, detected bool)
- func SanitizeRemoteToolSchemaForLLM(rawNode any, depth int) map[string]any
- func SanitizeRemoteToolSchemaJSON(rawNode json.RawMessage, depth int) map[string]any
- func StripMCPSmugglingChars(s string) string
- func StripThinkBlocksLinear(raw string) string
- func SummarizeMarkdownWithOptionalLLM(ctx context.Context, markdown, title string, llmConfig *ResolvedLLMConfig, ...) (summary string, viaLLM bool)
- func ValidateCleanHTTPBaseURL(rawURL string) (normalized string, parsed *parsedHTTPURL, errMsg string, ok bool)
- func WrapConnectorTextForAgentContext(rawText string, maxChars int, attrs map[string]string) string
- type AdapterCatalogItem
- type AgentEffort
- type AgentEvidenceItem
- type AgentInitialMessagesInput
- type AgentLoopCallbacks
- type AgentRunRecord
- type AgentSourceRef
- type AgentStatus
- type AgentStopReason
- type AgentToolExecutionOutput
- type AgentToolInvocation
- type AgentTraceSpan
- type CachedMCPToolSpec
- type ConnectedMCPServerSpec
- type FindRelevantAdaptersInput
- type LLMChatCompletionResult
- func CompleteLLMTurn(ctx context.Context, params LLMProviderTurnParams, timeout time.Duration, ...) LLMChatCompletionResult
- func ParseProviderHTTPResponse(provider LLMProvider, status int, rawBody []byte, allowedToolNames []string) LLMChatCompletionResult
- func ParseWorkersAIResponse(rawOut map[string]any, allowedToolNames []string) LLMChatCompletionResult
- type LLMEnvConfig
- type LLMMessage
- type LLMProvider
- type LLMProviderTurnParams
- type LLMTokenUsage
- type LLMToolCall
- type LLMToolDefinition
- type LLMTransportFunc
- type LLMTransportRequest
- type LLMTransportResponse
- type LoggableLLMConfigInput
- type ProviderHTTPRequest
- type PublicURLCheckResult
- type RankedAdapterMatch
- type ResolveLLMConfigInput
- type ResolveLLMConfigOutput
- type ResolvedLLMConfig
- type RunAgentLoopInput
- type SchemaValidationResult
- type ToolExecutorFunc
- type ToolResultBudget
- type ToolResultInput
- type ToolResultKind
Constants ¶
const ( // UntrustedRemoteParamPrefix marks every sanitized remote MCP tool parameter description in the LLM tools channel (P7). UntrustedRemoteParamPrefix = "[UNTRUSTED_REMOTE_PARAM] " // MaxConcurrentAgentsPerUser caps concurrent active /v1/agent runs per user. MaxConcurrentAgentsPerUser = 4 )
const ( // DefaultToolResultMaxChars caps one tool result, in Unicode code points (runes). DefaultToolResultMaxChars = 15000 // DefaultToolResultMaxLines caps one text tool result, in lines. DefaultToolResultMaxLines = 200 // DefaultStepToolResultMaxChars caps the sum of all tool results returned to the model in one step. DefaultStepToolResultMaxChars = 60000 )
Tool-result context budgets for the /v1/agent loop. Every tool result fed back to the model is capped so that no single result (and no single step of parallel tool calls) can flood the LLM context window.
const BudgetFinalAnswerPrompt = "You have reached this run's step budget and cannot call any more tools. " +
"Answer the original request now, using only what you have already read in this conversation. " +
"Cite the source URLs you used. If what you read is incomplete, say so in one short sentence."
BuildAgentInitialMessages builds the initial system and user messages for the autonomous BYO-LLM agent loop. H4 Security Invariant: NEVER interpolates remote MCP tool names or property names into the system prompt. BudgetFinalAnswerPrompt is appended as a final user turn when an agent run exhausts its step or page budget before the model produced a final answer, so the answer is written from the full conversation (question plus everything read) instead of a generic page summary.
const MaxLLMResponseBytes = 4 * 1024 * 1024
MaxLLMResponseBytes caps raw LLM API JSON responses at 4 MiB (H5).
Variables ¶
This section is empty.
Functions ¶
func AppendEndpointToBaseURL ¶
AppendEndpointToBaseURL appends an endpoint path to baseUrl while preserving any operator query string.
func BuildDeterministicSummary ¶
BuildDeterministicSummary extracts a zero-LLM extractive summary (lead paragraph + key bullets/headings).
func BuildWorkersAIInput ¶
func BuildWorkersAIInput(params LLMProviderTurnParams) map[string]any
BuildWorkersAIInput constructs the input payload for Cloudflare Workers AI env.AI.run(model, inputs).
func CapStepToolResults ¶ added in v2.8.42
func CapStepToolResults(ins []ToolResultInput, b ToolResultBudget) []string
CapStepToolResults caps each result and then enforces the per-step total: when the capped results still exceed MaxStepChars, the largest results are shrunk first (water-filling) until the total fits. Order is preserved.
func CapToolResult ¶ added in v2.8.42
func CapToolResult(in ToolResultInput, b ToolResultBudget) string
CapToolResult applies the per-result caps. Results within both caps are returned byte-for-byte unchanged. Structured JSON results stay valid JSON (inner strings and arrays are shortened instead of slicing the text).
func DefaultTotalIndexedAdapters ¶
func DefaultTotalIndexedAdapters() int
DefaultTotalIndexedAdapters returns the total count of indexed built-in keyless adapters.
func DoesMCPServerSelectorMatchRow ¶
DoesMCPServerSelectorMatchRow enforces S7: mcpServers selectors match strictly by exact connector id or slug (case-insensitive).
func ExtractJSONWithOptionalLLM ¶
func ExtractJSONWithOptionalLLM( ctx context.Context, markdown, title, urlStr, prompt string, schema map[string]any, heuristicFallback map[string]any, llmConfig *ResolvedLLMConfig, transport LLMTransportFunc, ) (data map[string]any, viaLLM bool)
ExtractJSONWithOptionalLLM extracts structured JSON via an optional BYO-LLM config, merging over heuristicFallback.
func FilterSafeAgentBrowserActions ¶
FilterSafeAgentBrowserActions enforces M8: allowlists only non-navigating, non-JS-executing browser actions.
func FormatFenceSafeUntrustedMCPEnvelope ¶
func FormatFenceSafeUntrustedMCPEnvelope(tag string, attrs map[string]string, content string, maxChars int) string
FormatFenceSafeUntrustedMCPEnvelope wraps untrusted MCP output in a backtick-fence-safe + XML-boundary-safe envelope.
func FormatPublicAgentResponse ¶
func FormatPublicAgentResponse(rec AgentRunRecord, includeTrace bool) map[string]any
FormatPublicAgentResponse converts an internal AgentRunRecord into its public API JSON shape, stripping internal fields (userId, prompt, urls, threadMemory) and scrubbing trace unless includeTrace is true.
func IsClaudeModelID ¶ added in v2.8.21
IsClaudeModelID reports whether an OpenAI-compatible model id routes to Anthropic Claude (e.g. OpenRouter "anthropic/claude-haiku-5.5"). Such requests omit temperature, which current Claude models reject.
func IsSafeMCPIdentifier ¶
IsSafeMCPIdentifier validates an MCP tool or parameter identifier against prototype pollution, `__`, and directive injection.
func IsURLAllowedByConstraint ¶
func IsURLAllowedByConstraint(candidateURL string, allowedSeeds []string, strictConstrain bool) bool
IsURLAllowedByConstraint validates candidateURL against strictConstrainToURLs seed URL prefixes.
func IsValidMCPConnectorSlug ¶
IsValidMCPConnectorSlug validates a normalized MCP connector slug.
func MatchesTrustedBaseURLPrefix ¶
MatchesTrustedBaseURLPrefix checks whether candidateURL is on the exact same origin and path-prefix as trustedURL.
func ParseAgentLocation ¶
func ParseAgentLocation(rawCountry string, rawLanguages []string) (country string, languages []string, acceptLanguage string)
ParseAgentLocation validates optional ISO-3166 country and BCP-47 language tags.
func ParseLooseJSONObject ¶
ParseLooseJSONObject extracts a JSON object from raw LLM text, stripping <think>...</think> blocks and optional Markdown code fences in O(N) time (M12).
func RedactHeadersForLog ¶
RedactHeadersForLog redacts sensitive header names and token-like values.
func RedactLLMConfigForLog ¶
func RedactLLMConfigForLog(cfg *LoggableLLMConfigInput) map[string]any
RedactLLMConfigForLog produces a zero-secret log summary of a resolved LLM config.
func RedactLLMURLForLog ¶
RedactLLMURLForLog strips userinfo, query strings, fragments, and non-allowlisted path segments from an LLM URL.
func SanitizeMCPMarkdownOutput ¶
SanitizeMCPMarkdownOutput sanitizes untrusted MCP Markdown/text, neutralizes boundary tags, and strips dangerous URI schemes.
func SanitizeRemoteMCPText ¶
SanitizeRemoteMCPText strips smuggling runes and checks/scrubs indirect prompt injection.
func SanitizeRemoteToolSchemaForLLM ¶
SanitizeRemoteToolSchemaForLLM sanitizes an in-memory remote tool parameter schema map.
func SanitizeRemoteToolSchemaJSON ¶
func SanitizeRemoteToolSchemaJSON(rawNode json.RawMessage, depth int) map[string]any
SanitizeRemoteToolSchemaJSON implements P7: rebuilds a remote MCP tool parameter JSON Schema for the LLM tools channel, stripping title/default/examples/$defs/$comment/const/raw enum and prefixing sanitized descriptions with [UNTRUSTED_REMOTE_PARAM].
func StripMCPSmugglingChars ¶
StripMCPSmugglingChars removes ANSI CSI sequences, ASCII C0/DEL controls, zero-width/bidi controls, and Unicode Tag characters.
func StripThinkBlocksLinear ¶
StripThinkBlocksLinear strips closed <think>...</think> reasoning blocks in strictly linear O(N) time (M12).
func SummarizeMarkdownWithOptionalLLM ¶
func SummarizeMarkdownWithOptionalLLM( ctx context.Context, markdown, title string, llmConfig *ResolvedLLMConfig, transport LLMTransportFunc, ) (summary string, viaLLM bool)
SummarizeMarkdownWithOptionalLLM summarizes Markdown via an optional BYO-LLM config, falling back deterministically.
func ValidateCleanHTTPBaseURL ¶
func ValidateCleanHTTPBaseURL(rawURL string) (normalized string, parsed *parsedHTTPURL, errMsg string, ok bool)
ValidateCleanHTTPBaseURL validates an untrusted or operator HTTP(S) LLM baseUrl against traversal, double-encoding, credentials, query/fragment smuggling, and empty segments.
Types ¶
type AdapterCatalogItem ¶
type AdapterCatalogItem struct {
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
Description string `json:"description"`
Domains []string `json:"domains"`
ExampleURLs []string `json:"exampleUrls"`
}
AdapterCatalogItem describes an indexed keyless site or ATS adapter for dynamic intent routing.
func DefaultAdapterCatalog ¶
func DefaultAdapterCatalog() []AdapterCatalogItem
DefaultAdapterCatalog returns a copy of all embedded declarative + built-in ATS adapters.
type AgentEffort ¶
type AgentEffort string
AgentEffort controls default reasoning step and page budgets.
const ( EffortLow AgentEffort = "low" EffortMedium AgentEffort = "medium" EffortHigh AgentEffort = "high" )
func ParseEffortBudgets ¶
func ParseEffortBudgets(rawEffort string, rawMaxSteps, rawMaxPages, rawMaxCredits *float64) (effort AgentEffort, maxSteps int, maxPages int)
ParseEffortBudgets computes bounded maxSteps and maxPages budgets for low/medium/high effort levels.
type AgentEvidenceItem ¶
type AgentEvidenceItem struct {
URL string `json:"url"`
Title string `json:"title,omitempty"`
Markdown string `json:"markdown"`
JSON map[string]any `json:"json,omitempty"`
FromMCP bool `json:"fromMcp,omitempty"`
MCPServer string `json:"mcpServer,omitempty"`
MCPTool string `json:"mcpTool,omitempty"`
}
AgentEvidenceItem represents a scraped page or MCP tool output collected during an agent run.
type AgentInitialMessagesInput ¶
type AgentInitialMessagesInput struct {
Prompt string `json:"prompt"`
SeedURLs []string `json:"seedUrls,omitempty"`
StrictConstrainToURLs bool `json:"strictConstrainToURLs"`
MaxSteps int `json:"maxSteps"`
MaxPages int `json:"maxPages"`
HasConnectedMCPs bool `json:"hasConnectedMcps"`
InitialMatches []RankedAdapterMatch `json:"initialMatches,omitempty"`
Schema map[string]any `json:"schema,omitempty"`
PriorThreadID string `json:"priorThreadId,omitempty"`
ReplayedPriorThreadEnvelope string `json:"replayedPriorThreadEnvelope,omitempty"`
}
AgentInitialMessagesInput holds parameters for constructing the initial system + user messages of an /v1/agent run.
type AgentLoopCallbacks ¶
type AgentLoopCallbacks struct {
LLMTransport LLMTransportFunc
ExecuteTool ToolExecutorFunc
IsCancelled func() bool
OnPersist func(rec *AgentRunRecord) error
OnEvent func(event string, data map[string]any)
NowMs func() int64
}
AgentLoopCallbacks wires host I/O, persistence, cancellation, and SSE event streaming into RunAgentLoop.
type AgentRunRecord ¶
type AgentRunRecord struct {
ID string `json:"id"`
UserID string `json:"userId,omitempty"`
ThreadID string `json:"threadId"`
Status AgentStatus `json:"status"`
StopReason AgentStopReason `json:"stopReason,omitempty"`
Prompt string `json:"prompt"`
URLs []string `json:"urls"`
StrictConstrainToURLs bool `json:"strictConstrainToURLs"`
Effort AgentEffort `json:"effort"`
MaxSteps int `json:"maxSteps"`
MaxPages int `json:"maxPages"`
StepsUsed int `json:"stepsUsed"`
PagesRead int `json:"pagesRead"`
Partial bool `json:"partial,omitempty"`
PartialSchemaValid *bool `json:"partialSchemaValid,omitempty"`
SchemaValid *bool `json:"schemaValid,omitempty"`
ZeroDataRetention bool `json:"zeroDataRetention"`
Visibility string `json:"visibility,omitempty"`
RoutedMCPs []string `json:"routedMcps,omitempty"`
LLMUsed bool `json:"llmUsed"`
LLMInfo map[string]any `json:"llmInfo,omitempty"`
RoutedAdapters []string `json:"routedAdapters"`
Sources []AgentSourceRef `json:"sources"`
Data any `json:"data,omitempty"`
HasData bool `json:"hasData,omitempty"`
Markdown string `json:"markdown,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt int64 `json:"createdAt"`
UpdatedAt int64 `json:"updatedAt"`
FinishedAt *int64 `json:"finishedAt,omitempty"`
ExpiresAt int64 `json:"expiresAt"`
Trace []AgentTraceSpan `json:"trace"`
ThreadMemory string `json:"threadMemory,omitempty"`
}
AgentRunRecord holds full state for an /v1/agent execution.
func RunAgentLoop ¶
func RunAgentLoop(ctx context.Context, in RunAgentLoopInput, cb AgentLoopCallbacks) (*AgentRunRecord, error)
RunAgentLoop executes the complete /v1/agent state machine (initial BM25 adapter routing, multi-step BYO-LLM tool loop or zero-key deterministic research fallback, schema/Markdown synthesis, partial budget recovery, and ZDR).
type AgentSourceRef ¶
type AgentSourceRef struct {
URL string `json:"url"`
Title string `json:"title,omitempty"`
Via string `json:"via,omitempty"`
ExtractorID string `json:"extractorId,omitempty"`
}
AgentSourceRef identifies a cited URL or MCP source in an /v1/agent run.
type AgentStatus ¶
type AgentStatus string
AgentStatus represents the lifecycle state of an /v1/agent run.
const ( StatusQueued AgentStatus = "queued" StatusProcessing AgentStatus = "processing" StatusCompleted AgentStatus = "completed" StatusFailed AgentStatus = "failed" StatusCancelled AgentStatus = "cancelled" )
type AgentStopReason ¶
type AgentStopReason string
AgentStopReason describes why an /v1/agent run terminated.
const ( StopCompleted AgentStopReason = "completed" StopBudgetReached AgentStopReason = "budget_reached" StopCancelled AgentStopReason = "cancelled" StopFailed AgentStopReason = "failed" )
type AgentToolExecutionOutput ¶
type AgentToolExecutionOutput struct {
OK bool
SummaryForLLM string
BudgetExhausted bool
ConsumedPage bool
TouchedMCP bool
Sources []AgentSourceRef
Evidence []AgentEvidenceItem
DiscoveredAdapters []string
TraceSpan *AgentTraceSpan
// ResultKind overrides head-vs-tail truncation of SummaryForLLM (default: ToolResultKindFor(name, OK)).
ResultKind ToolResultKind
// ArtifactID names a stored copy of the full output; truncated results then point the model at read_artifact.
ArtifactID string
}
AgentToolExecutionOutput is returned by ToolExecutorFunc to RunAgentLoop.
type AgentToolInvocation ¶
type AgentToolInvocation struct {
Step int
ToolCall LLMToolCall
PagesRead int
MaxPages int
}
AgentToolInvocation describes a tool call dispatched by RunAgentLoop to ToolExecutorFunc.
type AgentTraceSpan ¶
type AgentTraceSpan struct {
Sequence int `json:"sequence"`
SpanID string `json:"spanId"`
Kind string `json:"kind"`
Name string `json:"name"`
Status string `json:"status"`
StartedAt int64 `json:"startedAt"`
DurationMs int64 `json:"durationMs"`
Input map[string]any `json:"input,omitempty"`
OutputPreview any `json:"outputPreview,omitempty"`
}
AgentTraceSpan records a single monotonic trace span in an /v1/agent run.
type CachedMCPToolSpec ¶
type CachedMCPToolSpec struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
DestructiveHint *bool `json:"destructiveHint,omitempty"`
InputSchema json.RawMessage `json:"inputSchema,omitempty"`
}
CachedMCPToolSpec describes a cached MCP tool schema on an enabled connector.
type ConnectedMCPServerSpec ¶
type ConnectedMCPServerSpec struct {
ID string `json:"id"`
Slug string `json:"slug"`
CachedTools []CachedMCPToolSpec `json:"cachedTools"`
}
ConnectedMCPServerSpec describes a connected MCP server permitted for an agent run.
type FindRelevantAdaptersInput ¶
type FindRelevantAdaptersInput struct {
Query string `json:"query"`
URLs []string `json:"urls,omitempty"`
Category string `json:"category,omitempty"`
Limit int `json:"limit,omitempty"`
Adapters []AdapterCatalogItem `json:"adapters,omitempty"`
}
FindRelevantAdaptersInput configures a dynamic adapter search query.
type LLMChatCompletionResult ¶
type LLMChatCompletionResult struct {
OK bool `json:"ok"`
Content string `json:"content"`
ToolCalls []LLMToolCall `json:"toolCalls"`
Usage *LLMTokenUsage `json:"usage,omitempty"`
Error string `json:"error,omitempty"`
}
LLMChatCompletionResult represents the normalized outcome of a single LLM turn.
func CompleteLLMTurn ¶
func CompleteLLMTurn(ctx context.Context, params LLMProviderTurnParams, timeout time.Duration, transport LLMTransportFunc) LLMChatCompletionResult
CompleteLLMTurn executes a single vendor-neutral LLM turn via an injected LLMTransportFunc callback.
func ParseProviderHTTPResponse ¶
func ParseProviderHTTPResponse(provider LLMProvider, status int, rawBody []byte, allowedToolNames []string) LLMChatCompletionResult
ParseProviderHTTPResponse parses a provider HTTP status and raw JSON body into an LLMChatCompletionResult, enforcing 3xx redirect fail-closed errors, <think> stripping, and fallback <tool_call> extraction.
func ParseWorkersAIResponse ¶
func ParseWorkersAIResponse(rawOut map[string]any, allowedToolNames []string) LLMChatCompletionResult
ParseWorkersAIResponse normalizes the output object from Cloudflare Workers AI.
type LLMEnvConfig ¶
type LLMEnvConfig struct {
EdgeFetchLLMProvider string `json:"EDGEFETCH_LLM_PROVIDER,omitempty"`
EdgeFetchLLMBaseURL string `json:"EDGEFETCH_LLM_BASE_URL,omitempty"`
EdgeFetchLLMAPIKey string `json:"EDGEFETCH_LLM_API_KEY,omitempty"`
EdgeFetchLLMModel string `json:"EDGEFETCH_LLM_MODEL,omitempty"`
EdgeFetchAllowLocalOverride string `json:"EDGEFETCH_ALLOW_LOCAL_LLM_OVERRIDE,omitempty"`
OllamaHost string `json:"OLLAMA_HOST,omitempty"`
OpenAIAPIKey string `json:"OPENAI_API_KEY,omitempty"`
OpenRouterAPIKey string `json:"OPENROUTER_API_KEY,omitempty"`
AnthropicAPIKey string `json:"ANTHROPIC_API_KEY,omitempty"`
GeminiAPIKey string `json:"GEMINI_API_KEY,omitempty"`
HasWorkersAI bool `json:"hasWorkersAi,omitempty"`
}
LLMEnvConfig holds operator environment variables and binding flags for BYO-LLM resolution.
type LLMMessage ¶
type LLMMessage struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []LLMToolCall `json:"toolCalls,omitempty"`
ToolCallID string `json:"toolCallId,omitempty"`
Name string `json:"name,omitempty"`
}
LLMMessage represents a vendor-neutral chat message across system, user, assistant, and tool roles.
func BuildAgentInitialMessages ¶
func BuildAgentInitialMessages(in AgentInitialMessagesInput) []LLMMessage
func BuildBudgetFinalAnswerMessage ¶ added in v2.8.26
func BuildBudgetFinalAnswerMessage() LLMMessage
BuildBudgetFinalAnswerMessage returns the final user turn sent when an agent run hits its budget without a final answer.
func BuildExtractJSONMessages ¶
func BuildExtractJSONMessages(urlStr, title, prompt string, schema map[string]any, markdown string) []LLMMessage
BuildExtractJSONMessages constructs the system and user messages for LLM-backed structured JSON extraction.
func BuildSummarizeMessages ¶
func BuildSummarizeMessages(markdown, title string) []LLMMessage
BuildSummarizeMessages constructs the system and user messages for LLM-backed page summarization.
type LLMProvider ¶
type LLMProvider string
LLMProvider identifies a supported BYO-LLM or local inference provider.
const ( ProviderOpenAI LLMProvider = "openai" ProviderOllama LLMProvider = "ollama" ProviderLMStudio LLMProvider = "lmstudio" ProviderVLLM LLMProvider = "vllm" ProviderOpenRouter LLMProvider = "openrouter" ProviderAnthropic LLMProvider = "anthropic" ProviderGemini LLMProvider = "gemini" ProviderWorkersAI LLMProvider = "workers-ai" )
func NormalizeProvider ¶
func NormalizeProvider(raw string) (LLMProvider, bool)
NormalizeProvider maps provider aliases to canonical LLMProvider values.
type LLMProviderTurnParams ¶
type LLMProviderTurnParams struct {
Config ResolvedLLMConfig `json:"config"`
Messages []LLMMessage `json:"messages"`
Tools []LLMToolDefinition `json:"tools,omitempty"`
JSONMode bool `json:"jsonMode,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"maxTokens,omitempty"`
}
LLMProviderTurnParams holds inputs for building a provider-specific request payload.
type LLMTokenUsage ¶
type LLMTokenUsage struct {
PromptTokens *int `json:"promptTokens,omitempty"`
CompletionTokens *int `json:"completionTokens,omitempty"`
TotalTokens *int `json:"totalTokens,omitempty"`
}
LLMTokenUsage reports prompt, completion, and total token counts when returned by the provider.
type LLMToolCall ¶
type LLMToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
}
LLMToolCall represents a parsed tool call emitted by an LLM turn.
func ParseFallbackTextToolCalls ¶
func ParseFallbackTextToolCalls(content string, allowedToolNames map[string]bool) []LLMToolCall
ParseFallbackTextToolCalls parses <tool_call>{...}</tool_call> or JSON tool_calls emitted in plain assistant text by local quantized models (Ollama, llama.cpp, vLLM) in strictly linear O(N) time (M12).
type LLMToolDefinition ¶
type LLMToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters map[string]any `json:"parameters"`
}
LLMToolDefinition describes a structured tool declaration passed to an LLM provider.
func BuildAgentTools ¶
func BuildAgentTools(strictConstrainToURLs, hasSearchCollection bool, connectedMCPs []ConnectedMCPServerSpec) []LLMToolDefinition
BuildAgentTools assembles structured LLM tool definitions for an /v1/agent run, including sanitized remote MCP tools.
type LLMTransportFunc ¶
type LLMTransportFunc func(ctx context.Context, req LLMTransportRequest) (LLMTransportResponse, error)
LLMTransportFunc executes an outbound LLM HTTP request (with redirect: manual & SSRF dial guard) or invokes a Workers AI binding, keeping internal/agentloop free of net/http and crypto/tls.
type LLMTransportRequest ¶
type LLMTransportRequest struct {
Provider LLMProvider
Model string
IsOfflineLocal bool
HTTP *ProviderHTTPRequest
Timeout time.Duration
}
LLMTransportRequest is passed to LLMTransportFunc in native Go (--mode=hub) execution.
type LLMTransportResponse ¶
LLMTransportResponse is returned by LLMTransportFunc in native Go (--mode=hub) execution.
type LoggableLLMConfigInput ¶
type LoggableLLMConfigInput struct {
Provider LLMProvider `json:"provider"`
BaseURL string `json:"baseUrl"`
Endpoint *string `json:"endpoint,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
HasHeaders bool `json:"hasHeaders,omitempty"`
APIKey string `json:"apiKey,omitempty"`
Model string `json:"model"`
IsOfflineLocal bool `json:"isOfflineLocal"`
}
LoggableLLMConfigInput describes an LLM configuration plus optional endpoint/headers for safe logging.
type ProviderHTTPRequest ¶
type ProviderHTTPRequest struct {
Kind string `json:"kind"` // "http" or "workers-ai"
Method string `json:"method,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
WorkersAIInput map[string]any `json:"workersAiInput,omitempty"`
}
ProviderHTTPRequest describes an outbound HTTP request (or Workers AI binding call) for an LLM turn.
func BuildProviderHTTPRequest ¶
func BuildProviderHTTPRequest(params LLMProviderTurnParams) (*ProviderHTTPRequest, error)
BuildProviderHTTPRequest builds the outbound HTTP request (or Workers AI binding spec) for any supported LLM provider.
type PublicURLCheckResult ¶
type PublicURLCheckResult struct {
OK bool `json:"ok"`
Normalized string `json:"normalized,omitempty"`
Error string `json:"error,omitempty"`
Reason string `json:"reason,omitempty"`
Message string `json:"message,omitempty"`
}
PublicURLCheckResult reports validation of a public HTTPS target URL.
func ValidatePublicHTTPSTargetURL ¶
func ValidatePublicHTTPSTargetURL(raw, selfHost string) PublicURLCheckResult
ValidatePublicHTTPSTargetURL validates that raw is a public https:// URL on port 443.
type RankedAdapterMatch ¶
type RankedAdapterMatch struct {
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
Description string `json:"description"`
Domains []string `json:"domains"`
ExampleURLs []string `json:"exampleUrls"`
Score float64 `json:"score"`
}
RankedAdapterMatch represents a scored adapter returned by FindRelevantAdapters.
func FindRelevantAdapters ¶
func FindRelevantAdapters(input FindRelevantAdaptersInput) []RankedAdapterMatch
FindRelevantAdapters ranks all keyless site & ATS adapters against a natural-language query and optional seed URLs in <1ms using domain hits, slug/token specificity, and category intent boosting, with zero 3-source cap.
type ResolveLLMConfigInput ¶
type ResolveLLMConfigInput struct {
Env LLMEnvConfig `json:"env"`
RequestLLM json.RawMessage `json:"requestLlm,omitempty"`
SelfHost string `json:"selfHost,omitempty"`
}
ResolveLLMConfigInput describes inputs to ResolveLLMConfig.
type ResolveLLMConfigOutput ¶
type ResolveLLMConfigOutput struct {
OK bool `json:"ok"`
Config *ResolvedLLMConfig `json:"config"`
Error string `json:"error,omitempty"`
Message string `json:"message,omitempty"`
}
ResolveLLMConfigOutput represents the outcome of ResolveLLMConfig.
func ResolveLLMConfig ¶
func ResolveLLMConfig(input ResolveLLMConfigInput) ResolveLLMConfigOutput
ResolveLLMConfig resolves operator environment defaults and per-request overrides, enforcing C1/M1 API key origin + path-prefix isolation and SSRF validation on caller-supplied baseUrl overrides.
type ResolvedLLMConfig ¶
type ResolvedLLMConfig struct {
Provider LLMProvider `json:"provider"`
BaseURL string `json:"baseUrl"`
APIKey string `json:"apiKey,omitempty"`
Model string `json:"model"`
IsOfflineLocal bool `json:"isOfflineLocal"`
UseSafePublicFetch bool `json:"useSafePublicFetch,omitempty"`
}
ResolvedLLMConfig contains the validated, key-isolated LLM configuration for a turn or agent run.
type RunAgentLoopInput ¶
type RunAgentLoopInput struct {
AgentID string
UserID string
ThreadID string
Prompt string
SeedURLs []string
StrictConstrainToURLs bool
Effort AgentEffort
MaxSteps int
MaxPages int
ZeroDataRetention bool
HasSearchCollection bool
Schema map[string]any
LLMConfig *ResolvedLLMConfig
ConnectedMCPs []ConnectedMCPServerSpec
RoutedMCPs []string
PriorThread *AgentRunRecord
// ToolResultBudget caps tool results fed back to the model (zero fields = DefaultToolResultMaxChars,
// DefaultToolResultMaxLines, DefaultStepToolResultMaxChars).
ToolResultBudget ToolResultBudget
}
RunAgentLoopInput configures a complete autonomous or deterministic /v1/agent execution.
type SchemaValidationResult ¶
type SchemaValidationResult struct {
Valid bool `json:"valid"`
PartialValid bool `json:"partialValid"`
Errors []string `json:"errors"`
}
SchemaValidationResult reports strict and partial JSON Schema conformance.
func ValidateDataAgainstJSONSchema ¶
func ValidateDataAgainstJSONSchema(data any, hasData bool, schema map[string]any) SchemaValidationResult
ValidateDataAgainstJSONSchema validates data against a JSON Schema subset (type, required, properties, items, enum), returning both strict Valid and PartialValid (used when /v1/agent halts on maxSteps/maxPages budget).
type ToolExecutorFunc ¶
type ToolExecutorFunc func(ctx context.Context, inv AgentToolInvocation) (AgentToolExecutionOutput, error)
ToolExecutorFunc executes a single agent tool call (`scrape_url`, `web_search`, `map_site`, `interact_browser`, `search_jobs`, `search_collection`, `query_mcp`) in the host runtime (native Go `--mode=hub` or test harness).
type ToolResultBudget ¶ added in v2.8.42
ToolResultBudget configures the per-result and per-step caps. Zero fields take the package defaults.
type ToolResultInput ¶ added in v2.8.42
type ToolResultInput struct {
ToolName string
OK bool
// Kind overrides ToolResultKindFor when non-empty.
Kind ToolResultKind
// Content is the raw SummaryForLLM text.
Content string
// ArtifactID, when set, is the stored full output the model can page with read_artifact.
ArtifactID string
}
ToolResultInput is one tool result destined for an LLM `tool` message.
type ToolResultKind ¶ added in v2.8.42
type ToolResultKind string
ToolResultKind selects how an oversized tool result is shortened.
const ( // ToolResultKindAuto derives the kind from the tool name and OK flag (see ToolResultKindFor). ToolResultKindAuto ToolResultKind = "" // ToolResultKindDocument keeps the HEAD (pages, documents, search hits). ToolResultKindDocument ToolResultKind = "document" // ToolResultKindLog keeps the TAIL (errors, command and status output) where the decisive lines come last. ToolResultKindLog ToolResultKind = "log" )
func ToolResultKindFor ¶ added in v2.8.42
func ToolResultKindFor(toolName string, ok bool) ToolResultKind
ToolResultKindFor decides head-vs-tail truncation from the tool kind and outcome, never from the text itself: failed calls are error output (keep the tail), everything else keeps the head unless listed as log-like.