protocol

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: GPL-3.0 Imports: 9 Imported by: 0

Documentation

Overview

Package protocol defines the versioned, presentation-independent event vocabulary exchanged by the session engine, capability runtime, transcript, and user-surface adapters.

Index

Constants

View Source
const CurrentVersion = 1

CurrentVersion is the canonical event schema version emitted by this build.

Variables

This section is empty.

Functions

func ValidatePromptID

func ValidatePromptID(value string) error

ValidatePromptID validates a host-supplied idempotency key before it can be retained in the session ledger. Prompt identifiers intentionally use the same bounded, whitespace-free wire shape as the other correlation IDs.

Types

type CancellationEvent

type CancellationEvent struct {
	Scope    string `json:"scope"`
	TargetID string `json:"target_id,omitempty"`
	State    string `json:"state"` // requested, acknowledged, completed
	Reason   string `json:"reason,omitempty"`
}

func (CancellationEvent) Validate

func (c CancellationEvent) Validate() error

type CompactionEvent

type CompactionEvent struct {
	Trigger       string   `json:"trigger"` // manual or auto
	State         string   `json:"state"`   // started, completed, failed
	PreTokens     int      `json:"pre_tokens"`
	SummaryID     *EventID `json:"summary_id,omitempty"`
	PreservedHead *EventID `json:"preserved_head,omitempty"`
	Anchor        *EventID `json:"anchor,omitempty"`
	PreservedTail *EventID `json:"preserved_tail,omitempty"`
}

func (CompactionEvent) Validate

func (c CompactionEvent) Validate() error

type ConnectionEvent

