types

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	APIChunkTypeContentBlockStart = "content_block_start"
	APIChunkTypeContentBlockDelta = "content_block_delta"
	APIChunkTypeContentBlockStop  = "content_block_stop"
	APIChunkTypeMessageDelta      = "message_delta"
	APIChunkTypeMessageStop       = "message_stop"
	APIChunkTypeError             = "error"
)
View Source
const (
	ContextKeySessionID = "session_id"
	ContextKeyTurnID    = "turn_id"
	ContextKeyRequestID = "request_id"
	ContextKeyTraceID   = "trace_id"
)

Context keys for request tracing and correlation

View Source
const (
	StopReasonEndTurn      = "end_turn"
	StopReasonMaxTokens    = "max_tokens"
	StopReasonStopSequence = "stop_sequence"
	StopReasonToolUse      = "tool_use"
)

StopReason constants

View Source
const (
	CompactionBoundaryVersionV1 = 1
)
View Source
const POWERSHELL_TOOL_NAME = "powershell"

POWERSHELL_TOOL_NAME is the constant name for the PowerShell tool. Aligned with OpenClaude (permissions.ts:573).

View Source
const SessionMetadataSchemaVersion = 1

SessionMetadataSchemaVersion is the current schema version for persisted session metadata. Increment this constant whenever SessionMetadata gains a breaking structural change, and add migration logic in engine.migrateSessionMetadata.

Variables

View Source
var RuntimeEventEmitterKey = contextKeyRuntimeEventEmitter{}

RuntimeEventEmitterKey is used with context.WithValue to inject the parent session's event emitter into sub-agent calls, enabling streaming bridge from sub-agent to parent.

Functions

func ActiveCompactionPreservedTail

func ActiveCompactionPreservedTail(messages []Message) ([]Message, *CompactionMetadata, bool)

func AgentUserIDFromContext

func AgentUserIDFromContext(ctx context.Context) string

AgentUserIDFromContext returns the user ID from ctx, or empty string if absent.

func CanonicalTranscriptHash

func CanonicalTranscriptHash(messages []Message) (string, error)

CanonicalTranscriptHash computes a stable, normalized SHA-256 hash of the canonical transcript entries. It round-trips the JSON payload through a generic unmarshaling step to convert any nested structures (such as GitDiff) to generic maps, ensuring key ordering is consistently alphabetical.

func CanonicalTranscriptMessageCount

func CanonicalTranscriptMessageCount(messages []Message) int

func CanonicalTranscriptPrefix

func CanonicalTranscriptPrefix(messages []Message, prefix []Message) bool

func ContentBlocksContainToolUse

func ContentBlocksContainToolUse(content []ContentBlock) bool

ContentBlocksContainToolUse returns true when a response content array includes a tool_use block.

func CountCompactionArtifacts

func CountCompactionArtifacts(messages []Message) int

func CountCompactionMessages

func CountCompactionMessages(messages []Message) int

func CountDistinctTurnIDs

func CountDistinctTurnIDs(messages []Message) int

func CountPreservedTailMessages

func CountPreservedTailMessages(messages []Message) int

func CountPreservedTailToolResultMessages

func CountPreservedTailToolResultMessages(messages []Message) int

func CountPreservedTailTurns

func CountPreservedTailTurns(messages []Message) int

func CountToolResultMessages

func CountToolResultMessages(messages []Message) int

func FlattenSystemPromptBlocks

func FlattenSystemPromptBlocks(blocks []SystemPromptBlock) string

FlattenSystemPromptBlocks joins prompt blocks in order for providers that only support a single flattened system prompt string.

func HasCompactionBoundaryDescriptor

func HasCompactionBoundaryDescriptor(metadata *CompactionMetadata) bool

func HasCompactionMetadata

func HasCompactionMetadata(message Message) bool

func IsCanonicalTranscriptEntry

func IsCanonicalTranscriptEntry(entry TranscriptEntry) bool

func IsCanonicalTranscriptMessage

func IsCanonicalTranscriptMessage(message Message) bool

func IsCompactionArtifactMessage

func IsCompactionArtifactMessage(message Message) bool

func IsCompactionMarkerMessage

func IsCompactionMarkerMessage(message Message) bool

func IsCompactionSummaryMessage

func IsCompactionSummaryMessage(message Message) bool

func IsStreamingRetryable

func IsStreamingRetryable(err *EngineError) bool

IsStreamingRetryable returns true if a chunk error should be handled like a retryable API error.

func IsTranscriptCompactionEntry

func IsTranscriptCompactionEntry(entry TranscriptEntry) bool

func IsTranscriptSystemEntry

func IsTranscriptSystemEntry(entry TranscriptEntry) bool

func LegacyCanonicalTranscriptHash

func LegacyCanonicalTranscriptHash(messages []Message) (string, error)

LegacyCanonicalTranscriptHash calculates the hash of the raw marshaled entries without recursively normalizing nested objects to maps.

func MessageTranscriptMetadataSignature

func MessageTranscriptMetadataSignature(message Message) string

func MessagesEquivalentForTranscript

func MessagesEquivalentForTranscript(left Message, right Message) bool

func NormalizeStopReason

func NormalizeStopReason(reason string, content []ContentBlock) string

NormalizeStopReason returns the canonical runtime stop reason.

func SubAgentMaxDepthFromContext

func SubAgentMaxDepthFromContext(ctx context.Context) int

SubAgentMaxDepthFromContext returns the configured depth limit from ctx, or 0 if none was set (caller should then use the server default constant).

func ValidateCompactionBoundary

func ValidateCompactionBoundary(messages []Message) error

func WithAgentUserID

func WithAgentUserID(ctx context.Context, userID string) context.Context

WithAgentUserID returns a context carrying the authenticated user's ID.

func WithSubAgentMaxDepth

func WithSubAgentMaxDepth(ctx context.Context, depth int) context.Context

WithSubAgentMaxDepth returns a context carrying the user-configured sub-agent depth limit. The agent tool reads this to override the server-wide default. Pass 0 to clear any override and fall back to the server default.

Types

type APIChunkAccumulator

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

APIChunkAccumulator rebuilds a complete response from streaming chunks.

func (*APIChunkAccumulator) AddChunk

func (a *APIChunkAccumulator) AddChunk(chunk APIResponseChunk)

AddChunk folds a chunk into the aggregate response state.

func (*APIChunkAccumulator) Build

func (a *APIChunkAccumulator) Build(model ModelIdentifier, responseID string) APIResponse

Build returns the aggregated response.

type APIChunkType

type APIChunkType string

APIChunkType represents the type of chunk in a streaming response

type APIProvider

type APIProvider string

APIProvider represents the API provider being used

const (
	// Anthropic - Direct API (Claude models)
	APIProviderAnthropic APIProvider = "anthropic"

	// OpenAI - Direct API (GPT models)
	APIProviderOpenAI APIProvider = "openai"

	// Ollama - Local models
	APIProviderOllama APIProvider = "ollama"

	// AWS Bedrock - Claude via AWS
	APIProviderBedrock APIProvider = "bedrock"

	// Google Cloud Vertex AI - Claude via GCP
	APIProviderVertex APIProvider = "vertex"

	// Microsoft Azure AI Foundry - Claude via Azure
	APIProviderFoundry APIProvider = "foundry"

	// Google Gemini - Direct API
	APIProviderGemini APIProvider = "gemini"

	// Z.ai - Chinese AI platform (GLM models)
	APIProviderZAi APIProvider = "z-ai"

	// OpenRouter - Unified API for multiple providers
	APIProviderOpenRouter APIProvider = "openrouter"

	// MiniMax - Chinese AI platform
	APIProviderMiniMax APIProvider = "minimax"

	// Cloudflare Workers AI
	APIProviderWorkersAI APIProvider = "workers-ai"

	// Mistral AI - Direct API (OpenAI-compatible)
	APIProviderMistral APIProvider = "mistral"

	// Codex - ChatGPT Pro subscription via chatgpt.com/backend-api (Responses API, OAuth)
	APIProviderCodex APIProvider = "codex"

	// DeepSeek - Direct API (OpenAI-compatible)
	APIProviderDeepSeek APIProvider = "deepseek"

	// OpenCode Zen - Curated model gateway (OpenAI-compatible)
	APIProviderOpenCode APIProvider = "opencode"

	// Kimi (Moonshot AI) - Direct API (OpenAI-compatible)
	APIProviderKimi APIProvider = "kimi"
)

type APIRequest

type APIRequest struct {
	// Model is the model to use
	Model ModelIdentifier `json:"model"`

	// Messages are the messages to send
	Messages []Message `json:"messages"`

	// SystemPrompt is the legacy flattened system prompt.
	// When SystemPromptBlocks is provided, request builders should prefer the
	// structured representation and use this field only as a fallback.
	SystemPrompt string `json:"system_prompt,omitempty"`

	// SystemPromptBlocks carries the canonical prompt split.
	SystemPromptBlocks []SystemPromptBlock `json:"system_prompt_blocks,omitempty"`

	// Tools is the stable provider-facing tool surface.
	Tools []APIToolDefinition `json:"tools,omitempty"`

	// MaxTokens is the maximum tokens to generate
	MaxTokens int `json:"max_tokens"`

	// Temperature controls randomness (0-1)
	Temperature *float64 `json:"temperature,omitempty"`

	// TopK controls diversity
	TopK *int `json:"top_k,omitempty"`

	// TopP controls nucleus sampling
	TopP *float64 `json:"top_p,omitempty"`

	// StopSequences are sequences that will stop generation
	StopSequences []string `json:"stop_sequences,omitempty"`

	// Stream enables streaming responses
	Stream bool `json:"stream,omitempty"`

	// Metadata contains additional request metadata
	Metadata map[string]any `json:"metadata,omitempty"`

	// OutputSchema, when set, constrains the model to return JSON matching the
	// given schema. Providers with native support (OpenAI, Gemini) use their
	// structured-output API. Other providers receive a system message injection.
	OutputSchema *schema.StructuredOutputInfo `json:"output_schema,omitempty"`
}

