schema

package
v0.7.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	EventAgentStart     = "agent_start"
	EventTextDelta      = "text_delta"
	EventToolCallStart  = "tool_call_start"
	EventToolCallEnd    = "tool_call_end"
	EventToolResult     = "tool_result"
	EventIterationStart = "iteration_start"
	EventAgentEnd       = "agent_end"
	EventError          = "error"

	// LLM call events (emitted by largemodel metrics middleware).
	EventLLMCallStart = "llm_call_start"
	EventLLMCallEnd   = "llm_call_end"
	EventLLMCallError = "llm_call_error"

	EventTokenBudgetExhausted = "token_budget_exhausted"

	// Session- and daily-level budget events (distinct from EventTokenBudgetExhausted,
	// which is Run-level). Emitted by the BudgetMiddleware host closures — see
	// vv/traces/budgets.
	EventBudgetWarn     = "budget_warn"
	EventBudgetExceeded = "budget_exceeded"

	// Orchestration lifecycle events.
	EventPhaseStart    = "phase_start"
	EventPhaseEnd      = "phase_end"
	EventSubAgentStart = "sub_agent_start"
	EventSubAgentEnd   = "sub_agent_end"

	// Skill lifecycle events.
	EventSkillDiscover     = "skill_discover"
	EventSkillActivate     = "skill_activate"
	EventSkillDeactivate   = "skill_deactivate"
	EventSkillResourceLoad = "skill_resource_load"

	// Interaction events.
	EventPendingInteraction = "pending_interaction"

	// Guard events (emitted when a guard check produces a material outcome
	// such as log/rewrite/block/error; silent passes produce no event).
	EventGuardCheck = "guard_check"

	// MCP credential filter events (emitted by vage/mcp client/server when
	// the credential scanner detects credentials in tool I/O).
	EventMCPCredentialDetected = "mcp_credential_detected"

	// Todo tracking events (emitted by the todo_write built-in tool whenever
	// the session-scoped todo list changes). Payload carries the full snapshot
	// — consumers receive a version number and can treat each event as an
	// idempotent replacement of their local state.
	EventTodoUpdate = "todo_update"
)

EventType constants for streaming events.

View Source
const (
	ToolSourceLocal = "local"
	ToolSourceMCP   = "mcp"
	ToolSourceAgent = "agent"
)

Tool source constants.

Variables

View Source
var ErrRunStreamClosed = errors.New("vage: run stream is closed")

ErrRunStreamClosed is returned when Recv is called on a closed RunStream.

Functions

func SessionIDFromContext added in v0.5.0

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext returns the sessionID attached via WithSessionID, or empty string when absent.

func ToAIModelMessages

func ToAIModelMessages(msgs []Message) []aimodel.Message

ToAIModelMessages converts a slice of Message to []aimodel.Message.

func WithEmitter added in v0.5.0

func WithEmitter(ctx context.Context, e Emitter) context.Context

WithEmitter attaches a stream emitter to ctx. Nil is a no-op.

func WithSessionID added in v0.5.0

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

WithSessionID attaches sessionID to ctx so tool handlers can read it via SessionIDFromContext. Empty sessionID is a no-op.

Types

type AgentEndData

type AgentEndData struct {
	Duration   int64      `json:"duration_ms"`
	Message    string     `json:"message,omitempty"`
	StopReason StopReason `json:"stop_reason,omitempty"`
}

AgentEndData carries summary information when the agent finishes.

type AgentStartData

type AgentStartData struct{}

AgentStartData carries information when the agent begins.

type BudgetExceededData added in v0.5.0

type BudgetExceededData struct {
	Scope     string  `json:"scope"`
	Dimension string  `json:"dimension"`
	Used      int64   `json:"used"`
	UsedCost  float64 `json:"used_cost,omitempty"`
	Limit     int64   `json:"limit"`
	LimitCost float64 `json:"limit_cost,omitempty"`
}

BudgetExceededData reports that a session- or daily-level hard limit was hit and the LLM call was rejected before reaching the network.

type BudgetWarnData added in v0.5.0

type BudgetWarnData struct {
	Scope     string  `json:"scope"`     // "session" | "daily"
	Dimension string  `json:"dimension"` // "tokens" | "cost"
	Used      int64   `json:"used"`
	UsedCost  float64 `json:"used_cost,omitempty"`
	Limit     int64   `json:"limit"`
	LimitCost float64 `json:"limit_cost,omitempty"`
	Percent   float64 `json:"percent"`
}

BudgetWarnData reports the first crossing of a soft warn threshold on a session- or daily-level budget. Emitted at most once per tracker per window.

type ContentPart