type ConnectionEvent struct {
	Provider   string `json:"provider"`
	Name       string `json:"name"`
	State      string `json:"state"`
	Generation uint64 `json:"generation,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

func (ConnectionEvent) Validate

func (c ConnectionEvent) Validate() error

type ContentBlock

type ContentBlock struct {
	Type     ContentType `json:"type"`
	Text     string      `json:"text,omitempty"`
	Name     string      `json:"name,omitempty"`
	MIMEType string      `json:"mime_type,omitempty"`
	URI      string      `json:"uri,omitempty"`
}

ContentBlock carries either text/reasoning or attachment metadata. Binary attachment bytes live in the owning file-transfer subsystem, not JSONL.

func TextBlock

func TextBlock(text string) ContentBlock

TextBlock constructs a plain text block.

func (ContentBlock) Validate

func (b ContentBlock) Validate() error

Validate checks the content-block discriminator and required fields.

type ContentType

type ContentType string

ContentType discriminates a message or tool-result content block.

const (
	ContentText       ContentType = "text"
	ContentReasoning  ContentType = "reasoning"
	ContentAttachment ContentType = "attachment"
)

type DiagnosticEvent

type DiagnosticEvent struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

DiagnosticEvent carries a bounded classification without raw prompt, source, command, path, credentials, or arbitrary external response bodies.

func (DiagnosticEvent) Validate

func (d DiagnosticEvent) Validate() error

Validate checks a bounded, already-sanitized diagnostic.

type ErrorInfo

type ErrorInfo struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

ErrorInfo is a bounded semantic error classification. Message is intended for the user/model and must already be secret-safe at the producing boundary.

func (ErrorInfo) Validate

func (e ErrorInfo) Validate() error

Validate checks bounded error classification fields.

type Event

type Event struct {
	Version         int             `json:"version"`
	ID              EventID         `json:"id"`
	SessionID       SessionID       `json:"session_id"`
	TurnID          TurnID          `json:"turn_id,omitempty"`
	ParentID        *EventID        `json:"parent_id"`
	LogicalParentID *EventID        `json:"logical_parent_id,omitempty"`
	Sequence        uint64          `json:"sequence"`
	Timestamp       time.Time       `json:"timestamp"`
	Kind            EventKind       `json:"kind"`
	Visibility      Visibility      `json:"visibility"`
	Persistence     Persistence     `json:"persistence"`
	Origin          Origin          `json:"origin"`
	Session         SessionMetadata `json:"session"`
	Sidechain       bool            `json:"sidechain,omitempty"`
	AgentName       string          `json:"agent_name,omitempty"`
	AgentID         string          `json:"agent_id,omitempty"`

	Message      *Message           `json:"message,omitempty"`
	ToolCall     *ToolCall          `json:"tool_call,omitempty"`
	ToolResult   *ToolResult        `json:"tool_result,omitempty"`
	Metadata     *MetadataEvent     `json:"metadata,omitempty"`
	Usage        *Usage             `json:"usage,omitempty"`
	TurnResult   *TurnResult        `json:"turn_result,omitempty"`
	Progress     *ProgressEvent     `json:"progress,omitempty"`
	Diagnostic   *DiagnosticEvent   `json:"diagnostic,omitempty"`
	Permission   *PermissionEvent   `json:"permission,omitempty"`
	Task         *TaskEvent         `json:"task,omitempty"`
	Retry        *RetryEvent        `json:"retry,omitempty"`
	Connection   *ConnectionEvent   `json:"connection,omitempty"`
	Hook         *HookEvent         `json:"hook,omitempty"`
	Compaction   *CompactionEvent   `json:"compaction,omitempty"`
	Cancellation *CancellationEvent `json:"cancellation,omitempty"`
	LocalCommand *LocalCommandEvent `json:"local_command,omitempty"`
}

Event is the canonical semantic envelope. ParentID captures the persisted graph edge; LogicalParentID preserves provenance when a compaction or branch deliberately starts a new physical root.

Exactly one payload pointer must be non-nil and must match Kind. Unknown JSON fields are ignored by encoding/json for forward compatibility, but an unknown version or discriminator is rejected by Validate.

func NewBaseEvent

func NewBaseEvent(sessionID SessionID, turnID TurnID, kind EventKind) (Event, error)

NewBaseEvent initializes the common envelope. Callers must attach the payload selected by kind before validation or publication.

func NewMessageEvent

func NewMessageEvent(sessionID SessionID, turnID TurnID, role Role, content ...ContentBlock) (Event, error)

NewMessageEvent constructs and validates a durable semantic message event.

func NewToolCallEvent

func NewToolCallEvent(sessionID SessionID, turnID TurnID, call ToolCall) (Event, error)

NewToolCallEvent constructs and validates a durable accepted tool call. If call.ID is empty a cryptographically random ID is assigned.

func NewToolResultEvent

func NewToolResultEvent(sessionID SessionID, turnID TurnID, result ToolResult) (Event, error)

NewToolResultEvent constructs and validates a durable terminal tool result.

func (Event) Validate

func (e Event) Validate() error

Validate checks the semantic envelope. Sequence zero is accepted for a new event because the transcript owner assigns durable order atomically.

func (Event) ValidateStored

func (e Event) ValidateStored() error

ValidateStored additionally requires the monotonic sequence assigned by a durable transcript. Ephemeral events are valid with sequence zero.

type EventID

type EventID string

EventID identifies one canonical event. It is distinct from provider message and tool-use identifiers because conflating them breaks replay deduplication.

func NewEventID

func NewEventID() (EventID, error)

NewEventID creates a cryptographically random canonical event identifier.

type EventKind

type EventKind string

EventKind selects the single payload carried by an Event.

const (
	EventKindMessage         EventKind = "message"
	EventKindToolCall        EventKind = "tool_call"
	EventKindToolResult      EventKind = "tool_result"
	EventKindSessionMetadata EventKind = "session_metadata"
	EventKindUsage           EventKind = "usage"
	EventKindTurnResult      EventKind = "turn_result"
	EventKindProgress        EventKind = "progress"
	EventKindDiagnostic      EventKind = "diagnostic"
	EventKindPermission      EventKind = "permission"
	EventKindTaskLifecycle   EventKind = "task_lifecycle"
	EventKindRetry           EventKind = "retry"
	EventKindConnection      EventKind = "connection"
	EventKindHookLifecycle   EventKind = "hook_lifecycle"
	EventKindCompaction      EventKind = "compaction"
	EventKindCancellation    EventKind = "cancellation"
	EventKindLocalCommand    EventKind = "local_command"
)

type HookEvent

type HookEvent struct {
	HookID   string `json:"hook_id"`
	Name     string `json:"name"`
	Event    string `json:"event"`
	State    string `json:"state"` // started, progress, success, error, cancelled
	Output   string `json:"output,omitempty"`
	ExitCode *int   `json:"exit_code,omitempty"`
}

func (HookEvent) Validate

func (h HookEvent) Validate() error

type LocalCommandEvent

type LocalCommandEvent struct {
	Command string `json:"command"`
	Status  string `json:"status"`
	Output  string `json:"output,omitempty"`
}

func (LocalCommandEvent) Validate

func (c LocalCommandEvent) Validate() error

type Message

type Message struct {
	Role          Role           `json:"role"`
	Content       []ContentBlock `json:"content"`
	APIMessageID  string         `json:"api_message_id,omitempty"`
	APIResponseID string         `json:"api_response_id,omitempty"`
	Phase         string         `json:"phase,omitempty"`
	PromptID      string         `json:"prompt_id,omitempty"`
	Synthetic     bool           `json:"synthetic,omitempty"`
}

Message contains provider-independent semantic content. APIMessageID is optional provider correlation and never substitutes for the canonical event identifier.

func (Message) Validate

func (m Message) Validate() error

Validate checks message role and block-level union constraints.

type MessageID

type MessageID = identity.MessageID

Identifier aliases retain distinct compile-time domains while allowing protocol consumers to use one import for the common wire vocabulary.

type MetadataEvent

type MetadataEvent struct {
	Key   string          `json:"key"`
	Value json.RawMessage `json:"value"`
}

MetadataEvent represents append/last-wins session metadata without giving it model visibility. Value must be valid JSON and its key is a stable namespace.

func (MetadataEvent) Validate

func (m MetadataEvent) Validate() error

Validate checks append metadata syntax without interpreting its owner-specific schema.

type Origin

type Origin string

Origin describes the authority that produced an event. It is intentionally bounded so it is safe for diagnostics and low-cardinality metrics.

const (
	OriginUser       Origin = "user"
	OriginModel      Origin = "model"
	OriginCapability Origin = "capability"
	OriginRuntime    Origin = "runtime"
	OriginRecovery   Origin = "recovery"
)

type PermissionEvent

type PermissionEvent struct {
	RequestID RequestID `json:"request_id"`
	ToolUseID ToolUseID `json:"tool_use_id"`
	ToolName  string    `json:"tool_name"`
	Stage     string    `json:"stage"` // requested or decided
	Decision  string    `json:"decision,omitempty"`
	Reason    string    `json:"reason,omitempty"`
}

PermissionEvent carries both halves of an authorization exchange through the same semantic bus used by every surface. Input is deliberately omitted: the accepted ToolCall already owns it and diagnostics must not duplicate potentially sensitive arguments.

func (PermissionEvent) Validate

func (p PermissionEvent) Validate() error

type Persistence

type Persistence string

Persistence declares whether an event is authoritative history or derived, replaceable process state. Transcript stores must never write Ephemeral data.

const (
	PersistenceDurable   Persistence = "durable"
	PersistenceEphemeral Persistence = "ephemeral"
)

type ProgressEvent

type ProgressEvent struct {
	Phase         string    `json:"phase"`
	Message       string    `json:"message,omitempty"`
	ToolUseID     ToolUseID `json:"tool_use_id,omitempty"`
	ElapsedMillis int64     `json:"elapsed_millis,omitempty"`
}

ProgressEvent is presentation-only and therefore must be ephemeral.

func (ProgressEvent) Validate

func (p ProgressEvent) Validate() error

Validate checks bounded progress fields.

type RequestID

type RequestID = identity.RequestID

Identifier aliases retain distinct compile-time domains while allowing protocol consumers to use one import for the common wire vocabulary.

type RetryEvent

type RetryEvent struct {
	Attempt     int    `json:"attempt"`
	MaxAttempts int    `json:"max_attempts"`
	DelayMillis int64  `json:"delay_millis"`
	HTTPStatus  int    `json:"http_status,omitempty"`
	Category    string `json:"category"`
}

func (RetryEvent) Validate

func (r RetryEvent) Validate() error

type Role

type Role string

Role is a model-conversation role. Capability outputs use ToolResult events rather than overloading a user Message with provider-specific wire details.

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

type SessionID

type SessionID = identity.SessionID

Identifier aliases retain distinct compile-time domains while allowing protocol consumers to use one import for the common wire vocabulary.

type SessionMetadata

type SessionMetadata struct {
	ParentSessionID     SessionID `json:"parent_session_id,omitempty"`
	WorkingDirectory    string    `json:"working_directory,omitempty"`
	Entrypoint          string    `json:"entrypoint,omitempty"`
	Surface             string    `json:"surface,omitempty"`
	UserType            string    `json:"user_type,omitempty"`
	ProductVersion      string    `json:"product_version,omitempty"`
	SourceControlBranch string    `json:"source_control_branch,omitempty"`
	PlanSlug            string    `json:"plan_slug,omitempty"`
}

SessionMetadata is repeated on durable records so copied or forked events can be restamped with destination ownership. It contains no credentials.

type TaskEvent

type TaskEvent struct {
	TaskID      TaskID `json:"task_id"`
	Stage       string `json:"stage"` // started, progress, notification
	Status      string `json:"status,omitempty"`
	Description string `json:"description,omitempty"`
	OutputPath  string `json:"output_path,omitempty"`
}

TaskEvent is the canonical lifecycle projection for finite asynchronous work. The task store remains authoritative for complete task records.

func (TaskEvent) Validate

func (t TaskEvent) Validate() error

type TaskID

type TaskID = identity.TaskID

Identifier aliases retain distinct compile-time domains while allowing protocol consumers to use one import for the common wire vocabulary.

type ToolCall

type ToolCall struct {
	ID            ToolUseID       `json:"id"`
	Name          string          `json:"name"`
	Arguments     json.RawMessage `json:"arguments,omitempty"`
	RawArguments  *string         `json:"raw_arguments,omitempty"`
	APIResponseID string          `json:"api_response_id,omitempty"`
}

ToolCall records an accepted model request before tool-schema validation. Exactly one argument representation is present: Arguments for an already validated object, or RawArguments for the provider string preserved exactly even when it is empty or malformed. This lets every accepted provider call ID receive a terminal malformed result instead of disappearing during parsing.

func NewRawToolCall

func NewRawToolCall(id ToolUseID, name, rawArguments string) ToolCall

NewRawToolCall preserves an untrusted provider argument string for later structural and tool-schema validation.

func (ToolCall) ParseArguments

func (c ToolCall) ParseArguments() (json.RawMessage, error)

ParseArguments performs the structural validation deliberately deferred for provider-originated calls. The returned bytes are an independent copy.

func (ToolCall) Validate

func (c ToolCall) Validate() error

Validate checks tool identity, name, and the argument-representation union. RawArguments deliberately remains unparsed at acceptance time.

type ToolResult

type ToolResult struct {
	ToolUseID      ToolUseID        `json:"tool_use_id"`
	ToolName       string           `json:"tool_name"`
	Status         ToolResultStatus `json:"status"`
	Content        []ContentBlock   `json:"content"`
	IsError        bool             `json:"is_error"`
	DurationMillis int64            `json:"duration_millis,omitempty"`
	Error          *ErrorInfo       `json:"error,omitempty"`
	Synthetic      bool             `json:"synthetic,omitempty"`
}

ToolResult settles exactly one accepted ToolCall ID.

func (ToolResult) Validate

func (r ToolResult) Validate() error

Validate checks that a ToolResult is terminal and error classification agrees with status. Every non-success terminal outcome is model-visible as an error.

type ToolResultStatus

type ToolResultStatus string

ToolResultStatus is terminal. There is deliberately no pending/running value in the result union; progress is a separate ephemeral event.

const (
	ToolResultSuccess     ToolResultStatus = "success"
	ToolResultError       ToolResultStatus = "error"
	ToolResultDenied      ToolResultStatus = "denied"
	ToolResultCancelled   ToolResultStatus = "cancelled"
	ToolResultTimedOut    ToolResultStatus = "timed_out"
	ToolResultInterrupted ToolResultStatus = "interrupted"
	ToolResultUnavailable ToolResultStatus = "unavailable"
	ToolResultMalformed   ToolResultStatus = "malformed"
)

type ToolUseID

type ToolUseID = identity.ToolUseID

Identifier aliases retain distinct compile-time domains while allowing protocol consumers to use one import for the common wire vocabulary.

func NewToolUseID

func NewToolUseID() (ToolUseID, error)

NewToolUseID creates a cryptographically random model-tool correlation ID.

type TurnID

type TurnID = identity.TurnID

Identifier aliases retain distinct compile-time domains while allowing protocol consumers to use one import for the common wire vocabulary.

type TurnResult

type TurnResult struct {
	Status         TurnResultStatus `json:"status"`
	IsError        bool             `json:"is_error"`
	StopReason     string           `json:"stop_reason,omitempty"`
	Message        string           `json:"message,omitempty"`
	Turns          int              `json:"turns"`
	DurationMillis int64            `json:"duration_millis"`
}

TurnResult records terminal turn semantics and bounded accounting.

func (TurnResult) Validate

func (r TurnResult) Validate() error

Validate checks turn-result terminal state and accounting.

type TurnResultStatus

type TurnResultStatus string

TurnResultStatus names terminal turn outcomes independent of presentation.

const (
	TurnResultSuccess   TurnResultStatus = "success"
	TurnResultError     TurnResultStatus = "error"
	TurnResultCancelled TurnResultStatus = "cancelled"
	TurnResultMaxTurns  TurnResultStatus = "max_turns"
	TurnResultMaxBudget TurnResultStatus = "max_budget"
)

type Usage

type Usage struct {
	Model             string   `json:"model"`
	InputTokens       int64    `json:"input_tokens"`
	CachedInputTokens int64    `json:"cached_input_tokens"`
	OutputTokens      int64    `json:"output_tokens"`
	ReasoningTokens   int64    `json:"reasoning_tokens"`
	TotalTokens       int64    `json:"total_tokens"`
	CostUSD           *float64 `json:"cost_usd,omitempty"`
}

Usage is a completed provider-call accounting snapshot. Exporters consume a copy; the session state remains authoritative for aggregate budget decisions.

func (Usage) Validate

func (u Usage) Validate() error

Validate checks nonnegative completed usage values and optional cost.

type Visibility

type Visibility string

Visibility describes which semantic projections may consume an event. It is independent of persistence: a recovered tool result can be model-visible but deliberately ephemeral, while internal metadata can be durable but hidden.

const (
	VisibilityUser     Visibility = "user"
	VisibilityModel    Visibility = "model"
	VisibilityBoth     Visibility = "both"
	VisibilityInternal Visibility = "internal"
)

func (Visibility) ModelVisible

func (v Visibility) ModelVisible() bool

ModelVisible reports whether the event belongs in a provider request projection. Presentation-only progress and internal metadata return false.

func (Visibility) UserVisible

func (v Visibility) UserVisible() bool

UserVisible reports whether a presentation adapter may show the event.

Jump to

Keyboard shortcuts

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