APIRequest represents a request to the API

type APIResponse

type APIResponse struct {
	// Role is always "assistant" for responses
	Role Role `json:"role"`

	// Content is the response content
	Content []ContentBlock `json:"content"`

	// StopReason is why generation stopped
	StopReason string `json:"stop_reason"`

	// StopSequence is the sequence that caused the stop (if applicable)
	StopSequence *string `json:"stop_sequence,omitempty"`

	// Usage is token usage information
	Usage TokenUsage `json:"usage"`

	// Model is the model that was used
	Model ModelIdentifier `json:"model"`

	// ID is the response ID
	ID string `json:"id"`
}

APIResponse represents a complete API response

func (APIResponse) MarshalJSON

func (r APIResponse) MarshalJSON() ([]byte, error)

func (*APIResponse) UnmarshalJSON

func (r *APIResponse) UnmarshalJSON(data []byte) error

type APIResponseChunk

type APIResponseChunk struct {
	// Type is the type of chunk
	Type APIChunkType `json:"type"`

	// Delta is the text delta (for text chunks)
	Delta string `json:"delta,omitempty"`

	// DeltaType identifies the provider delta payload variant.
	DeltaType string `json:"delta_type,omitempty"`

	// PartialJSON carries an incremental tool_use input payload.
	PartialJSON string `json:"partial_json,omitempty"`

	// ContentBlock is a complete content block
	ContentBlock ContentBlock `json:"content_block,omitempty"`

	// StopReason is why generation stopped
	StopReason *string `json:"stop_reason,omitempty"`

	// StopSequence is the stop sequence emitted by the provider, if any.
	StopSequence *string `json:"stop_sequence,omitempty"`

	// Usage is token usage information
	Usage *TokenUsage `json:"usage,omitempty"`

	// Error contains any error
	Error *EngineError `json:"error,omitempty"`
}

APIResponseChunk represents a chunk of a streaming API response

type APIStream

type APIStream <-chan APIResponseChunk

APIStream is a stream of API response chunks

type APIStreamResult

type APIStreamResult struct {
	Response APIResponse        `json:"response"`
	Chunks   []APIResponseChunk `json:"chunks,omitempty"`
}

APIStreamResult is the canonical aggregated result reconstructed from streaming chunks.

type APIToolDefinition

type APIToolDefinition struct {
	Name        string                `json:"name"`
	Description string                `json:"description"`
	InputSchema toolschema.JSONSchema `json:"input_schema,omitempty"`
	// CacheControl, when set, instructs Anthropic to cache all content up to
	// and including this tool definition. Set on the last tool in the list.
	CacheControl *PromptCacheControl `json:"cache_control,omitempty"`
}

APIToolDefinition is the stable provider-facing tool schema used by Seshat.

type AgentID

type AgentID string

AgentID uniquely identifies an agent/subagent

type AgentRuntimeEvent

type AgentRuntimeEvent struct {
	// CallID is the tool_use ID of the spawning / waiting / interaction call.
	CallID string `json:"call_id"`
	// AgentID is the stable agent identifier (returned by spawn_agent).
	AgentID string `json:"agent_id"`
	// AgentNickname is the optional random human-friendly name (e.g. "Orion").
	AgentNickname string `json:"agent_nickname,omitempty"`
	// AgentRole is the optional role the agent was spawned with (e.g. "reviewer").
	AgentRole string `json:"agent_role,omitempty"`
	// Prompt is the initial or follow-up prompt (may be empty to prevent leaking CoT).
	Prompt string `json:"prompt,omitempty"`
	// Status is the last known CollabAgentStatus of the agent.
	Status string `json:"status,omitempty"`
	// Message is the inter-agent message text for interaction events.
	Message string `json:"message,omitempty"`
	// StartedAtMs is the Unix millisecond timestamp for begin events.
	StartedAtMs int64 `json:"started_at_ms,omitempty"`
	// CompletedAtMs is the Unix millisecond timestamp for end events.
	CompletedAtMs int64 `json:"completed_at_ms,omitempty"`
}

AgentRuntimeEvent is the structured payload for agent.spawn/wait/interaction/close events. Mirrors Codex's CollabAgent*Event family from protocol.rs.

type BrowserRuntimeEvent

type BrowserRuntimeEvent struct {
	Action string `json:"action,omitempty"`

	PageID       string `json:"page_id,omitempty"`
	URL          string `json:"url,omitempty"`
	Title        string `json:"title,omitempty"`
	ActivePageID string `json:"active_page_id,omitempty"`

	PageCount    int `json:"page_count,omitempty"`
	ActionCount  int `json:"action_count,omitempty"`
	ElementCount int `json:"element_count,omitempty"`
	HeadingCount int `json:"heading_count,omitempty"`
	TextLength   int `json:"text_length,omitempty"`

	Bytes         int    `json:"bytes,omitempty"`
	PersistedPath string `json:"persisted_path,omitempty"`
	PersistedSize int    `json:"persisted_size,omitempty"`
	FullPage      bool   `json:"full_page,omitempty"`
}

BrowserRuntimeEvent is the structured payload emitted for browser lifecycle and interaction activity.

type CanUseToolFn

type CanUseToolFn func(ctx context.Context, request ToolPermissionRequest) PermissionResult

CanUseToolFn is a function that checks if a tool can be used. It is the key interface that decouples permissions from tool execution. CanUseToolFn also implements PermissionResolver.

func CanUseToolFunc

func CanUseToolFunc(resolver PermissionResolver) CanUseToolFn

CanUseToolFunc adapts a PermissionResolver to the CanUseToolFn form.

func (CanUseToolFn) ResolvePermission

func (f CanUseToolFn) ResolvePermission(ctx context.Context, request ToolPermissionRequest) PermissionResult

ResolvePermission implements PermissionResolver for CanUseToolFn.

type CompactionMetadata

type CompactionMetadata struct {
	Kind                    string    `json:"kind,omitempty"`
	PreCompactTokens        int       `json:"pre_compact_tokens,omitempty"`
	PostCompactTokens       int       `json:"post_compact_tokens,omitempty"`
	TargetTokens            int       `json:"target_tokens,omitempty"`
	PreservedMessages       int       `json:"preserved_messages,omitempty"`
	PreservedTurns          int       `json:"preserved_turns,omitempty"`
	PreservedToolPairs      int       `json:"preserved_tool_pairs,omitempty"`
	BoundaryVersion         int       `json:"boundary_version,omitempty"`
	FirstPreservedMessageID MessageID `json:"first_preserved_message_id,omitempty"`
	LastPreservedMessageID  MessageID `json:"last_preserved_message_id,omitempty"`
	PreservedTailHash       string    `json:"preserved_tail_hash,omitempty"`
}

CompactionMetadata describes a runtime-owned compaction rewrite that has been materialized into the canonical transcript.

func ActiveCompactionBoundary

func ActiveCompactionBoundary(messages []Message) (*CompactionMetadata, int, int, bool)

func BuildCompactionMetadata

func BuildCompactionMetadata(kind string, preCompactTokens int, postCompactTokens int, targetTokens int, preservedMessages int, preservedTurns int, preservedToolPairs int) *CompactionMetadata

func CloneCompactionMetadata

func CloneCompactionMetadata(metadata *CompactionMetadata) *CompactionMetadata

func CompactionMetadataFromMessages

func CompactionMetadataFromMessages(messages []Message) *CompactionMetadata

type ContentBlock

type ContentBlock interface {
	ContentType() ContentType
}

ContentBlock represents a single block of content in a message

type ContentReplacementState

type ContentReplacementState struct {
	// OriginalSize is the original size in bytes
	OriginalSize int64 `json:"original_size"`

	// ReplacedSize is the size after replacement
	ReplacedSize int64 `json:"replaced_size"`

	// ReplacementType indicates what type of replacement occurred
	ReplacementType ContentReplacementType `json:"replacement_type"`

	// Preview is a preview of the original content
	Preview string `json:"preview,omitempty"`

	// FilePath is where the content was stored (if applicable)
	FilePath string `json:"file_path,omitempty"`
}

ContentReplacementState represents when content was replaced due to size

type ContentReplacementType

type ContentReplacementType string

ContentReplacementType represents the type of content replacement

const (
	// ContentReplacementTypeDisk means content was written to disk
	ContentReplacementTypeDisk ContentReplacementType = "disk"

	// ContentReplacementTypePreview means content was replaced with a preview
	ContentReplacementTypePreview ContentReplacementType = "preview"

	// ContentReplacementTypeTruncated means content was truncated
	ContentReplacementTypeTruncated ContentReplacementType = "truncated"
)

type ContentType

type ContentType string

ContentType represents the type of content in a message block

const (
	ContentTypeText       ContentType = "text"
	ContentTypeImage      ContentType = "image"
	ContentTypeToolUse    ContentType = "tool_use"
	ContentTypeToolResult ContentType = "tool_result"
	ContentTypeThinking   ContentType = "thinking"
)

type ContextChangeData