type ContentPart struct {
	Type     string `json:"type"` // text, json, image, file
	Text     string `json:"text,omitempty"`
	Data     []byte `json:"data,omitempty"`
	MimeType string `json:"mime_type,omitempty"`
	URL      string `json:"url,omitempty"`
}

ContentPart represents a piece of content in a tool result.

type Emitter added in v0.5.0

type Emitter func(Event) error

Emitter sends a single Event into the active stream. Returning an error normally means the stream is shutting down; most callers ignore it because the run is terminating anyway.

func EmitterFromContext added in v0.5.0

func EmitterFromContext(ctx context.Context) Emitter

EmitterFromContext returns the Emitter attached via WithEmitter, or nil when absent.

type ErrorData

type ErrorData struct {
	Message string `json:"message"`
}

ErrorData carries error information.

type Event

type Event struct {
	Type      string    `json:"type"`
	AgentID   string    `json:"agent_id,omitempty"`
	SessionID string    `json:"session_id,omitempty"`
	Timestamp time.Time `json:"timestamp"`
	Data      EventData `json:"data,omitempty"`
	ParentID  string    `json:"parent_id,omitempty"`
}

Event represents an agent lifecycle event emitted during streaming.

func NewEvent

func NewEvent(eventType, agentID, sessionID string, data EventData) Event

NewEvent creates an Event with the given type, agent ID, session ID, and data.

type EventData

type EventData interface {
	// contains filtered or unexported methods
}

EventData is a sealed interface for event payloads. Only types within this package may implement it.

type GuardCheckData added in v0.5.0

type GuardCheckData struct {
	GuardName  string   `json:"guard_name"`
	ToolCallID string   `json:"tool_call_id,omitempty"`
	ToolName   string   `json:"tool_name,omitempty"`
	Action     string   `json:"action"`              // "log" | "rewrite" | "block" | "error"
	RuleHits   []string `json:"rule_hits,omitempty"` // matched rule names
	Severity   string   `json:"severity,omitempty"`  // max severity among hits
	Snippet    string   `json:"snippet,omitempty"`   // leading chars of scanned content
}

GuardCheckData carries the outcome of a guard check with a material effect (log / rewrite / block / error). Silent passes do not emit this event.

type IterationStartData

type IterationStartData struct {
	Iteration int `json:"iteration"`
}

IterationStartData carries metadata about a new ReAct loop iteration.

type LLMCallEndData

type LLMCallEndData struct {
	Model            string `json:"model"`
	Duration         int64  `json:"duration_ms"`
	PromptTokens     int    `json:"prompt_tokens"`
	CompletionTokens int    `json:"completion_tokens"`
	TotalTokens      int    `json:"total_tokens"`
	CacheReadTokens  int    `json:"cache_read_tokens,omitempty"`
	Stream           bool   `json:"stream"`
}

LLMCallEndData carries information when an LLM call completes.

type LLMCallErrorData

type LLMCallErrorData struct {
	Model    string `json:"model"`
	Duration int64  `json:"duration_ms"`
	Error    string `json:"error"`
	Stream   bool   `json:"stream"`
}

LLMCallErrorData carries information when an LLM call fails.

type LLMCallStartData

type LLMCallStartData struct {
	Model    string `json:"model"`
	Messages int    `json:"messages"`
	Tools    int    `json:"tools"`
	Stream   bool   `json:"stream"`
}

LLMCallStartData carries information when an LLM call begins.

type MCPCredentialDetectedData added in v0.5.0

type MCPCredentialDetectedData struct {
	Direction string   `json:"direction"` // e.g. "mcp_outbound", "mcp_inbound"
	ServerURI string   `json:"server_uri,omitempty"`
	ToolName  string   `json:"tool_name,omitempty"`
	Action    string   `json:"action"` // "log" | "redact" | "block"
	HitTypes  []string `json:"hit_types"`
	HitCount  int      `json:"hit_count"`
	Masked    []string `json:"masked,omitempty"`
	Truncated bool     `json:"truncated,omitempty"`
}

MCPCredentialDetectedData carries a summary of a credential scan at the MCP boundary. Plaintext credentials never appear in this payload — only masked previews such as "AKIA****".

type Message

