Documentation
¶
Overview ¶
Package toolregistry defines the canonical wire protocol and stream naming helpers used by the tool registry gateway and tool providers/consumers.
Package toolregistry defines the canonical wire protocol and stream naming helpers used by the tool registry gateway and tool providers/consumers.
Package toolregistry defines the canonical wire protocol and stream naming helpers used by the tool registry gateway and tool providers/consumers.
This file defines the context plumbing used by providers to expose an output-delta publisher to tool implementations. Tools may use it to emit best-effort output fragments while running; the canonical tool result is still delivered via ToolResultMessage.
Package toolregistry owns registry transport identity and result retention.
The gateway derives transport IDs from validated run/call metadata and selects one absolute expiration carried through every result-stream user.
Index ¶
- Constants
- func DeriveToolUseID(runID, toolCallID string) string
- func ExtractTraceContext(ctx context.Context, traceParent, traceState, baggage string) context.Context
- func InjectTraceContext(ctx context.Context) (traceParent, traceState, baggage string)
- func ResultStreamID(toolUseID string) string
- func ToolUseIDFromContext(ctx context.Context) (string, bool)
- func ToolsetStreamID(toolset string) string
- func ValidateAdmissionRevision(revision string) error
- func ValidateExecutionDeadline(deadline time.Time) error
- func ValidateRegistrationToken(token string) error
- func ValidateResultStreamExpiration(expiresAt time.Time) error
- func ValidateToolCallMessage(message ToolCallMessage) error
- func ValidateToolCallRef(ref ToolCallRef) error
- func ValidateToolResultMessage(message ToolResultMessage) error
- func ValidateToolUseID(toolUseID string) error
- func ValidateWireProtocolVersion(version int) error
- func ValidationIssues(err error) []*tools.FieldIssue
- func WithOutputDeltaPublisher(ctx context.Context, pub OutputDeltaPublisher) context.Context
- func WithToolUseID(ctx context.Context, toolUseID string) context.Context
- type OutputDeltaPublisher
- type ServerDataItem
- type ToolCallMessage
- type ToolCallMessageType
- type ToolCallMeta
- type ToolCallRef
- type ToolError
- type ToolOutputDeltaMessage
- type ToolResultMessage
- func NewToolResultErrorMessage(registrationToken, toolUseID, code, message string) ToolResultMessage
- func NewToolResultInvalidArgumentsMessage(registrationToken, toolUseID, message string, issues []*tools.FieldIssue) ToolResultMessage
- func NewToolResultMessage(registrationToken, toolUseID string, result json.RawMessage) ToolResultMessage
- func NewToolResultMessageWithServerData(registrationToken, toolUseID string, result json.RawMessage, ...) ToolResultMessage
- func NewToolResultRetryMessage(registrationToken, toolUseID string, reason ToolRetryReason, ...) ToolResultMessage
- func NewToolResultServiceErrorMessage(registrationToken, toolUseID string, _ tools.Ident, code string, err error) ToolResultMessage
- type ToolRetry
- type ToolRetryReason
Constants ¶
const ( // WireProtocolVersion is the only tool registry message protocol accepted by // this runtime. Provider registration and consumer CallTool/RetryTool requests // carry it explicitly so the registry rejects binaries that encode another // ToolCallMessage or ToolResultMessage contract before side effects. WireProtocolVersion = 8 // AdmissionRevisionPattern is the canonical deployment-issued admission // revision syntax shared by the Goa boundary and provider lifecycle config. AdmissionRevisionPattern = `^[A-Za-z0-9][A-Za-z0-9._:/@+\-]{0,255}$` // RegistrationTokenPattern is the lowercase SHA-256 admission-generation // identity syntax shared by Goa and Pulse message boundaries. // #nosec G101 -- this public validation pattern is not a credential. RegistrationTokenPattern = `^[0-9a-f]{64}$` // MinProviderLeaseDuration exceeds the default provider shutdown margin, // registration attempt, and maximum retry-delay budget. MinProviderLeaseDuration = 45 * time.Second // MaxProviderLeaseDuration bounds registry-issued leases so overflow and // operationally stale provider membership cannot become valid state. MaxProviderLeaseDuration = 24 * time.Hour // ResultStreamMaxLen bounds retained best-effort delivery history. The // authoritative terminal message remains in the registry call record and // can be restored after this stream trims it. ResultStreamMaxLen = 512 // MaxToolOutputDeltaCount bounds best-effort fragments retained for one // call before the registry suppresses further output. MaxToolOutputDeltaCount = 256 // MaxToolOutputDeltaBytes bounds one UTF-8 output fragment at the registry // API boundary. MaxToolOutputDeltaBytes = 64 * 1024 // MaxToolResultMessageBytes bounds one complete canonical terminal envelope // before the registry stores it in both the call record and result stream. MaxToolResultMessageBytes = 1024 * 1024 )
const ( // MessageTypeCall indicates a tool invocation message on a toolset stream. MessageTypeCall ToolCallMessageType = "call" // MessageTypePing indicates a health ping message on a toolset stream. MessageTypePing ToolCallMessageType = "ping" // ResultEventKey is the Pulse event name used to publish canonical terminal // results and retry-control envelopes to a per-call result stream. ResultEventKey = "result" // ProviderConsumerGroup is the one canonical Pulse consumer group shared by // every provider replica for a toolset stream. ProviderConsumerGroup = "provider" // OutputDeltaEventKey is the Pulse event name used to publish best-effort tool // output delta messages to a per-call result stream. OutputDeltaEventKey = "output_delta" // ProviderOverloadRetryAfter is the provider-requested delay before the // registry republishes an admitted call after queue saturation. ProviderOverloadRetryAfter = 250 * time.Millisecond // MaxProviderOverloadRetryAfter bounds overload delay at the message boundary. MaxProviderOverloadRetryAfter = 5 * time.Second // MaxToolCallMetaIDLength matches the Goa boundary for every identifier // propagated in ToolCallMeta. MaxToolCallMetaIDLength = 256 // ToolRetryReasonProviderOverloaded means provider intake was saturated // before execution began. ToolRetryReasonProviderOverloaded ToolRetryReason = "provider_overloaded" // ToolErrorCodeInvalidArguments identifies a terminal schema-validation failure. ToolErrorCodeInvalidArguments = "invalid_arguments" // ToolErrorCodeStaleRegistration completes a queued call whose admission // generation no longer matches the admitted provider. ToolErrorCodeStaleRegistration = "stale_registration" // ToolErrorCodeOutcomeUnknown completes a claimed call when the exact // provider lease disappears before terminal publication. The provider may // already have performed the side effect, so execution must not transfer. ToolErrorCodeOutcomeUnknown = "outcome_unknown" )
const ( // MaxToolUseIDLength is the transport boundary shared by calls and results. MaxToolUseIDLength = 256 // MaxToolCallWait bounds how long an executor waits for a provider result. MaxToolCallWait = 10 * time.Minute // ResultStreamTransportBudget preserves the stream beyond the maximum wait // for publication, acknowledgement, and transport scheduling. ResultStreamTransportBudget = time.Minute // MinResultStreamTTL is the shortest retention from which the registry may // derive an absolute call expiration. MinResultStreamTTL = MaxToolCallWait + ResultStreamTransportBudget // DefaultResultStreamTTL is used when registry configuration omits retention. DefaultResultStreamTTL = 15 * time.Minute // MaxResultStreamTTL bounds orphan retention after a caller disappears. MaxResultStreamTTL = 24 * time.Hour // ToolUseIDPattern rejects the composite-key separator at non-Goa // call/result boundaries. ToolUseIDPattern = `^[^\x00]{1,256}$` )
Variables ¶
This section is empty.
Functions ¶
func DeriveToolUseID ¶ added in v2.1.0
DeriveToolUseID returns the deterministic global transport identity for one model/provider call inside one run. Length delimiters prevent concatenation ambiguity while the domain separator prevents cross-protocol reuse.
func ExtractTraceContext ¶
func ExtractTraceContext(ctx context.Context, traceParent, traceState, baggage string) context.Context
ExtractTraceContext returns a context that carries the W3C Trace Context represented by traceParent and traceState. Empty values are allowed and will yield the input ctx unchanged.
func InjectTraceContext ¶
InjectTraceContext encodes the trace context in ctx as W3C Trace Context header values. If ctx does not contain a valid trace context, it returns empty strings.
func ResultStreamID ¶
ResultStreamID returns the deterministic Pulse stream identifier used for publishing a single tool result message for the given tool use identifier.
func ToolUseIDFromContext ¶ added in v2.1.0
ToolUseIDFromContext returns the canonical run-scoped tool-call identity.
func ToolsetStreamID ¶
ToolsetStreamID returns the deterministic Pulse stream identifier used for publishing tool call messages to providers for the given toolset registration ID.
func ValidateAdmissionRevision ¶ added in v2.1.0
ValidateAdmissionRevision rejects revisions that cannot be admitted through the registry contract. Callers use it for non-Goa boundaries such as provider process configuration and persisted catalog rehydration.
func ValidateExecutionDeadline ¶ added in v2.1.0
ValidateExecutionDeadline enforces the structural absolute execution contract without using the caller's local clock to decide liveness.
func ValidateRegistrationToken ¶ added in v2.1.0
ValidateRegistrationToken rejects values that are not canonical lowercase SHA-256 admission-generation identities.
func ValidateResultStreamExpiration ¶ added in v2.1.0
ValidateResultStreamExpiration enforces the structural absolute retention contract without using the caller's local clock to decide liveness.
func ValidateToolCallMessage ¶ added in v2.1.0
func ValidateToolCallMessage(message ToolCallMessage) error
ValidateToolCallMessage enforces the structural Pulse request boundary without deciding whether a call's absolute expiration has elapsed. The registry owns that decision with Redis time.
func ValidateToolCallRef ¶ added in v2.1.0
func ValidateToolCallRef(ref ToolCallRef) error
ValidateToolCallRef enforces the registry result reference's structural identity and expiration contract. It deliberately does not decide liveness.
func ValidateToolResultMessage ¶ added in v2.1.0
func ValidateToolResultMessage(message ToolResultMessage) error
ValidateToolResultMessage enforces the top-level success, terminal-error, or retry-control union before a consumer acts on the message.
func ValidateToolUseID ¶ added in v2.1.0
ValidateToolUseID enforces the shared call/result transport boundary.
func ValidateWireProtocolVersion ¶ added in v2.1.0
ValidateWireProtocolVersion rejects provider and consumer binaries that do not implement the registry's one canonical message envelope.
func ValidationIssues ¶
func ValidationIssues(err error) []*tools.FieldIssue
ValidationIssues extracts structured field-level validation issues from err.
It supports two common sources:
- Generated tool-codec validation errors that expose Issues() []*tools.FieldIssue
- Goa ServiceErrors (possibly merged) that use Goa validation error names (missing_field, invalid_length, etc.) and populate ServiceError.Field.
ValidationIssues returns nil when err does not represent a field-level validation failure.
func WithOutputDeltaPublisher ¶
func WithOutputDeltaPublisher(ctx context.Context, pub OutputDeltaPublisher) context.Context
WithOutputDeltaPublisher returns a context that carries pub.
Types ¶
type OutputDeltaPublisher ¶
type OutputDeltaPublisher interface {
PublishToolOutputDelta(ctx context.Context, stream string, delta string) error
}
OutputDeltaPublisher emits best-effort tool output deltas for a single tool execution. Providers inject an instance into the tool call context so tool implementations can stream partial output while running.
func OutputDeltaPublisherFromContext ¶
func OutputDeltaPublisherFromContext(ctx context.Context) (OutputDeltaPublisher, bool)
OutputDeltaPublisherFromContext returns the output-delta publisher carried by ctx, if any.
type ServerDataItem ¶
type ServerDataItem struct {
Kind string `json:"kind"`
Audience string `json:"audience"`
Data json.RawMessage `json:"data"`
}
ServerDataItem is server-only tool output published alongside the canonical tool result JSON. Server data is never sent to model providers.
func DecodeServerData ¶ added in v2.1.0
func DecodeServerData(data []byte) ([]*ServerDataItem, error)
DecodeServerData decodes the canonical server-only item envelope carried by planner tool results. Kind-specific payloads remain raw JSON for decoding by the generated codec declared on the corresponding tool specification.
type ToolCallMessage ¶
type ToolCallMessage struct {
// RegistrationToken is the exact admission generation used to validate
// and route this message. Providers reject calls from any other admission.
RegistrationToken string `json:"registration_token"`
// ToolUseID is the globally unique transport identity for this request.
Type ToolCallMessageType `json:"type"`
ToolUseID string `json:"tool_use_id,omitempty"`
// ExecutionDeadlineUnixMilli is the Redis-selected absolute deadline
// that bounds provider dispatch and executor waiting.
ExecutionDeadlineUnixMilli int64 `json:"execution_deadline_unix_ms,omitempty"`
// ResultStreamExpiresAtUnixMilli is the registry-selected absolute
// expiration shared by the call record and every result-stream handle.
ResultStreamExpiresAtUnixMilli int64 `json:"result_stream_expires_at_unix_ms,omitempty"`
PingID string `json:"ping_id,omitempty"`
Tool tools.Ident `json:"tool,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
Meta *ToolCallMeta `json:"meta,omitempty"`
// TraceParent and TraceState carry W3C Trace Context headers for distributed
// tracing across Pulse boundaries. These fields are optional and may be empty.
// When set, consumers should extract them into their context before starting
// spans for handling the tool call.
TraceParent string `json:"traceparent,omitempty"`
TraceState string `json:"tracestate,omitempty"`
// Baggage carries the W3C baggage header when the global propagator includes
// baggage propagation (common for OTEL setups). Optional.
Baggage string `json:"baggage,omitempty"`
}
ToolCallMessage is published to a toolset request stream for tool invocations and provider health checks.
func NewPingMessage ¶
func NewPingMessage(registrationToken, pingID string) ToolCallMessage
NewPingMessage constructs a health ping message.
func NewToolCallMessage ¶
func NewToolCallMessage( registrationToken, toolUseID string, executionDeadline time.Time, resultStreamExpiresAt time.Time, tool tools.Ident, payload json.RawMessage, meta *ToolCallMeta, ) ToolCallMessage
NewToolCallMessage constructs a tool invocation message.
type ToolCallMessageType ¶
type ToolCallMessageType string
ToolCallMessageType is the type discriminator for toolset stream messages.
type ToolCallMeta ¶
type ToolCallMeta struct {
RunID string `json:"run_id"`
SessionID string `json:"session_id"`
TurnID string `json:"turn_id,omitempty"`
// ToolCallID is the model/provider call identity. The registry preserves it
// as metadata and derives the separate global ToolUseID from RunID plus
// ToolCallID.
ToolCallID string `json:"tool_call_id"`
ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
}
ToolCallMeta is execution metadata propagated alongside tool calls. Providers may use this metadata to scope data access and persistence (for example, applying session-scoped policies without polluting tool payload schemas).
type ToolCallRef ¶ added in v2.1.0
type ToolCallRef struct {
ToolUseID string
RegistrationToken string
ExecutionDeadline time.Time
ResultStreamExpiresAt time.Time
}
ToolCallRef identifies one registry-routed invocation and the exact admission generation whose events the caller may accept.
type ToolError ¶
type ToolError struct {
Code string `json:"code"`
Message string `json:"message"`
Issues []*tools.FieldIssue `json:"issues,omitempty"`
}
ToolError is a structured terminal provider failure.
type ToolOutputDeltaMessage ¶
type ToolOutputDeltaMessage struct {
// RegistrationToken echoes the exact token stamped on the tool call so
// reused transport IDs cannot forward output from an older admission.
RegistrationToken string `json:"registration_token"`
ToolUseID string `json:"tool_use_id"`
// Stream identifies which logical output channel produced the delta
// (for example, "stdout", "stderr", "log", "progress").
Stream string `json:"stream"`
Delta string `json:"delta"`
}
ToolOutputDeltaMessage is published to a per-call result stream while a tool is still running. It streams partial output to consumers for improved UX (live output panels) without changing the final ToolResultMessage.
Contract:
- This is best-effort and may be dropped by consumers.
- Deltas are not persisted by default; the canonical output remains the final tool result payload.
func NewToolOutputDeltaMessage ¶
func NewToolOutputDeltaMessage(registrationToken, toolUseID, stream, delta string) ToolOutputDeltaMessage
NewToolOutputDeltaMessage constructs a tool output delta message.
type ToolResultMessage ¶
type ToolResultMessage struct {
// RegistrationToken echoes the exact token stamped on the tool call.
RegistrationToken string `json:"registration_token"`
ToolUseID string `json:"tool_use_id"`
Result json.RawMessage `json:"result_json,omitempty"`
// Bounds carries canonical bounded-result metadata projected out-of-band
// from the semantic result payload when the tool declares a bounded-result
// contract.
Bounds *agent.Bounds `json:"bounds,omitempty"`
// ServerData carries server-only metadata about the tool execution that must
// not be serialized into model provider requests.
//
// This is the canonical home for any non-model payloads emitted alongside a
// tool result. Consumers may project it into different observer views (for
// example, UI render cards vs persistence-only evidence), but the wire
// protocol keeps a single server-side envelope.
ServerData []*ServerDataItem `json:"server_data,omitempty"`
Error *ToolError `json:"error,omitempty"`
// Retry asks registry orchestration to republish this exact admitted call.
// It is mutually exclusive with every terminal success and error field.
Retry *ToolRetry `json:"retry,omitempty"`
}
ToolResultMessage is published to a per-call result stream. The gateway interprets only the retry-control variant; consumers decode terminal success and error variants using compiled tool contracts.
func NewToolResultErrorMessage ¶
func NewToolResultErrorMessage(registrationToken, toolUseID, code, message string) ToolResultMessage
NewToolResultErrorMessage constructs an error tool result message.
func NewToolResultInvalidArgumentsMessage ¶ added in v2.1.0
func NewToolResultInvalidArgumentsMessage( registrationToken, toolUseID, message string, issues []*tools.FieldIssue, ) ToolResultMessage
NewToolResultInvalidArgumentsMessage constructs a correct-call failure with structured validation issues. Other recovery actions cannot carry issues.
func NewToolResultMessage ¶
func NewToolResultMessage(registrationToken, toolUseID string, result json.RawMessage) ToolResultMessage
NewToolResultMessage constructs a successful tool result message.
func NewToolResultMessageWithServerData ¶
func NewToolResultMessageWithServerData( registrationToken, toolUseID string, result json.RawMessage, serverData []*ServerDataItem, ) ToolResultMessage
NewToolResultMessageWithServerData constructs a successful tool result message with additional server-only metadata.
func NewToolResultRetryMessage ¶ added in v2.1.0
func NewToolResultRetryMessage( registrationToken, toolUseID string, reason ToolRetryReason, retryAfter time.Duration, ) ToolResultMessage
NewToolResultRetryMessage constructs a non-terminal retry-control message.
func NewToolResultServiceErrorMessage ¶ added in v2.1.0
func NewToolResultServiceErrorMessage( registrationToken, toolUseID string, _ tools.Ident, code string, err error, ) ToolResultMessage
NewToolResultServiceErrorMessage constructs a terminal provider result with an explicitly safe service message or a generic fallback.
type ToolRetry ¶ added in v2.1.0
type ToolRetry struct {
// Reason identifies the retryable transport condition.
Reason ToolRetryReason `json:"reason"`
// RetryAfterMillis is the bounded delay before exact republication.
RetryAfterMillis int64 `json:"retry_after_ms,omitempty"`
}
ToolRetry is a non-terminal registry orchestration instruction. It never carries planner failure semantics.
type ToolRetryReason ¶ added in v2.1.0
type ToolRetryReason string
ToolRetryReason identifies one registry-owned reason for republishing an admitted call without exposing a terminal failure to the planner.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package executor provides registry-backed tool execution.
|
Package executor provides registry-backed tool execution. |
|
Package provider implements the provider-side Pulse subscription loop for registry-routed tool execution.
|
Package provider implements the provider-side Pulse subscription loop for registry-routed tool execution. |