type ContextChangeData struct {
	OldValue string `json:"old_value,omitempty"`
	NewValue string `json:"new_value"`
	Reason   string `json:"reason,omitempty"`
}

ContextChangeData contains data for context change events

type ContextWindow

type ContextWindow struct {
	// MaxTokens is the maximum tokens for the model
	MaxTokens int `json:"max_tokens"`

	// MaxOutputTokens is the maximum tokens that can be generated
	MaxOutputTokens int `json:"max_output_tokens"`
}

ContextWindow represents the context window for a model

func GetContextWindow

func GetContextWindow(m ModelIdentifier) ContextWindow

GetContextWindow returns the context window for a model. It consults the centralised model.Global registry first; if the model is not found there it falls back to a conservative default (128k/4k).

type DangerousPattern

type DangerousPattern struct {
	// ToolName is the tool this pattern applies to. Empty means all tools.
	ToolName string `json:"tool_name"`

	// Pattern is a substring match in the input (key or value).
	Pattern string `json:"pattern"`

	// Reason explains why this pattern is dangerous.
	Reason string `json:"reason"`

	// CheckType identifies the check source.
	CheckType string `json:"check_type"`
}

DangerousPattern defines a safety rule.

type DangerousPatternChecker

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

DangerousPatternChecker is a simple pattern-based safety checker.

func NewDangerousPatternChecker

func NewDangerousPatternChecker() *DangerousPatternChecker

NewDangerousPatternChecker creates a checker with default patterns.

func (*DangerousPatternChecker) AddPattern

func (c *DangerousPatternChecker) AddPattern(toolName string, pattern DangerousPattern)

AddPattern registers a dangerous pattern for a tool.

func (*DangerousPatternChecker) CheckSafety

func (c *DangerousPatternChecker) CheckSafety(toolName string, input map[string]any) SafetyCheckResult

CheckSafety evaluates input against registered patterns.

type DenialLimitConfig

type DenialLimitConfig struct {
	// MaxConsecutiveDenials triggers fallback when reached.
	// A value of 0 means no limit.
	MaxConsecutiveDenials int `json:"max_consecutive_denials"`

	// MaxTotalDenials triggers fallback when reached.
	// A value of 0 means no limit.
	MaxTotalDenials int `json:"max_total_denials"`

	// ResetAfterSeconds without a denial resets consecutive counter.
	// A value of 0 means no time-based reset.
	ResetAfterSeconds int `json:"reset_after_seconds"`
}

DenialLimitConfig defines thresholds for denial-based fallback.

func DefaultDenialLimitConfig

func DefaultDenialLimitConfig() DenialLimitConfig

DefaultDenialLimitConfig returns sensible defaults.

func (DenialLimitConfig) ShouldFallback

func (c DenialLimitConfig) ShouldFallback(state *DenialTrackingState) bool

ShouldFallback returns true if the denial state exceeds configured limits. When the time-based reset threshold is exceeded, consecutive denials are automatically reset before evaluating the limit.

type DenialTrackingState

type DenialTrackingState struct {

	// ConsecutiveDenials counts refusals in a row since the last success.
	ConsecutiveDenials int `json:"consecutive_denials"`

	// TotalDenials is the cumulative count of denials in this session.
	TotalDenials int `json:"total_denials"`

	// LastDeniedAt records when the most recent denial occurred.
	LastDeniedAt *time.Time `json:"last_denied_at,omitempty"`

	// LastAllowedAt records when the most recent allowance occurred.
	LastAllowedAt *time.Time `json:"last_allowed_at,omitempty"`
	// contains filtered or unexported fields
}

DenialTrackingState tracks consecutive permission denials for a session.

func (*DenialTrackingState) GetConsecutiveDenials

func (d *DenialTrackingState) GetConsecutiveDenials() int

GetConsecutiveDenials returns the current consecutive denial count.

func (*DenialTrackingState) GetTotalDenials

func (d *DenialTrackingState) GetTotalDenials() int

GetTotalDenials returns the total denial count.

func (*DenialTrackingState) RecordDenial

func (d *DenialTrackingState) RecordDenial()

RecordDenial increments the denial counters and updates the last denied timestamp.

func (*DenialTrackingState) RecordSuccess

func (d *DenialTrackingState) RecordSuccess()

RecordSuccess resets the consecutive denial counter and updates the last allowed timestamp.

type ElicitationData

type ElicitationData struct {
	RequestID string           `json:"request_id"`
	Prompt    string           `json:"prompt"`
	Options   []map[string]any `json:"options,omitempty"`
}

ElicitationData contains data for elicitation events

type EngineError

type EngineError struct {
	// Code is the error code
	Code ErrorCode `json:"code"`

	// Message is a human-readable message
	Message string `json:"message"`

	// Err is the underlying error
	Err error `json:"-"`

	// Context contains additional error context
	Context map[string]any `json:"context,omitempty"`
}

EngineError represents an error in the engine

func NewError

func NewError(code ErrorCode, message string) *EngineError

NewError creates a new EngineError

func WrapError

func WrapError(code ErrorCode, message string, err error) *EngineError

WrapError wraps an existing error

func WrapErrorWithContext

func WrapErrorWithContext(code ErrorCode, message string, err error, context map[string]any) *EngineError

WrapErrorWithContext wraps an error with additional context

func (*EngineError) Error

func (e *EngineError) Error() string

Error implements the error interface

func (*EngineError) IsAPIError

func (e *EngineError) IsAPIError() bool

IsAPIError returns true if this is an API-related error

func (*EngineError) IsPermanent

func (e *EngineError) IsPermanent() bool

IsPermanent returns true if the error is permanent (not retryable)

func (*EngineError) IsRetryable

func (e *EngineError) IsRetryable() bool

IsRetryable returns true if the error is retryable

func (*EngineError) Unwrap

func (e *EngineError) Unwrap() error

Unwrap returns the underlying error

type EntryType

type EntryType string

EntryType represents the type of transcript entry

const (
	EntryTypeMessage EntryType = "message"
	EntryTypeTurn    EntryType = "turn"
	EntryTypeCompact EntryType = "compact"
	EntryTypeSystem  EntryType = "system"
	EntryTypeControl EntryType = "control"
)

type ErrorCode

type ErrorCode string

ErrorCode represents a specific error type

const (
	// API errors
	ErrCodeAPIRequest   ErrorCode = "api_request"
	ErrCodeAPIResponse  ErrorCode = "api_response"
	ErrCodeAPIRateLimit ErrorCode = "api_rate_limit"
	ErrCodeAPIAuth      ErrorCode = "api_auth"
	ErrCodeAPITimeout   ErrorCode = "api_timeout"
	ErrCodeAPIInvalid   ErrorCode = "api_invalid"

	// Tool errors
	ErrCodeToolNotFound     ErrorCode = "tool_not_found"
	ErrCodeToolExecution    ErrorCode = "tool_execution"
	ErrCodeToolPermission   ErrorCode = "tool_permission"
	ErrCodeToolTimeout      ErrorCode = "tool_timeout"
	ErrCodeToolInvalidInput ErrorCode = "tool_invalid_input"

	// Permission errors
	ErrCodePermissionDenied ErrorCode = "permission_denied"
	ErrCodePermissionError  ErrorCode = "permission_error"

	// Session errors
	ErrCodeSessionNotFound    ErrorCode = "session_not_found"
	ErrCodeSessionClosed      ErrorCode = "session_closed"
	ErrCodeSessionInterrupted ErrorCode = "session_interrupted"

	// Compact errors
	ErrCodeCompactFailed ErrorCode = "compact_failed"
	ErrCodeCompactFull   ErrorCode = "compact_full"

	// General errors
	ErrCodeInvalidInput ErrorCode = "invalid_input"
	ErrCodeInternal     ErrorCode = "internal"
	ErrCodeNotSupported ErrorCode = "not_supported"
)

type ExecutionOrigin

type ExecutionOrigin string

ExecutionOrigin indicates whether a run is initiated by an interactive user flow or a future background automation.

const (
	ExecutionOriginInteractive ExecutionOrigin = "interactive"
	ExecutionOriginAutomation  ExecutionOrigin = "automation"
	ExecutionOriginSkillAgent  ExecutionOrigin = "skill_agent"
)

func NormalizeExecutionOrigin

func NormalizeExecutionOrigin(raw string) ExecutionOrigin

type GoalRuntimeEvent

type GoalRuntimeEvent struct {
	// SessionID identifies the session this goal belongs to.
	SessionID string `json:"session_id"`
	// Objective is the current goal objective text.
	Objective string `json:"objective"`
	// Status is the current ThreadGoalStatus string.
	Status string `json:"status"`
	// TokenBudget is the optional max token budget.
	TokenBudget *int64 `json:"token_budget,omitempty"`
	// TokensUsed is the cumulative tokens consumed so far.
	TokensUsed int64 `json:"tokens_used"`
	// TimeUsedSeconds is the elapsed wall-clock time since goal creation.
	TimeUsedSeconds int64 `json:"time_used_seconds"`
	// CreatedAt is the Unix millisecond timestamp when the goal was created.
	CreatedAt int64 `json:"created_at"`
	// UpdatedAt is the Unix millisecond timestamp of the last update.
	UpdatedAt int64 `json:"updated_at"`
}

GoalRuntimeEvent is the structured payload for goal.updated events. Mirrors Codex's ThreadGoalUpdatedEvent / ThreadGoalUpdatedNotification.

type GranularConfig