type Message struct {
	aimodel.Message
	AgentID   string         `json:"agent_id,omitempty"`
	Timestamp time.Time      `json:"timestamp"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Message wraps aimodel.Message with agent-specific metadata.

func FromAIModelMessage

func FromAIModelMessage(msg aimodel.Message) Message

FromAIModelMessage converts an aimodel.Message to a Message.

func NewAssistantMessage

func NewAssistantMessage(msg aimodel.Message, agentID string) Message

NewAssistantMessage wraps an aimodel.Message as an agent assistant message.

func NewUserMessage

func NewUserMessage(text string) Message

NewUserMessage creates a user message with the given text.

type PendingInteractionData added in v0.4.0

type PendingInteractionData struct {
	InteractionID  string `json:"interaction_id"`
	Question       string `json:"question"`
	TimeoutSeconds int    `json:"timeout_seconds"`
}

PendingInteractionData carries information about a pending user interaction.

type PhaseEndData added in v0.4.0

type PhaseEndData struct {
	Phase            string `json:"phase"`
	Duration         int64  `json:"duration_ms"`
	Summary          string `json:"summary,omitempty"`           // optional phase summary (e.g., plan overview)
	ToolCalls        int    `json:"tool_calls,omitempty"`        // total tool calls in the phase
	PromptTokens     int    `json:"prompt_tokens,omitempty"`     // total prompt tokens in the phase
	CompletionTokens int    `json:"completion_tokens,omitempty"` // total completion tokens in the phase
	CacheReadTokens  int    `json:"cache_read_tokens,omitempty"` // total cache-read tokens in the phase
}

PhaseEndData carries information when an orchestration phase completes.

type PhaseStartData added in v0.4.0

type PhaseStartData struct {
	Phase      string `json:"phase"`       // e.g. "explore", "plan", "dispatch"
	PhaseIndex int    `json:"phase_index"` // 1-based index
	TotalPhase int    `json:"total_phase"` // total number of phases
}

PhaseStartData carries information when an orchestration phase begins.

type RunOptions

type RunOptions struct {
	Model          string   `json:"model,omitempty"`
	Temperature    *float64 `json:"temperature,omitempty"`
	MaxIterations  int      `json:"max_iterations,omitempty"`
	MaxTokens      int      `json:"max_tokens,omitempty"`
	RunTokenBudget int      `json:"run_token_budget,omitempty"`
	Tools          []string `json:"tools,omitempty"`
	StopSequences  []string `json:"stop_sequences,omitempty"`
}

RunOptions holds optional overrides for a single Run call.

type RunRequest

type RunRequest struct {
	Messages  []Message      `json:"messages"`
	SessionID string         `json:"session_id,omitempty"`
	Options   *RunOptions    `json:"options,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

RunRequest is the input to Agent.Run.

type RunResponse

type RunResponse struct {
	Messages   []Message      `json:"messages"`
	SessionID  string         `json:"session_id,omitempty"`
	Usage      *aimodel.Usage `json:"usage,omitempty"`
	Duration   int64          `json:"duration_ms,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
	StopReason StopReason     `json:"stop_reason,omitempty"`
}

RunResponse is the output of Agent.Run.

type RunStream

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

RunStream delivers streaming events from an agent run using a pull-based API. The caller reads events via Recv and can stop the stream early via Close.

func MergeStreams

func MergeStreams(ctx context.Context, bufSize int, streams ...*RunStream) *RunStream

MergeStreams merges multiple RunStreams into a single RunStream. Events from all source streams are interleaved. The parentID is set on each forwarded event to track which sub-stream produced it.

func NewRunStream

func NewRunStream(ctx context.Context, bufSize int, producer StreamProducer) *RunStream

NewRunStream creates a RunStream and starts the producer in a goroutine. The producer calls send to emit events. If the producer returns a non-nil error, Recv will surface it after all buffered events are drained. The parent context is used to derive a cancelable context for the producer; calling Close cancels this context, allowing the producer to stop promptly.

func (*RunStream) Close

func (rs *RunStream) Close() error

Close signals the producer to stop and prevents further Recv calls.

func (*RunStream) Recv

func (rs *RunStream) Recv() (Event, error)

Recv returns the next event from the stream. Returns io.EOF when the stream completes successfully. Returns the producer error if the producer failed. Returns ErrRunStreamClosed if Close was called.

type SkillActivateData

type SkillActivateData struct {
	SkillName string `json:"skill_name"`
	SessionID string `json:"session_id"`
}

SkillActivateData carries information when a skill is activated.

type SkillDeactivateData

type SkillDeactivateData struct {
	SkillName string `json:"skill_name"`
	SessionID string `json:"session_id"`
}

SkillDeactivateData carries information when a skill is deactivated.

type SkillDiscoverData

type SkillDiscoverData struct {
	Directory string `json:"directory"`
	Count     int    `json:"count"`
}

SkillDiscoverData carries information about skill discovery.

type SkillResourceLoadData

type SkillResourceLoadData struct {
	SkillName    string `json:"skill_name"`
	ResourceType string `json:"resource_type"`
	ResourceName string `json:"resource_name"`
}

SkillResourceLoadData carries information when a skill resource is loaded.

type StopReason

type StopReason string

StopReason indicates why an agent run terminated.

const (
	StopReasonComplete        StopReason = "complete"
	StopReasonBudgetExhausted StopReason = "token_budget_exhausted"
	StopReasonMaxIterations   StopReason = "max_iterations_exceeded"
)

StopReason constants.

type StreamProducer

type StreamProducer func(ctx context.Context, send func(Event) error) error

StreamProducer is the function signature for producing stream events. The producer receives a context (canceled on Close) and a send function to emit events.

type SubAgentEndData added in v0.4.0

type SubAgentEndData struct {
	AgentName        string `json:"agent_name"`
	StepID           string `json:"step_id,omitempty"`
	Duration         int64  `json:"duration_ms"`
	ToolCalls        int    `json:"tool_calls"`
	TokensUsed       int    `json:"tokens_used"`                 // kept for backward compat (prompt + completion)
	PromptTokens     int    `json:"prompt_tokens,omitempty"`     // prompt tokens used by this sub-agent
	CompletionTokens int    `json:"completion_tokens,omitempty"` // completion tokens used by this sub-agent
	CacheReadTokens  int    `json:"cache_read_tokens,omitempty"` // cache-read tokens used by this sub-agent
}

SubAgentEndData carries information when a sub-agent finishes execution.

type SubAgentStartData added in v0.4.0

type SubAgentStartData struct {
	AgentName   string `json:"agent_name"`
	StepID      string `json:"step_id,omitempty"`     // for plan mode
	Description string `json:"description,omitempty"` // step description
	StepIndex   int    `json:"step_index,omitempty"`  // 1-based step index
	TotalSteps  int    `json:"total_steps,omitempty"` // total steps in plan
}

SubAgentStartData carries information when a sub-agent begins execution.

type TextDeltaData

type TextDeltaData struct {
	Delta string `json:"delta"`
}

TextDeltaData carries a text chunk from the LLM.

type TodoItem added in v0.5.0

type TodoItem struct {
	ID         string `json:"id"`
	Content    string `json:"content"`
	ActiveForm string `json:"active_form"`
	Status     string `json:"status"`
}

TodoItem is the wire form of a single todo list entry emitted on EventTodoUpdate. It duplicates vage/tool/todo.Item to keep the schema package free of a reverse dependency on vage/tool.

type TodoUpdateData added in v0.5.0

type TodoUpdateData struct {
	Version int64      `json:"version"`
	Items   []TodoItem `json:"items"`
}

TodoUpdateData carries a full snapshot of the session-scoped todo list after a successful todo_write invocation. Version is strictly monotonic per session; clients may use it as an idempotency key.

type TokenBudgetExhaustedData

type TokenBudgetExhaustedData struct {
	Budget     int  `json:"budget"`
	Used       int  `json:"used"`
	Iterations int  `json:"iterations"`
	Estimated  bool `json:"estimated,omitempty"`
}

TokenBudgetExhaustedData carries information when the token budget is exhausted.

type ToolCallEndData

type ToolCallEndData struct {
	ToolCallID string `json:"tool_call_id"`
	ToolName   string `json:"tool_name"`
	Duration   int64  `json:"duration_ms"`
}

ToolCallEndData carries the end of a tool invocation with duration.

type ToolCallStartData

type ToolCallStartData struct {
	ToolCallID string `json:"tool_call_id"`
	ToolName   string `json:"tool_name"`
	Arguments  string `json:"arguments"`
}

ToolCallStartData carries the start of a tool invocation.

type ToolDef

type ToolDef struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Parameters  any    `json:"parameters,omitempty"` // JSON Schema
	// ForceUse indicates whether the LLM must invoke this tool (i.e. forced tool choice).
	// It does NOT refer to parameter-level "required" in JSON Schema.
	ForceUse     bool   `json:"force_use,omitempty"`
	Source       string `json:"source,omitempty"` // e.g. "local", "mcp", "agent"
	MCPServerURI string `json:"mcp_server_uri,omitempty"`
	AgentID      string `json:"agent_id,omitempty"`
	ReadOnly     bool   `json:"read_only,omitempty"`
}

ToolDef describes a tool that can be registered and invoked.

type ToolResult

type ToolResult struct {
	ToolCallID string        `json:"tool_call_id"`
	Content    []ContentPart `json:"content"`
	IsError    bool          `json:"is_error,omitempty"`
}

ToolResult represents the result of a tool execution.

func ErrorResult

func ErrorResult(toolCallID, errMsg string) ToolResult

ErrorResult creates an error tool result.

func TextResult

func TextResult(toolCallID, text string) ToolResult

TextResult creates a successful text tool result.

type ToolResultData

type ToolResultData struct {
	ToolCallID string     `json:"tool_call_id"`
	ToolName   string     `json:"tool_name"`
	Result     ToolResult `json:"result"`
}

ToolResultData carries the result of a tool execution.

Jump to

Keyboard shortcuts

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