type GranularConfig struct {
	// SandboxApproval controls whether sandbox approval prompts are allowed.
	// When true, commands that match sandbox policy can request approval.
	// When false, sandbox prompts are auto-denied.
	SandboxApproval bool `json:"sandbox_approval,omitempty"`

	// RulesApproval controls whether exec-policy "prompt" rules trigger approval prompts.
	// When true, rules with behavior=ask can prompt for approval.
	// When false, rule-based prompts are auto-denied.
	RulesApproval bool `json:"rules_approval,omitempty"`

	// SkillApproval controls whether skill script execution triggers approval prompts.
	// When true, skill scripts can request additional permissions.
	// When false, skill approval prompts are auto-denied.
	SkillApproval bool `json:"skill_approval,omitempty"`

	// RequestPermissionsApproval controls whether request_permissions tool triggers prompts.
	// When true, users can request additional permissions via tool.
	// When false, permission requests are auto-denied.
	RequestPermissionsApproval bool `json:"request_permissions_approval,omitempty"`
}

GranularConfig provides fine-grained approval controls. Each field controls whether prompts in that category are allowed. When a field is true, commands in that category are auto-approved. When false, those requests are automatically denied instead of shown to the user.

func DefaultGranularConfig

func DefaultGranularConfig() GranularConfig

DefaultGranularConfig returns the default granular configuration. All approvals are allowed by default.

func (GranularConfig) AllowsRequestPermissionsApproval

func (g GranularConfig) AllowsRequestPermissionsApproval() bool

AllowsRequestPermissionsApproval returns true if request_permissions tool prompts are allowed.

func (GranularConfig) AllowsRulesApproval

func (g GranularConfig) AllowsRulesApproval() bool

AllowsRulesApproval returns true if exec-policy rule approval prompts are allowed.

func (GranularConfig) AllowsSandboxApproval

func (g GranularConfig) AllowsSandboxApproval() bool

AllowsSandboxApproval returns true if sandbox approval prompts are allowed.

func (GranularConfig) AllowsSkillApproval

func (g GranularConfig) AllowsSkillApproval() bool

AllowsSkillApproval returns true if skill approval prompts are allowed.

type Hook

type Hook interface {
	// Execute runs the hook and returns the result.
	Execute(ctx context.Context, stage HookStage, toolName string, toolInput map[string]any, metadata map[string]any) HookResult

	// Priority determines hook execution order (higher = earlier).
	Priority() int

	// Name identifies the hook.
	Name() string
}

Hook represents a permission hook interface. Aligned with OpenClaude's PermissionHook (permissions.ts:628-639).

type HookAction

type HookAction string

HookAction represents the action to take after a hook. Aligned with OpenClaude's HookAction (permissions.ts:630-633).

const (
	HookActionContinue HookAction = "continue"
	HookActionStop     HookAction = "stop"
	// HookActionDeny explicitly blocks an operation (tool call, model call).
	// Semantically equivalent to Stop but carries an explicit denial message.
	HookActionDeny   HookAction = "deny"
	HookActionModify HookAction = "modify"
	HookActionRetry  HookAction = "retry"
)

type HookEvent

type HookEvent string

HookEvent represents a lifecycle event in the engine

const (
	// Session hooks
	HookEventSessionStart HookEvent = "session_start"
	HookEventSessionEnd   HookEvent = "session_end"

	// Query/Loop hooks
	HookEventQueryStart        HookEvent = "query_start"
	HookEventQueryComplete     HookEvent = "query_complete"
	HookEventIterationStart    HookEvent = "iteration_start"
	HookEventIterationStop     HookEvent = "iteration_stop"
	HookEventIterationContinue HookEvent = "iteration_continue"
	HookEventIterationComplete HookEvent = "iteration_complete"
	HookEventToolUsesStart     HookEvent = "tool_uses_start"
	HookEventToolUsesComplete  HookEvent = "tool_uses_complete"

	// Turn hooks
	HookEventTurnStart   HookEvent = "turn_start"
	HookEventTurnEnd     HookEvent = "turn_end"
	HookEventTurnStop    HookEvent = "turn_stop"
	HookEventStopFailure HookEvent = "stop_failure"

	// Tool hooks
	HookEventPreToolUse      HookEvent = "pre_tool_use"
	HookEventPostToolUse     HookEvent = "post_tool_use"
	HookEventPostToolUseFail HookEvent = "post_tool_use_fail"

	// Compact hooks
	HookEventPreCompact  HookEvent = "pre_compact"
	HookEventPostCompact HookEvent = "post_compact"

	// API hooks
	HookEventPreAPICall  HookEvent = "pre_api_call"
	HookEventPostAPICall HookEvent = "post_api_call"

	// Error hooks
	HookEventOnError HookEvent = "on_error"

	// Notification hooks
	HookEventNotification HookEvent = "notification"

	// User prompt hooks
	HookEventUserPromptSubmit HookEvent = "user_prompt_submit"

	// Subagent hooks
	HookEventSubagentStart HookEvent = "subagent_start"
	HookEventSubagentStop  HookEvent = "subagent_stop"

	// Permission hooks
	HookEventPermissionRequest HookEvent = "permission_request"
	HookEventPermissionDenied  HookEvent = "permission_denied"

	// System hooks
	HookEventSetup        HookEvent = "setup"
	HookEventConfigChange HookEvent = "config_change"

	// Multi-agent hooks
	HookEventTeammateIdle HookEvent = "teammate_idle"

	// Task hooks
	HookEventTaskCreated   HookEvent = "task_created"
	HookEventTaskCompleted HookEvent = "task_completed"

	// Elicitation hooks
	HookEventElicitation       HookEvent = "elicitation"
	HookEventElicitationResult HookEvent = "elicitation_result"

	// Worktree hooks
	HookEventWorktreeCreate HookEvent = "worktree_create"
	HookEventWorktreeRemove HookEvent = "worktree_remove"

	// Context hooks
	HookEventInstructionsLoaded HookEvent = "instructions_loaded"
	HookEventCwdChanged         HookEvent = "cwd_changed"
	HookEventFileChanged        HookEvent = "file_changed"
)

type HookHandler

type HookHandler func(ctx context.Context, progress HookProgress) (*HookResult, error)

HookHandler is a function that handles a hook event. It may return a HookResult to signal Deny, Modify, or Retry actions. Returning (nil, nil) is equivalent to HookActionContinue.

type HookProgress

type HookProgress struct {
	// Event is the hook event type
	Event HookEvent `json:"event"`

	// Message is a human-readable message
	Message string `json:"message,omitempty"`

	// Data contains event-specific data
	Data map[string]any `json:"data,omitempty"`
}

HookProgress represents progress information for a hook

type HookRegistration

type HookRegistration struct {
	// Event is the event this hook is registered for
	Event HookEvent `json:"event"`

	// Stage is when this hook should be called
	Stage HookStage `json:"stage"`

	// Handler is the function to call
	Handler HookHandler `json:"-"`

	// Priority determines order (higher = earlier)
	Priority int `json:"priority"`

	// ID uniquely identifies this hook registration
	ID string `json:"id"`
}

HookRegistration represents a registered hook

type HookResult

type HookResult struct {
	// Action indicates what action to take.
	Action HookAction `json:"action"`

	// UpdatedInput contains modified input from the hook.
	UpdatedInput map[string]any `json:"updated_input,omitempty"`

	// Message contains a message to display to the user.
	Message string `json:"message,omitempty"`

	// Retry indicates that the tool should be retried.
	Retry bool `json:"retry,omitempty"`

	// Metadata contains additional hook-specific data.
	Metadata map[string]any `json:"metadata,omitempty"`
}

HookResult represents the result of a hook execution. Aligned with OpenClaude's HookResult (permissions.ts:629-633).

type HookStage

type HookStage string

HookStage represents when a hook should be called

const (
	HookStagePre    HookStage = "pre"
	HookStagePost   HookStage = "post"
	HookStageAround HookStage = "around"

	// Permission-specific hook stages
	HookStagePrePermission  HookStage = "pre_permission"
	HookStagePostPermission HookStage = "post_permission"
)

type ImageContent

type ImageContent struct {
	Source struct {
		Type      string `json:"type"`
		MediaType string `json:"media_type"`
		Data      string `json:"data"`
	} `json:"source"`
}

ImageContent represents an image content block

func (ImageContent) ContentType

func (ImageContent) ContentType() ContentType

type Message

type Message struct {
	ID        MessageID        `json:"id"`
	Role      Role             `json:"role"`
	Content   []ContentBlock   `json:"content"`
	Timestamp time.Time        `json:"timestamp"`
	Metadata  *MessageMetadata `json:"metadata,omitempty"`
}

Message represents a single message in the conversation

func AssistantMessage

func AssistantMessage(id string, content []ContentBlock) Message

AssistantMessage is a helper to create an assistant message

func CanonicalMessagesFromTranscriptEntries

func CanonicalMessagesFromTranscriptEntries(entries []TranscriptEntry) []Message

func CanonicalTranscriptMessages

func CanonicalTranscriptMessages(messages []Message) []Message

func CloneMessages

func CloneMessages(messages []Message) []Message

func LastCompactionMessage

func LastCompactionMessage(messages []Message) (Message, bool)

func MessageFromTranscriptEntry

func MessageFromTranscriptEntry(entry TranscriptEntry) (Message, bool)

func MessagesFromTranscriptEntries

func MessagesFromTranscriptEntries(entries []TranscriptEntry) []Message

func SystemMessage

func SystemMessage(id string, content string) Message

SystemMessage creates a system message (for internal use)

func UserMessage

func UserMessage(id string, content string) Message

UserMessage is a helper to create a user message

func UserMessageWithImage

func UserMessageWithImage(id string, text string, images ...ImageContent) Message

UserMessageWithImage is a helper to create a user message with an image

func WithCompactionMetadata

func WithCompactionMetadata(message Message, metadata *CompactionMetadata) Message

func WithoutCompactionMetadata

func WithoutCompactionMetadata(message Message) Message

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

type MessageID

type MessageID string

MessageID uniquely identifies a message

func NewMessageID

func NewMessageID(id string) MessageID

NewMessageID creates a new message ID (wrapper for clarity)

func (MessageID) String

func (m MessageID) String() string

String returns the string representation

type MessageMetadata

type MessageMetadata struct {
	TurnID string `json:"turn_id,omitempty"`

	StopReason string `json:"stop_reason,omitempty"`

	StopSequence *string `json:"stop_sequence,omitempty"`

	Usage *TokenUsage `json:"usage,omitempty"`

	Compaction *CompactionMetadata `json:"compaction,omitempty"`
}

MessageMetadata contains optional metadata about a message.

func CloneMessageMetadata

func CloneMessageMetadata(metadata *MessageMetadata) *MessageMetadata

type ModelIdentifier

type ModelIdentifier struct {
	// Provider is the API provider
	Provider APIProvider `json:"provider"`

	// Model is the model name (e.g., "claude-3-5-sonnet-20241022")
	Model string `json:"model"`

	// Version is the optional version
	Version string `json:"version,omitempty"`
}

ModelIdentifier uniquely identifies a model

func (ModelIdentifier) ProviderModelName

func (m ModelIdentifier) ProviderModelName() string

ProviderModelName returns the provider-facing model identifier. For most providers, this just returns the model as-is. For providers with aliases (like Z.ai), this should resolve via provider config.

func (ModelIdentifier) String

func (m ModelIdentifier) String() string

String returns the string representation

type NotificationData

type NotificationData struct {
	Level   string `json:"level"` // info, warning, error
	Message string `json:"message"`
	Source  string `json:"source,omitempty"`
}

NotificationData contains data for notification events

type PermissionBehavior

type PermissionBehavior string

PermissionBehavior represents what action should be taken.

const (
	// PermissionBehaviorAllow allows the action.
	PermissionBehaviorAllow PermissionBehavior = "allow"

	// PermissionBehaviorDeny denies the action.
	PermissionBehaviorDeny PermissionBehavior = "deny"

	// PermissionBehaviorAsk asks the user for permission.
	PermissionBehaviorAsk PermissionBehavior = "ask"

	// PermissionBehaviorPassthrough delegates to the global permission pipeline.
	PermissionBehaviorPassthrough PermissionBehavior = "passthrough"
)

type PermissionContext

type PermissionContext struct {
	// Mode is the current permission mode (who approves)
	Mode PermissionMode `json:"mode"`

	// ExecutionMode is the current execution mode (what agent does: execute, plan, pair_programming, browse)
	ExecutionMode string `json:"execution_mode,omitempty"`

	// PrePlanMode stores the mode before entering plan mode for restoration
	PrePlanMode PermissionMode `json:"pre_plan_mode,omitempty"`

	// IsBypassPermissionsModeAvailable indicates if bypass permissions were available before plan mode
	IsBypassPermissionsModeAvailable bool `json:"is_bypass_permissions_mode_available,omitempty"`

	// IsAutoModeAvailable indicates if auto mode is available for this session
	IsAutoModeAvailable bool `json:"is_auto_mode_available,omitempty"`

	// StrippedDangerousRules stores permissions that were stripped for auto mode safety
	StrippedDangerousRules map[string][]string `json:"stripped_dangerous_rules,omitempty"`
}

PermissionContext represents the permission mode context for a session. Aligned with OpenClaude's ToolPermissionContext (Tool.ts:123-138).

func (*PermissionContext) NormalizeLegacyPlanMode

func (p *PermissionContext) NormalizeLegacyPlanMode()

NormalizeLegacyPlanMode rewrites deprecated mode=plan contexts so the approval mode remains in Mode while plan state lives in ExecutionMode.

type PermissionDecisionReason

type PermissionDecisionReason struct {
	Type PermissionDecisionReasonType `json:"type"`

	// Source identifies the subsystem or rule source that produced the decision.
	Source string `json:"source,omitempty"`

	// Reason is a human-readable detail for the decision.
	Reason string `json:"reason,omitempty"`

	// RuleBehavior is set when Type is "rule" to indicate the original rule behavior
	// (allow, deny, ask). This lets the pipeline distinguish a content-specific
	// ask-rule from a passthrough ask, and treat ask-rules as bypass-immune.
	RuleBehavior PermissionBehavior `json:"rule_behavior,omitempty"`

	// ClassifierApprovable is set on safetyCheck decisions to indicate that
	// the auto-mode classifier may override this decision. Non-approvable
	// safety checks stay immune to ALL auto-approve paths.
	ClassifierApprovable bool `json:"classifier_approvable,omitempty"`

	// SubcommandResults contains results for each subcommand in a complex command.
	// Used by tools like bash that can execute multiple operations in a single call.
	// Aligned with OpenClaude's subcommandResults (permissions.ts:165-188).
	SubcommandResults map[string]PermissionResult `json:"subcommand_results,omitempty"`

	// Reasons contains detailed reasons for each subcommand when Type is "subcommandResults".
	// Aligned with OpenClaude's decisionReason.reasons (permissions.ts:167).
	Reasons map[string]PermissionDecisionReason `json:"reasons,omitempty"`
}

PermissionDecisionReason records the structured reason for a permission decision.

type PermissionDecisionReasonType

type PermissionDecisionReasonType string

PermissionDecisionReasonType classifies why a permission decision was made.

const (
	PermissionDecisionReasonRule        PermissionDecisionReasonType = "rule"
	PermissionDecisionReasonMode        PermissionDecisionReasonType = "mode"
	PermissionDecisionReasonTool        PermissionDecisionReasonType = "tool"
	PermissionDecisionReasonPrompt      PermissionDecisionReasonType = "prompt"
	PermissionDecisionReasonSafetyCheck PermissionDecisionReasonType = "safetyCheck"
	PermissionDecisionReasonAsyncAgent  PermissionDecisionReasonType = "asyncAgent"
	PermissionDecisionReasonOther       PermissionDecisionReasonType = "other"
)

type PermissionDeniedData

type PermissionDeniedData struct {
	ToolName     string         `json:"tool_name"`
	Input        map[string]any `json:"input"`
	Reason       string         `json:"reason"`
	RetryAllowed bool           `json:"retry_allowed"`
}

PermissionDeniedData contains data for permission denial

type PermissionMode

type PermissionMode string

PermissionMode represents the mode of APPROVAL checking. This determines WHO approves actions (user, classifier, etc.)

const (
	// PermissionModeOnRequest asks the user for permission on non-automated actions.
	// This is the default/standard mode - the model decides when to ask for approval.
	PermissionModeOnRequest PermissionMode = "onRequest"

	// PermissionModeAuto automatically approves actions via classifier.
	PermissionModeAuto PermissionMode = "auto"

	// PermissionModeAcceptEdits automatically allows safe file operations in the working directory.
	// Aligned with OpenClaude's acceptEdits mode (permissions.ts:16-22).
	PermissionModeAcceptEdits PermissionMode = "acceptEdits"

	// PermissionModeBypass bypasses all permission checks.
	PermissionModeBypass PermissionMode = "bypass"

	// PermissionModeNever never asks the user to approve commands.
	// Failures are immediately returned to the model, never escalated to user.
	// Used for headless/background agents that cannot display UI prompts.
	PermissionModeNever PermissionMode = "never"

	// PermissionModeGranular provides fine-grained controls for individual approval flows.
	PermissionModeGranular PermissionMode = "granular"
)

func NormalizePermissionMode

func NormalizePermissionMode(raw string) (PermissionMode, bool)

func NormalizePermissionModeOrDefault

func NormalizePermissionModeOrDefault(mode PermissionMode, fallback PermissionMode) PermissionMode

type PermissionRequestData

type PermissionRequestData struct {
	ToolName       string         `json:"tool_name"`
	Input          map[string]any `json:"input"`
	PermissionMode string         `json:"permission_mode"`
	Context        map[string]any `json:"context,omitempty"`
}

PermissionRequestData contains data for permission requests

type PermissionResolver

type PermissionResolver interface {
	ResolvePermission(ctx context.Context, request ToolPermissionRequest) PermissionResult
}

PermissionResolver resolves permission decisions for the execution runtime.

type PermissionResult

type PermissionResult struct {
	Behavior PermissionBehavior `json:"behavior"`

	// Reason provides a human-readable explanation.
	Reason string `json:"reason,omitempty"`

	// UpdatedInput contains normalized or rewritten input approved by permissions.
	UpdatedInput map[string]any `json:"updated_input,omitempty"`

	// Confidence indicates confidence in the decision (0-1).
	// Only applicable in auto mode with classifier.
	Confidence *float64 `json:"confidence,omitempty"`

	// Metadata contains additional information.
	Metadata map[string]any `json:"metadata,omitempty"`

	// DecisionReason captures the structured reason for this decision.
	DecisionReason *PermissionDecisionReason `json:"decision_reason,omitempty"`

	// DenialTracking tracks denial state when available.
	// Used for auto-mode fallback behavior.
	DenialTracking *DenialTrackingState `json:"denial_tracking,omitempty"`
}

PermissionResult represents the result of a permission check.

func AllowWithDecisionReason

func AllowWithDecisionReason(reason string, decisionReason *PermissionDecisionReason) PermissionResult

AllowWithDecisionReason creates an allow result with a structured reason.

func AllowWithInput

func AllowWithInput(reason string, updatedInput map[string]any) PermissionResult

AllowWithInput creates an Allow result with normalized input.

func AllowWithInputAndDecisionReason

func AllowWithInputAndDecisionReason(reason string, updatedInput map[string]any, decisionReason *PermissionDecisionReason) PermissionResult

AllowWithInputAndDecisionReason creates an allow result with normalized input and a structured reason.

func AllowWithUpdatedInput

func AllowWithUpdatedInput(updatedInput map[string]any) PermissionResult

AllowWithUpdatedInput attaches normalized input to an allow result.

func Ask

func Ask(reason string) PermissionResult

Ask creates an Ask result.

func AskWithDecisionReason

func AskWithDecisionReason(reason string, decisionReason *PermissionDecisionReason) PermissionResult

AskWithDecisionReason creates an ask result with a structured reason.

func Deny

func Deny(reason string) PermissionResult

Deny creates a Deny result.

func DenyWithDecisionReason

func DenyWithDecisionReason(reason string, decisionReason *PermissionDecisionReason) PermissionResult

DenyWithDecisionReason creates a deny result with a structured reason.

func Passthrough

func Passthrough(updatedInput map[string]any) PermissionResult

Passthrough delegates the decision to the global permission pipeline.

func PassthroughWithDecisionReason

func PassthroughWithDecisionReason(updatedInput map[string]any, decisionReason *PermissionDecisionReason) PermissionResult

PassthroughWithDecisionReason delegates to the global permission pipeline with a structured reason.

func (PermissionResult) IsAllowed

func (p PermissionResult) IsAllowed() bool

IsAllowed returns true if the behavior is Allow.

func (PermissionResult) IsAsk

func (p PermissionResult) IsAsk() bool

IsAsk returns true if the behavior is Ask.

func (PermissionResult) IsBypassImmune

func (p PermissionResult) IsBypassImmune() bool

IsBypassImmune returns true if this permission result should not be overridden by bypass mode. This applies to:

  • Deny decisions (always immune)
  • Ask decisions with safetyCheck reason (bypass-immune)
  • Ask decisions with rule ask reason (content-specific ask rules)

func (PermissionResult) IsDenied

func (p PermissionResult) IsDenied() bool

IsDenied returns true if the behavior is Deny.

func (PermissionResult) IsPassthrough

func (p PermissionResult) IsPassthrough() bool

IsPassthrough returns true if the decision should be delegated.

type PermissionRuleSource

type PermissionRuleSource string

PermissionRuleSource represents where a permission rule comes from. Aligned with OpenClaude's PermissionRuleSource (permissions.ts:1352-1365).

const (
	PermissionSourceStatic          PermissionRuleSource = "static"
	PermissionSourceDynamic         PermissionRuleSource = "dynamic"
	PermissionSourceClassifier      PermissionRuleSource = "classifier"
	PermissionSourceHook            PermissionRuleSource = "hook"
	PermissionSourceLocalSettings   PermissionRuleSource = "localSettings"
	PermissionSourceUserSettings    PermissionRuleSource = "userSettings"
	PermissionSourceProjectSettings PermissionRuleSource = "projectSettings"
	PermissionSourceCliArg          PermissionRuleSource = "cliArg"
	PermissionSourceSession         PermissionRuleSource = "session"
)

type PermissionRuleValue

type PermissionRuleValue struct {
	// ToolName identifies the tool this rule targets.
	ToolName string `json:"tool_name"`

	// RuleContent carries optional content-specific matching handled by the tool.
	RuleContent string `json:"rule_content,omitempty"`
}

PermissionRuleValue is the structured value of a permission rule.

type PermissionUpdate

type PermissionUpdate struct {
	// Type is the update type.
	Type PermissionUpdateType `json:"type"`

	// Rules are the permission rule values to update.
	Rules []PermissionRuleValue `json:"rules"`

	// Behavior is the permission behavior.
	Behavior PermissionBehavior `json:"behavior"`

	// Destination is where to apply the rules.
	Destination PermissionRuleSource `json:"destination"`
}

PermissionUpdate represents a permission rule update. Aligned with OpenClaude's PermissionUpdate (permissions.ts:1420-1447).

type PermissionUpdateType

type PermissionUpdateType string

PermissionUpdateType represents the type of permission update. Aligned with OpenClaude (permissions.ts:1421-1423).

const (
	PermissionUpdateTypeAddRules     PermissionUpdateType = "addRules"
	PermissionUpdateTypeReplaceRules PermissionUpdateType = "replaceRules"
	PermissionUpdateTypeDeleteRules  PermissionUpdateType = "deleteRules"
)

type PlanRuntimeEvent

type PlanRuntimeEvent struct {
	PlanID   string `json:"plan_id"`
	Slug     string `json:"slug"`
	Filename string `json:"filename"`
	Status   string `json:"status"`
	Version  int    `json:"version"`
	Content  string `json:"content,omitempty"`
}

PlanRuntimeEvent is emitted when a plan document is submitted or its status changes.

type ProgressStream

type ProgressStream <-chan ToolProgress

ProgressStream is a stream of progress updates

type PromptCacheControl

type PromptCacheControl struct {
	Type  string `json:"type"`
	Scope string `json:"scope,omitempty"`
	TTL   string `json:"ttl,omitempty"`
}

PromptCacheControl represents prompt caching metadata for a prompt block.

func CacheControlEphemeral

func CacheControlEphemeral() *PromptCacheControl

CacheControlEphemeral creates a cache-control with default 5min TTL. This is used for content that changes frequently.

func CacheControlWithTTL

func CacheControlWithTTL() *PromptCacheControl

CacheControlWithTTL creates a cache-control with 1h TTL (longer cache). This is typically used for stable content that won't change across turns.

func NewEphemeralPromptCacheControl

func NewEphemeralPromptCacheControl() *PromptCacheControl

NewEphemeralPromptCacheControl creates the minimal cache-control payload used by Anthropic-compatible prompt caching.

func NewPromptCacheControl

func NewPromptCacheControl(ttl string) *PromptCacheControl

NewPromptCacheControl creates a cache-control payload with optional TTL. The TTL "1h" provides longer cache retention (5 min default without TTL). Use ShouldUse1hCacheTTL() to determine if the user is eligible for 1h TTL.

type PromptFn

type PromptFn func(ctx context.Context, request PromptRequest) (PromptResponse, error)

PromptFn is a function that can prompt the user

type PromptOption

type PromptOption struct {
	// Label is the human-readable label
	Label string `json:"label"`

	// Value is the value to return if selected
	Value any `json:"value"`

	// Description is an optional description
	Description string `json:"description,omitempty"`
}

PromptOption represents an option in a choice prompt

type PromptRequest

type PromptRequest struct {
	// Type is the type of prompt
	Type PromptType `json:"type"`

	// Message is the message to show the user
	Message string `json:"message"`

	// Options are the available options (for choice prompts)
	Options []PromptOption `json:"options,omitempty"`

	// Default is the default value
	Default any `json:"default,omitempty"`

	// Metadata contains additional information
	Metadata map[string]any `json:"metadata,omitempty"`
}

PromptRequest represents a request to prompt the user

type PromptResponse

type PromptResponse struct {
	// Value is the user's response
	Value any `json:"value"`

	// Cancelled indicates if the user cancelled
	Cancelled bool `json:"cancelled"`

	// Metadata contains additional information
	Metadata map[string]any `json:"metadata,omitempty"`
}

PromptResponse represents a response from the user

type PromptType

type PromptType string

PromptType represents the type of prompt

const (
	PromptTypeText    PromptType = "text"
	PromptTypeChoice  PromptType = "choice"
	PromptTypeConfirm PromptType = "confirm"
)

type RetryConfig

type RetryConfig struct {
	// MaxAttempts is the maximum number of attempts
	MaxAttempts int `json:"max_attempts"`

	// InitialBackoff is the initial backoff duration in milliseconds
	InitialBackoff int64 `json:"initial_backoff_ms"`

	// MaxBackoff is the maximum backoff duration in milliseconds
	MaxBackoff int64 `json:"max_backoff_ms"`

	// BackoffMultiplier multiplies the backoff after each attempt
	BackoffMultiplier float64 `json:"backoff_multiplier"`

	// RetryableErrors is a set of error codes that are retryable
	RetryableErrors map[ErrorCode]bool `json:"retryable_errors,omitempty"`
}

RetryConfig configures retry behavior for API requests

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a default retry configuration

type Role

type Role string

Role represents the role of a message sender

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleSystem    Role = "system"
)

type RuntimeEvent

type RuntimeEvent struct {
	Type RuntimeEventType `json:"type"`

	SessionID SessionID `json:"session_id,omitempty"`
	TurnID    TurnID    `json:"turn_id,omitempty"`

	// TurnNumber is 1-indexed for the active turn being processed.
	TurnNumber int `json:"turn_number,omitempty"`

	Timestamp time.Time `json:"timestamp,omitempty"`

	StopReason    string      `json:"stop_reason,omitempty"`
	ExecutionMode string      `json:"execution_mode,omitempty"`
	Usage         *TokenUsage `json:"usage,omitempty"`

	Chunk             *APIResponseChunk      `json:"chunk,omitempty"`
	ToolProgress      *ToolProgress          `json:"tool_progress,omitempty"`
	Browser           *BrowserRuntimeEvent   `json:"browser,omitempty"`
	PermissionRequest *ToolPermissionRequest `json:"permission_request,omitempty"`
	PromptRequest     *PromptRequest         `json:"prompt_request,omitempty"`
	PlanEvent         *PlanRuntimeEvent      `json:"plan_event,omitempty"`
	TaskEvent         *TaskRuntimeEvent      `json:"task_event,omitempty"`

	// AgentToolUseID is set when this event originates from a sub-agent.
	// It identifies the parent agent tool_use block that spawned the sub-agent.
	AgentToolUseID string `json:"agent_tool_use_id,omitempty"`

	// GoalEvent carries structured payload for goal.updated events.
	GoalEvent *GoalRuntimeEvent `json:"goal_event,omitempty"`

	// AgentEvent carries structured payload for multi-agent collab events.
	AgentEvent *AgentRuntimeEvent `json:"agent_event,omitempty"`

	Error string `json:"error,omitempty"`
}

RuntimeEvent is the structured event envelope emitted by the runtime.

type RuntimeEventType

type RuntimeEventType string

RuntimeEventType identifies a structured runtime event emitted during a turn.

const (
	RuntimeEventTypeTurnStarted            RuntimeEventType = "turn.started"
	RuntimeEventTypeTurnCompleted          RuntimeEventType = "turn.completed"
	RuntimeEventTypeTurnFailed             RuntimeEventType = "turn.failed"
	RuntimeEventTypeResponseChunk          RuntimeEventType = "response.chunk"
	RuntimeEventTypeToolProgress           RuntimeEventType = "tool.progress"
	RuntimeEventTypeBrowserSession         RuntimeEventType = "browser.session"
	RuntimeEventTypeBrowserAction          RuntimeEventType = "browser.action"
	RuntimeEventTypeBrowserPage            RuntimeEventType = "browser.page"
	RuntimeEventTypeBrowserSnapshot        RuntimeEventType = "browser.snapshot"
	RuntimeEventTypeBrowserScreenshot      RuntimeEventType = "browser.screenshot"
	RuntimeEventTypeToolPermissionRequired RuntimeEventType = "tool.permission_required"
	RuntimeEventTypePromptRequired         RuntimeEventType = "prompt.request"
	RuntimeEventTypePlanSubmitted          RuntimeEventType = "plan.submitted"
	RuntimeEventTypePlanStatusChanged      RuntimeEventType = "plan.status_changed"
	RuntimeEventTypeExecutionModeChanged   RuntimeEventType = "execution_mode.changed"
	RuntimeEventTypeTaskChanged            RuntimeEventType = "task.changed"

	// Goal events — mirrors Codex ThreadGoalUpdatedNotification / ThreadGoalUpdatedEvent.
	RuntimeEventTypeGoalUpdated RuntimeEventType = "goal.updated"

	// Multi-agent collab events — mirrors Codex CollabAgent* protocol events.
	RuntimeEventTypeAgentSpawnBegin       RuntimeEventType = "agent.spawn.begin"
	RuntimeEventTypeAgentSpawnEnd         RuntimeEventType = "agent.spawn.end"
	RuntimeEventTypeAgentWaitBegin        RuntimeEventType = "agent.wait.begin"
	RuntimeEventTypeAgentWaitEnd          RuntimeEventType = "agent.wait.end"
	RuntimeEventTypeAgentInteractionBegin RuntimeEventType = "agent.interaction.begin"
	RuntimeEventTypeAgentInteractionEnd   RuntimeEventType = "agent.interaction.end"
	RuntimeEventTypeAgentCloseBegin       RuntimeEventType = "agent.close.begin"
	RuntimeEventTypeAgentCloseEnd         RuntimeEventType = "agent.close.end"
)

type SafetyCheckResult

type SafetyCheckResult struct {
	// IsDangerous indicates the pattern is unsafe.
	IsDangerous bool `json:"is_dangerous"`

	// Reason explains why the pattern is dangerous.
	Reason string `json:"reason"`

	// CheckType identifies which safety check produced this result.
	CheckType string `json:"check_type"`
}

SafetyCheckResult is the outcome of a bypass-immune safety check.

type SafetyChecker

type SafetyChecker interface {
	// CheckSafety evaluates whether a tool use is unsafe regardless of permission mode.
	CheckSafety(toolName string, input map[string]any) SafetyCheckResult
}

SafetyChecker performs bypass-immune safety validation.

type SessionID

type SessionID string

SessionID uniquely identifies a session

func NewSessionID

func NewSessionID(id string) SessionID

NewSessionID creates a new session ID (wrapper for clarity)

func (SessionID) String

func (s SessionID) String() string

String returns the string representation

type SessionMetadata

type SessionMetadata struct {
	// ID is the unique session identifier
	ID SessionID `json:"id"`

	// Title is the human-readable session name (e.g. "untitled_session_1").
	// Generated once at creation; never reassigned automatically.
	Title string `json:"title,omitempty"`

	// Status is the current status
	Status SessionStatus `json:"status"`

	// CreatedAt is when the session was created
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt is when the session was last updated
	UpdatedAt time.Time `json:"updated_at"`

	// RootPath is the working directory for this session
	RootPath string `json:"root_path,omitempty"`

	// Model is the model being used
	Model string `json:"model,omitempty"`

	// TotalTurns is the total number of turns completed
	TotalTurns int `json:"total_turns"`

	// TotalTokens is the total tokens used across all turns
	TotalTokens int `json:"total_tokens"`

	// MaxTokens is the context window for the current model
	MaxTokens int `json:"max_tokens,omitempty"`

	// CompactCount tracks how many times we've compacted
	CompactCount int `json:"compact_count"`

	// LastCompactedAt tracks when we last compacted
	LastCompactedAt *time.Time `json:"last_compacted_at,omitempty"`

	// Additional metadata
	Additional map[string]any `json:"additional,omitempty"`

	// SchemaVersion is the schema version of this persisted metadata.
	// Zero means pre-versioning (treat as v0 / legacy).
	SchemaVersion int `json:"schema_version,omitempty"`
}

SessionMetadata contains metadata about a session

type SessionStatus

type SessionStatus string

SessionStatus represents the status of a session

const (
	SessionStatusActive    SessionStatus = "active"
	SessionStatusIdle      SessionStatus = "idle"
	SessionStatusInterrupt SessionStatus = "interrupted"
	SessionStatusClosed    SessionStatus = "closed"
)

type SetupData

type SetupData struct {
	SessionID      string `json:"session_id"`
	InitialMessage string `json:"initial_message,omitempty"`
}

SetupData contains data for setup events

type StopFailureData

type StopFailureData struct {
	Reason string `json:"reason"`
	Error  error  `json:"error,omitempty"`
}

StopFailureData contains data for stop failure events

type StreamToolOutput

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

StreamToolOutput is a streaming implementation of ToolOutput

func NewStreamToolOutput

func NewStreamToolOutput(data []byte) StreamToolOutput

NewStreamToolOutput creates a new StreamToolOutput

func (StreamToolOutput) Bytes

func (s StreamToolOutput) Bytes() []byte

Bytes implements ToolOutput

func (StreamToolOutput) Reader

func (s StreamToolOutput) Reader() io.Reader

Reader implements ToolOutput

func (StreamToolOutput) String

func (s StreamToolOutput) String() string

String implements ToolOutput

type SubagentData

type SubagentData struct {
	AgentID   string `json:"agent_id"`
	AgentName string `json:"agent_name"`
	ParentID  string `json:"parent_id,omitempty"`
	TaskType  string `json:"task_type,omitempty"`
	IsFork    bool   `json:"is_fork"`
}

SubagentData contains data for subagent events

type SystemPromptBlock

type SystemPromptBlock struct {
	Type         string              `json:"type"`
	Text         string              `json:"text"`
	CacheControl *PromptCacheControl `json:"cache_control,omitempty"`
}

SystemPromptBlock is a provider-facing prompt block.

func NewTextSystemPromptBlock

func NewTextSystemPromptBlock(text string, cacheControl *PromptCacheControl) SystemPromptBlock

NewTextSystemPromptBlock creates a canonical text block.

type TaskData

type TaskData struct {
	TaskID   string `json:"task_id"`
	TaskType string `json:"task_type"`
	TaskName string `json:"task_name"`
	Status   string `json:"status"`
	Result   any    `json:"result,omitempty"`
	Error    error  `json:"error,omitempty"`
}

TaskData contains data for task events

type TaskRuntimeEvent

type TaskRuntimeEvent struct {
	TaskID  string `json:"task_id"`
	Action  string `json:"action"`
	Status  string `json:"status,omitempty"`
	Subject string `json:"subject,omitempty"`
}

type TextContent

type TextContent struct {
	Text string `json:"text"`
}

TextContent represents a text content block

func (TextContent) ContentType

func (TextContent) ContentType() ContentType

type ThinkingContent

type ThinkingContent struct {
	Thinking string `json:"thinking"`
}

ThinkingContent represents a thinking content block (extended thinking)

func (ThinkingContent) ContentType

func (ThinkingContent) ContentType() ContentType

type TokenUsage

type TokenUsage struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`

	// CachedTokens represents tokens served from cache (OpenAI style).
	CachedTokens int `json:"cached_tokens,omitempty"`

	// CacheReadInputTokens is the number of tokens read from the Anthropic
	// prompt cache (served at reduced cost). Set by Anthropic responses.
	CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`

	// CacheCreationInputTokens is the number of tokens written into the
	// Anthropic prompt cache (billed at a 25% premium on first write).
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
}

TokenUsage represents token usage information

type ToolOutput

type ToolOutput interface {
	// Bytes returns the output as bytes
	Bytes() []byte

	// String returns the output as a string
	String() string

	// Reader returns a reader for the output
	Reader() io.Reader
}

ToolOutput represents the output of a tool that can be streamed

type ToolPermissionIntent

type ToolPermissionIntent string

ToolPermissionIntent identifies what kind of decision is being requested.

const (
	ToolPermissionIntentCheck ToolPermissionIntent = "check"
	ToolPermissionIntentDeny  ToolPermissionIntent = "deny"
	ToolPermissionIntentAsk   ToolPermissionIntent = "ask"
	ToolPermissionIntentAllow ToolPermissionIntent = "allow"
)

type ToolPermissionRequest

type ToolPermissionRequest struct {
	// ToolName is the name of the tool being checked.
	ToolName string `json:"tool_name"`

	// Description is a human-readable explanation for the approval UI.
	Description string `json:"description,omitempty"`

	// ToolInput is the candidate tool input.
	ToolInput map[string]any `json:"tool_input"`

	// ToolUseID identifies the tool use when available.
	ToolUseID string `json:"tool_use_id,omitempty"`

	// SessionID identifies the session when available.
	SessionID SessionID `json:"session_id,omitempty"`

	// TurnID identifies the turn when available.
	TurnID TurnID `json:"turn_id,omitempty"`

	// PermissionMode is the active permission mode.
	PermissionMode PermissionMode `json:"permission_mode,omitempty"`

	// WorkingDirectory is the working directory visible to the tool runtime.
	WorkingDirectory string `json:"working_directory,omitempty"`

	// IsToolRunningInSandbox indicates whether the tool will run inside a sandbox.
	// Used for sandbox auto-allow logic.
	IsToolRunningInSandbox bool `json:"is_tool_running_in_sandbox,omitempty"`

	// Stage identifies which permission stage is being resolved.
	Stage ToolPermissionStage `json:"stage,omitempty"`

	// Intent identifies the decision kind requested for the stage.
	Intent ToolPermissionIntent `json:"intent,omitempty"`

	// Metadata carries optional runtime metadata.
	Metadata map[string]any `json:"metadata,omitempty"`
}

ToolPermissionRequest represents a structured permission check request.

func GlobalToolPermissionRequest

func GlobalToolPermissionRequest(
	toolName string,
	toolInput map[string]any,
	toolUseID string,
	sessionID SessionID,
	turnID TurnID,
	mode PermissionMode,
	workingDirectory string,
	metadata map[string]any,
) ToolPermissionRequest

GlobalToolPermissionRequest builds a full-input global permission request.

func WholeToolPermissionRequest

func WholeToolPermissionRequest(
	toolName string,
	toolUseID string,
	sessionID SessionID,
	turnID TurnID,
	mode PermissionMode,
	workingDirectory string,
	intent ToolPermissionIntent,
	metadata map[string]any,
) ToolPermissionRequest

WholeToolPermissionRequest builds a whole-tool permission request for a specific stage.

type ToolPermissionStage

type ToolPermissionStage string

ToolPermissionStage identifies which permission stage is being resolved.

const (
	ToolPermissionStageWholeTool ToolPermissionStage = "whole_tool"
	ToolPermissionStageGlobal    ToolPermissionStage = "global"
)

type ToolProgress

type ToolProgress struct {
	// ToolName is the name of the tool
	ToolName string `json:"tool_name,omitempty"`

	// ToolUseID identifies the concrete tool call instance when available.
	ToolUseID string `json:"tool_use_id,omitempty"`

	// Stage indicates the current stage
	Stage ToolProgressStage `json:"stage"`

	// Message is a human-readable progress message
	Message string `json:"message,omitempty"`

	// PercentComplete is 0-100
	PercentComplete float64 `json:"percent_complete,omitempty"`

	// Metadata contains additional progress information
	Metadata map[string]any `json:"metadata,omitempty"`
}

ToolProgress represents progress updates for a tool execution

type ToolProgressStage

type ToolProgressStage string

ToolProgressStage represents the stage of tool execution

const (
	ToolProgressStagePending   ToolProgressStage = "pending"
	ToolProgressStageRunning   ToolProgressStage = "running"
	ToolProgressStageCompleted ToolProgressStage = "completed"
	ToolProgressStageFailed    ToolProgressStage = "failed"
)

type ToolResult

type ToolResult struct {
	// Data contains the result data
	// The specific type depends on the tool
	Data any `json:"data"`

	// Error contains any error that occurred
	Error error `json:"error,omitempty"`

	// Metadata contains additional result information
	Metadata *ToolResultMetadata `json:"metadata,omitempty"`
}

ToolResult represents the result of a tool execution

type ToolResultContent

type ToolResultContent struct {
	ToolUseID string          `json:"tool_use_id"`
	Content   string          `json:"content"`
	IsError   bool            `json:"is_error,omitempty"`
	Metadata  *map[string]any `json:"metadata,omitempty"`
}

ToolResultContent represents a tool result content block

func (ToolResultContent) ContentType

func (ToolResultContent) ContentType() ContentType

type ToolResultMetadata

type ToolResultMetadata struct {
	// ContentReplacement indicates the result was too large and replaced
	ContentReplacement *ContentReplacementState `json:"content_replacement,omitempty"`

	// ExecutionDuration is how long the tool took to run
	ExecutionDuration int64 `json:"execution_duration_ms,omitempty"`

	// Additional metadata
	Additional map[string]any `json:"additional,omitempty"`
}

ToolResultMetadata contains metadata about a tool result

type ToolUseContent

type ToolUseContent struct {
	ID       string          `json:"id"`
	Name     string          `json:"name"`
	Input    map[string]any  `json:"input"`
	Metadata *map[string]any `json:"metadata,omitempty"`
}

ToolUseContent represents a tool use content block

func (ToolUseContent) ContentType

func (ToolUseContent) ContentType() ContentType

type TranscriptEntry

type TranscriptEntry struct {
	// ID uniquely identifies this entry
	ID MessageID `json:"id"`

	// Type is the type of entry
	Type EntryType `json:"type"`

	// Role is the message role (for message entries)
	Role Role `json:"role,omitempty"`

	// Content is the message content (for message entries)
	Content []ContentBlock `json:"content,omitempty"`

	// Timestamp is when this entry was created
	Timestamp time.Time `json:"timestamp"`

	// TurnID indicates which turn this belongs to
	TurnID TurnID `json:"turn_id,omitempty"`

	// Metadata contains additional information
	Metadata map[string]any `json:"metadata,omitempty"`
}

TranscriptEntry represents a single entry in the transcript

func CanonicalTranscriptEntriesFromMessages

func CanonicalTranscriptEntriesFromMessages(messages []Message, turnID TurnID) []TranscriptEntry

func FilterCanonicalTranscriptEntries

func FilterCanonicalTranscriptEntries(entries []TranscriptEntry) []TranscriptEntry

func TranscriptEntriesFromMessages

func TranscriptEntriesFromMessages(messages []Message, turnID TurnID) []TranscriptEntry

func TranscriptEntryFromMessage

func TranscriptEntryFromMessage(message Message, turnID TurnID) TranscriptEntry

func (TranscriptEntry) MarshalJSON

func (t TranscriptEntry) MarshalJSON() ([]byte, error)

func (*TranscriptEntry) UnmarshalJSON

func (t *TranscriptEntry) UnmarshalJSON(data []byte) error

type TurnID

type TurnID string

TurnID uniquely identifies a turn within a session

func NewTurnID

func NewTurnID(id string) TurnID

NewTurnID creates a new turn ID (wrapper for clarity)

func (TurnID) String

func (t TurnID) String() string

String returns the string representation

type TurnMetadata

type TurnMetadata struct {
	// TurnID is the unique turn identifier
	TurnID TurnID `json:"turn_id"`

	// SessionID is the parent session
	SessionID SessionID `json:"session_id"`

	// TurnNumber is the sequential turn number (1-indexed)
	TurnNumber int `json:"turn_number"`

	// StartedAt is when the turn started
	StartedAt time.Time `json:"started_at"`

	// CompletedAt is when the turn completed
	CompletedAt *time.Time `json:"completed_at,omitempty"`

	// StopReason is why the turn stopped
	StopReason string `json:"stop_reason,omitempty"`

	// ToolUses is the number of tools used in this turn
	ToolUses int `json:"tool_uses,omitempty"`

	// InputTokens is the tokens used for input
	InputTokens int `json:"input_tokens"`

	// OutputTokens is the tokens used for output
	OutputTokens int `json:"output_tokens"`

	// IsCompacted indicates if this turn was after a compaction
	IsCompacted bool `json:"is_compacted"`

	// Additional metadata
	Additional map[string]any `json:"additional,omitempty"`
}

TurnMetadata contains metadata about a turn

type UserPromptSubmitData

type UserPromptSubmitData struct {
	Prompt         string `json:"prompt"`
	SessionID      string `json:"session_id"`
	IsFirstMessage bool   `json:"is_first_message"`
}

UserPromptSubmitData contains data for user prompt submission

type WorktreeData

type WorktreeData struct {
	WorktreePath string `json:"worktree_path"`
	BaseBranch   string `json:"base_branch,omitempty"`
}

WorktreeData contains data for worktree events

Jump to

Keyboard shortcuts

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