events

package
v0.32.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 2 Imported by: 1

Documentation

Overview

Package events defines the typed payload structs that flow over the engine bus. Plugins import these types directly; the engine serializes them to the journal as JSON; out-of-tree consumers (replay tools, dashboards, MCP servers) read those journals.

Schema versioning

Each top-level payload struct carries an `_schema_version` JSON field (the `SchemaVersion int` Go field) and a sibling `<Name>Version` constant declaring the running code's version of that payload. Producers stamp `SchemaVersion = <Name>Version` at emit time so the journal records which contract the payload was written under.

Versions start at 1 — Nexus is a fresh project with no historical drift to encode. Field-level compatibility migrations between versions live in the sibling pkg/events/compat package; the empty registry today is the scaffold journal-replay code calls into when a future PR ships v2.

The v0 == v1 deserialization rule

When a journal record (or a third-party producer) leaves out the `_schema_version` field, JSON deserializes it to Go's zero value: 0. Consumers MUST treat 0 as v1 — i.e., the current contract — rather than reject the payload. This keeps journals written before the field existed replayable, and keeps producers that haven't been updated yet (e.g. an embedder still on the previous Nexus minor) interoperable during the transition window.

The rule is implicit while v1 is the only shipped version: nothing special happens during unmarshal. When a v2 ships, the compat package gains a `{Type, From: 0, To: 1}` migrator that is a no-op pass-through plus the real `{Type, From: 1, To: 2}` migrator chained after it. Apply is the entry point.

Shipped versions above 1

Most payloads are still at v1. The ones that have moved, and why:

  • io.input / UserInput — v2 added PreloadMessages, v3 added Headers.
  • llm.request / LLMRequest — v2 added Overrides, the carrier for the `core.models` chain entry a request is actually being served by (native provider blocks plus the API-surface selector). Both directions are compatible: a v1 payload parses into the v2 struct with every axis unset, and a v1 consumer ignores the extra object.

Each of those additions is an optional field, so neither needed a compat migrator — see the mutation rules below.

Consumer-side pinning

Versions returns the whole manifest — payload struct name to its `<Name>Version` constant — so an embedder pinned to a released Nexus can name the payloads it reads in one table test and get a single failure listing every one that moved on a pin bump. `make check-events` is the producer-side guard; it diffs git revisions and cannot run from a module cache. Versions is the fact a consumer asserts against.

A version pin is NOT a complete guard. An additive field is not required to bump the version and usually does not (see below; the io.input and llm.request bumps above were the author's choice, not the rule), so a payload can gain a field a consumer ought to start reading while its version stays put. A consumer that must react to new fields reads the release notes (the GitHub Release for each tag) for the payloads it pins; the version only signals a breaking change.

Adding a new event type

  1. Define the struct in the appropriate per-domain file (core.go, llm.go, agent.go, …) with a SchemaVersion int field tagged `json:"_schema_version"` as the first declared field.
  2. Add a <Name>Version = 1 constant alongside the struct.
  3. List it in the versions manifest in versions.go (what Versions returns); TestVersionsManifestCoversEveryConstant fails until you do.
  4. Producers must stamp `SchemaVersion = <Name>Version` on every literal they emit. The `make check-events` lint rule catches mutations to existing structs that forget to bump the constant; net-new structs are not lint-enforced (no diff).

Mutating an existing event type

  • Adding a field with a sensible zero value is forward-compatible — bump the version constant only when consumers must distinguish pre/post-add records (e.g., to reject empty defaults from old producers). The lint check accepts additive-only diffs without a bump.
  • Removing or renaming a field is a breaking change — bump the constant and register a compat migrator. The lint check fails the PR if you forget.
  • Changing a field's type is a breaking change — same as remove/rename.

Index

Constants

View Source
const (
	TurnInfoVersion          = 1
	PlanVersion              = 1
	SubagentSpawnVersion     = 1
	SubagentStartedVersion   = 1
	SubagentIterationVersion = 1
	AgentToolChoiceVersion   = 1
	SubagentCompleteVersion  = 1
)

Schema-version constants for agent.* payloads. See doc.go.

View Source
const (
	CancelRequestVersion  = 1
	CancelActiveVersion   = 1
	CancelCompleteVersion = 1
	CancelResumeVersion   = 1
)

Schema-version constants for cancel.* payloads. See doc.go.

View Source
const (
	RetrievalContextVersion = 1
	CitedResponseVersion    = 1
)

Schema-version constants for citations.* payloads. See doc.go.

View Source
const (
	CodeExecRequestVersion = 1
	CodeExecStdoutVersion  = 1
	CodeExecResultVersion  = 1
)

Schema-version constants for code.* payloads. See doc.go.

View Source
const (
	BootConfigVersion          = 1
	ShutdownReasonVersion      = 1
	ErrorInfoVersion           = 1
	TickInfoVersion            = 1
	ConfigReloadRequestVersion = 1
	ConfigReloadResultVersion  = 1
)

Schema-version constants for core.* payloads. See doc.go for the versioning convention.

View Source
const (
	HITLRequestVersion  = 1
	HITLResponseVersion = 1
	HITLCancelVersion   = 1
)

Schema-version constants for hitl.* payloads. See doc.go.

View Source
const (
	UserInputVersion        = 3
	AgentOutputVersion      = 1
	OutputChunkVersion      = 1
	StreamRefVersion        = 1
	StatusUpdateVersion     = 1
	ApprovalRequestVersion  = 1
	ApprovalResponseVersion = 1
	HistoryReplayVersion    = 1
	SessionInfoVersion      = 1
)

Schema-version constants for io.* payloads. See doc.go.

View Source
const (
	LexicalUpsertVersion        = 1
	LexicalQueryVersion         = 1
	LexicalDeleteVersion        = 1
	LexicalNamespaceDropVersion = 1
)

Schema-version constants for lexical.* payloads. See doc.go.

View Source
const (
	LLMRequestVersion    = 2
	LLMResponseVersion   = 1
	StreamChunkVersion   = 1
	StreamEndVersion     = 1
	StreamSegmentVersion = 1
	StreamHoldVersion    = 1
	StreamRetractVersion = 1
	BatchSubmitVersion   = 1
	BatchStatusVersion   = 1
	BatchResultsVersion  = 1
)

Schema-version constants for llm.* payloads. See doc.go.

View Source
const (
	MCPResourceUpdatedVersion = 1
	MCPPromptsListVersion     = 1
)

Schema-version constants for mcp.* payloads. See doc.go.

View Source
const (
	MemoryEntryVersion                 = 1
	MemoryQueryVersion                 = 1
	MemoryResultVersion                = 1
	HistoryQueryVersion                = 1
	LongTermMemoryEntryVersion         = 1
	LongTermMemoryLoadedVersion        = 1
	LongTermMemoryStoreRequestVersion  = 1
	LongTermMemoryStoredVersion        = 1
	LongTermMemoryReadRequestVersion   = 1
	LongTermMemoryReadResultVersion    = 1
	LongTermMemoryDeleteRequestVersion = 1
	LongTermMemoryDeletedVersion       = 1
	LongTermMemoryQueryVersion         = 1
	LongTermMemoryListResultVersion    = 1
	CompactionTriggeredVersion         = 1
	CompactionCompleteVersion          = 1

	// Idea 30 — live context curation events.
	MemoryToolResultClearedVersion  = 1
	MemoryToolDefPrunedVersion      = 1
	MemoryTopicShiftDetectedVersion = 1
	MemorySummaryReplacedVersion    = 1
	MemoryCuratedVersion            = 1
)

Schema-version constants for memory.* payloads. See doc.go.

View Source
const (
	PlanRequestVersion  = 1
	PlanResultVersion   = 1
	PlanProgressVersion = 1
)

Schema-version constants for plan.* payloads. See doc.go.

View Source
const (
	ProviderFallbackVersion       = 1
	ProviderFanoutStartVersion    = 1
	ProviderFanoutResponseVersion = 1
	ProviderFanoutCompleteVersion = 1
	ProviderFanoutChooseVersion   = 1
	ProviderFanoutChosenVersion   = 1
)

Schema-version constants for provider.* payloads. See doc.go.

View Source
const (
	RAGIngestVersion       = 1
	RAGIngestDeleteVersion = 1
)

Schema-version constants for rag.* payloads. See doc.go.

View Source
const (
	SchemaRegistrationVersion   = 1
	SchemaDeregistrationVersion = 1
)

Schema-version constants for schema.* registry payloads. See doc.go.

Note: this file holds payloads for the schema-registry events ("schema.register" / "schema.deregister") that JSON-schema gates use to publish output schemas. It is unrelated to the per-event-type `_schema_version` field added to every payload struct in this package — that is a versioning mechanism for the event payloads themselves.

View Source
const (
	// SessionFileVersion is 2 because version 1 named an Action field and no
	// SessionID, Offset or BytesAdded -- but nothing ever emitted it, so 2 is
	// the first version any subscriber will see. See SessionFile.
	//
	// No compat migrator is registered for 1->2, deliberately. The struct
	// changed; the wire did not, beyond gaining _schema_version itself. A
	// journaled payload written before this carries the same five keys under
	// the same names, so it deserializes to a v2 payload with the version
	// reading 0 -- which the v0 == v1 rule in pkg/events/compat already covers,
	// and which every subscriber reads by key regardless.
	SessionFileVersion            = 2
	SessionSnapshotRequestVersion = 1
	SessionSnapshotResultVersion  = 1
	SessionOwnerConflictVersion   = 1

	SessionStorageDegradedVersion  = 1
	SessionStorageRecoveredVersion = 1

	SessionTagSetRequestVersion    = 1
	SessionTagDeleteRequestVersion = 1
	SessionTagSetVersion           = 1
	SessionTagDeletedVersion       = 1
)

Schema-version constants for session.* payloads. See doc.go.

View Source
const (
	SkillCatalogVersion      = 1
	SkillActivationVersion   = 1
	SkillContentVersion      = 1
	SkillRefVersion          = 1
	SkillResourceReqVersion  = 1
	SkillResourceDataVersion = 1
)

Schema-version constants for skill.* payloads. See doc.go.

View Source
const (
	ToolCallVersion         = 1
	ToolCatalogQueryVersion = 1
	ToolTimeoutVersion      = 1
	ToolResultVersion       = 1
)

Schema-version constants for tool.* payloads. See doc.go.

View Source
const (
	VectorUpsertVersion        = 1
	VectorQueryVersion         = 1
	VectorDeleteVersion        = 1
	VectorNamespaceDropVersion = 1
)

Schema-version constants for vector.* payloads. See doc.go.

View Source
const (
	VoiceAudioInputChunkVersion  = 1
	VoiceAudioOutputChunkVersion = 1
)

Schema-version constants for voice.* payloads. See doc.go.

Voice events are forward-looking placeholders for Phase 4 of the multimodal/voice IO work tracked under Idea 18. The realtime IO transport (nexus.io.realtime) carries them between connected clients and the bus today; nexus.io.voice will consume input chunks (run VAD + ASR) and produce output chunks (TTS) once that plugin lands.

View Source
const (
	WorkflowStatusStarted   = "started"
	WorkflowStatusRunning   = "running"
	WorkflowStatusIterating = "iterating"
	WorkflowStatusItemDone  = "item_done"
	WorkflowStatusCompleted = "completed"
	WorkflowStatusFailed    = "failed"
	WorkflowStatusHalted    = "halted"
)

Workflow* status constants are the closed set Status field values for WorkflowProgress. Workflow plugins (e.g. nexus.workflows.icm, nexus.agent.planexec) emit one event per state transition.

View Source
const (
	EmbeddingsRequestVersion = 1
)

Schema-version constants for embeddings.* payloads. See doc.go.

View Source
const (
	HybridQueryVersion = 1
)

Schema-version constants for hybrid.* payloads. See doc.go.

View Source
const (
	RerankRequestVersion = 1
)

Schema-version constants for reranker.* payloads. See doc.go.

View Source
const (
	SearchRequestVersion = 1
)

Schema-version constants for search.* payloads. See doc.go.

View Source
const (
	ThinkingStepVersion = 1
)

Schema-version constants for thinking.* payloads. See doc.go.

View Source
const ToolTagAwaitsHuman = "awaits_human"

ToolTagAwaitsHuman marks a ToolDef whose call can block on a human (or a human-driven client) from inside its handler — a write approval, a client-executed tool whose result comes back on a later request. A per-call deadline sized for machines would cut such a call off while the person is still deciding, so nexus.gate.tool_timeout exempts tools carrying this tag by default, learned from tool.register and from tool.catalog.query snapshots. The owning plugin sets the tag only when the wait is real (e.g. longterm memory_write only while require_approval is on), so the flag stays with the plugin that knows, and the gate never hard-codes a foreign name.

View Source
const (
	VectorMemoryStoreVersion = 1
)

Schema-version constants for memory.vector payloads. See doc.go.

View Source
const (
	WorkflowProgressVersion = 1
)

Schema-version constants for workflow.* payloads. See doc.go.

Variables

This section is empty.

Functions

func Versions

func Versions() map[string]int

Versions returns the payload version manifest: payload struct name (e.g. "ToolCall", "LLMRequest") mapped to the `<Name>Version` constant the running code stamps into `_schema_version`. It covers every payload that carries a version constant.

The map is a fresh copy on every call, so a caller cannot mutate the package's view. Consumers pin the subset they read in one table test and get a single failure naming every payload that moved; see "Consumer-side pinning" in the package documentation.

Types

type AgentOutput

type AgentOutput struct {
	SchemaVersion int `json:"_schema_version"`

	Content  string
	Role     string // "assistant", "system", "tool"
	Metadata map[string]any
	TurnID   string
}

AgentOutput represents a complete output message from the agent.

type AgentToolChoice

type AgentToolChoice struct {
	SchemaVersion int `json:"_schema_version"`

	Mode     string // "auto" | "required" | "none" | "tool"
	ToolName string // when Mode == "tool"
	Duration string // "once" = next request only; "sticky" = until replaced
}

AgentToolChoice is emitted by plugins to dynamically override the agent's tool choice for subsequent LLM requests.

type ApprovalRequest

type ApprovalRequest struct {
	SchemaVersion int `json:"_schema_version"`

	PromptID    string
	Description string
	ToolCall    string
	Risk        string // "low", "medium", "high"
}

ApprovalRequest asks the user to approve an action.

type ApprovalResponse

type ApprovalResponse struct {
	SchemaVersion int `json:"_schema_version"`

	PromptID string
	Approved bool
	Always   bool
}

ApprovalResponse carries the user's approval decision.

type BatchCounts

type BatchCounts struct {
	Total     int
	Completed int
	Failed    int
}

BatchCounts is a best-effort snapshot of per-request progress in a batch.

type BatchRequest

type BatchRequest struct {
	CustomID string
	Request  LLMRequest
}

BatchRequest pairs a stable caller-defined id with an LLMRequest. The CustomID is how the caller correlates results (per-request) when the batch returns out of order.

type BatchResult

type BatchResult struct {
	CustomID string
	Response *LLMResponse // nil when Error is set
	Error    string       // non-empty when this individual request failed
}

BatchResult is a single per-request entry in a BatchResults payload. Either Response is non-nil (success) or Error is non-empty (this individual request failed); callers must check both.

type BatchResults

type BatchResults struct {
	SchemaVersion int `json:"_schema_version"`

	Provider string
	BatchID  string
	Results  []BatchResult
}

BatchResults is emitted once at the end of a batch, carrying all per-request results.

Bus event type: "llm.batch.results".

type BatchStatus

type BatchStatus struct {
	SchemaVersion int `json:"_schema_version"`

	Provider string
	BatchID  string
	Status   string // "submitted" | "in_progress" | "completed" | "failed" | "cancelled"
	Counts   BatchCounts
}

BatchStatus is emitted periodically by the coordinator while the batch is in flight. Counts are best-effort — providers report different shapes.

Bus event type: "llm.batch.status".

type BatchSubmit

type BatchSubmit struct {
	SchemaVersion int `json:"_schema_version"`

	Provider string // "anthropic" | "openai"
	Requests []BatchRequest
	Metadata map[string]any
}

BatchSubmit is published by callers (CLI subcommand, agent tool, etc.) to request that a slice of LLMRequests be sent to a provider's batch endpoint rather than the synchronous llm.request path. The coordinator plugin (`nexus.llm.batch`) handles dispatch, polling, and result aggregation.

Bus event type: "llm.batch.submit".

type BootConfig

type BootConfig struct {
	SchemaVersion int `json:"_schema_version"`

	ConfigPath string
	Profile    string
}

BootConfig carries bootstrap configuration for system startup.

type CancelActive

type CancelActive struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID string
}

CancelActive signals that cancellation is in progress.

type CancelComplete

type CancelComplete struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	Resumable bool
}

CancelComplete signals that cancellation has finished. Resumable indicates whether the cancelled operation can be resumed.

type CancelRequest

type CancelRequest struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID string
	Source string // "tui", "browser", etc.
}

CancelRequest asks the system to cancel the current operation.

type CancelResume

type CancelResume struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID string
}

CancelResume requests resuming a previously cancelled operation.

type ChoiceKind

type ChoiceKind string

ChoiceKind classifies a HITLChoice for renderers and policy code that want to treat allow/reject/edit specially without parsing the label. "custom" is the escape hatch for choices that don't fit the canonical approval vocabulary (e.g., "Plan A / Plan B / Plan C").

const (
	ChoiceAllow  ChoiceKind = "allow"
	ChoiceReject ChoiceKind = "reject"
	ChoiceEdit   ChoiceKind = "edit"
	ChoiceCustom ChoiceKind = "custom"
)

type Citation

type Citation struct {
	Type            string // "char_location" | "page_location" | "content_block_location"
	CitedText       string
	DocumentIndex   int
	DocumentTitle   string
	StartCharIndex  int
	EndCharIndex    int
	StartPageNumber int
	EndPageNumber   int
	StartBlockIndex int
	EndBlockIndex   int
}

Citation is a single source attribution returned by a provider that supports native citation tracking (currently Anthropic). Other providers leave the LLMResponse.Citations slice nil.

type CitationRef

type CitationRef struct {
	Source    string
	DocID     string
	ChunkIdx  string
	Snippet   string
	TrustTier string

	// Span is the [start, end) byte offset into CitedResponse.Text where the
	// citation applied. Zeros when the source format does not provide it.
	SpanStart int
	SpanEnd   int
}

CitationRef is one parsed source attribution attached to an LLM response. Lighter than the provider-native Citation struct (which carries Anthropic- specific char/page indices) — works for both tag-based parsing and the Anthropic native path.

type CitedResponse

type CitedResponse struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	Text      string
	Citations []CitationRef
	// Mode tracks how the citations were obtained: "tag" (parsed from
	// <cite/> markers) or "anthropic_native" (read from Citations[] on the
	// underlying response).
	Mode string
}

CitedResponse is the post-processed LLM response with citation tags stripped from user-visible text and structured CitationRefs collected. Emitted as "llm.response.cited" after every llm.response that resolves against an active retrieval context.

type CodeExecRequest

type CodeExecRequest struct {
	SchemaVersion int `json:"_schema_version"`

	CallID  string // matches the originating ToolCall.ID
	TurnID  string
	Script  string   // full Go source
	Imports []string // import paths referenced by the script
	Skills  []string // active skill names whose helpers are loaded
}

CodeExecRequest signals that a run_code script is about to execute. Emitted by nexus.tool.code_exec before the Yaegi interpreter runs the script.

type CodeExecResult

type CodeExecResult struct {
	SchemaVersion int `json:"_schema_version"`

	CallID    string
	TurnID    string
	Output    string // stdout (capped at max_output_bytes)
	Result    string // JSON-marshaled return value of Run()
	Error     string // first error encountered (compile, AST reject, runtime, timeout)
	Duration  int64  // execution wall time in milliseconds
	Truncated bool   // stdout was truncated
}

CodeExecResult reports the outcome of a run_code script. Emitted by nexus.tool.code_exec after the script returns (or errors out).

type CodeExecStdout

type CodeExecStdout struct {
	SchemaVersion int `json:"_schema_version"`

	CallID    string
	TurnID    string
	Chunk     string // UTF-8 text; may contain newlines
	Final     bool   // true for the last chunk of this call
	Truncated bool   // true on the final chunk if the total exceeded max_output_bytes
}

CodeExecStdout carries a chunk of stdout produced by a run_code script while it is still executing. Emitted incrementally by nexus.tool.code_exec so IO plugins can show live output instead of waiting for the final CodeExecResult. Chunks are flushed on newline or when the buffered output exceeds an internal threshold; the last chunk (possibly empty) carries Final=true so UIs can mark the stream closed.

type CompactionComplete

type CompactionComplete struct {
	SchemaVersion int `json:"_schema_version"`

	Messages     []Message // the compacted conversation
	BackupPath   string    // session-relative path to the backup file
	MessageCount int       // number of messages after compaction
	PrevCount    int       // number of messages before compaction
}

CompactionComplete signals that context compaction has finished. Subscribers should replace their conversation history with Messages.

type CompactionTriggered

type CompactionTriggered struct {
	SchemaVersion int `json:"_schema_version"`

	Reason       string // human-readable trigger reason
	MessageCount int    // number of messages before compaction
	BackupPath   string // session-relative path to the backup file
}

CompactionTriggered signals that context compaction is starting.

type ConfigReloadRequest

type ConfigReloadRequest struct {
	SchemaVersion int `json:"_schema_version"`

	Path   string `json:"path,omitempty"`
	Source string `json:"source,omitempty"`
}

ConfigReloadRequest is emitted by an external trigger (admin HTTP, custom plugin) to request that the engine re-read its YAML and apply the result via Engine.ReloadConfig. Path may override the original config path; an empty Path means "re-read whatever path the engine was launched with". Source identifies the trigger for log correlation (e.g. "browser-admin").

type ConfigReloadResult

type ConfigReloadResult struct {
	SchemaVersion int `json:"_schema_version"`

	RequestID    string `json:"request_id,omitempty"`
	Source       string `json:"source,omitempty"`
	OK           bool   `json:"ok"`
	ErrorMessage string `json:"error,omitempty"`
}

ConfigReloadResult is emitted by the engine after acting on a ConfigReloadRequest. Triggers that need synchronous feedback (the admin HTTP endpoint) subscribe to this and correlate by the optional RequestID field. ErrorMessage is empty on success.

type CurationSection

type CurationSection struct {
	// SectionID is an opaque identifier for the section that was edited.
	// Convention: "<plugin-id>/<scope>" e.g. "nexus.memory.tool_result_clear/turn-12"
	// or "nexus.memory.summary_buffer/range-3-8".
	SectionID string `json:"section_id"`
	// Kind is the cache-stability category. "volatile" = recent turns
	// (no cache impact); "session" = session-long content like compaction
	// summaries (controlled re-cache); "static" = system prompt / tool defs
	// (curator must not touch these).
	Kind string `json:"kind"`
	// TokensDelta is the post-edit minus pre-edit token estimate. Negative
	// for shrinkage (the common case); positive for replacements that grew.
	TokensDelta int `json:"tokens_delta"`
}

CurationSection describes one section of context touched by a curation pass. Used by MemoryCurated to convey stability impact.

type EmbeddingsInput

type EmbeddingsInput struct {
	// Text is set when this input is a text snippet. Mutually exclusive
	// with Image and ImageURI.
	Text string
	// Image is the inline image bytes. Mutually exclusive with Text and
	// ImageURI. Requires MimeType.
	Image []byte
	// ImageURI references an image by URI: "nexus-blob:<sha>" for the
	// engine blob store, or a plain HTTPS URL the provider can fetch.
	// Mutually exclusive with Text and Image.
	ImageURI string
	// MimeType is the IANA media type (e.g. "image/png", "image/jpeg")
	// describing Image / ImageURI bytes. Required when Image is set;
	// recommended for ImageURI.
	MimeType string
}

EmbeddingsInput is one polymorphic embedding input. Exactly one of Text, Image, or ImageURI is populated. Adapters that don't support image inputs must return a clear error when they encounter an image-bearing input rather than silently downgrading.

The ImageURI form supports the engine's content-addressed blob scheme ("nexus-blob:<sha>") and plain external URLs. A provider that can't resolve a particular scheme must error rather than skip the input.

type EmbeddingsRequest

type EmbeddingsRequest struct {
	SchemaVersion int `json:"_schema_version"`

	// Texts is the batch of strings to embed. Order is preserved in Vectors.
	// Used when Inputs is empty — keeps existing text-only callers and
	// adapters working unchanged.
	Texts []string
	// Inputs is the polymorphic batch (text and/or image inputs) for
	// multimodal-aware providers. Additive over Texts: when empty, providers
	// continue to read Texts. When non-empty, providers must consume Inputs
	// in order (one vector per Input) and either honor every Input kind or
	// return a clear error (e.g. an OpenAI text-only embedding model
	// receiving an image input). Adapters must not silently downgrade an
	// image input to a text fallback.
	Inputs []EmbeddingsInput
	// Model is the embeddings model to use. Zero value means provider default.
	Model string
	// Dimensions optionally requests a specific vector dimensionality when
	// the provider supports truncation (e.g. OpenAI text-embedding-3-*). Zero
	// means provider default.
	Dimensions int

	// Vectors / Provider / Model (possibly echoed back) / Usage / Error are
	// populated by the provider handler. Callers should treat them as zero
	// on input.
	Vectors  [][]float32
	Provider string // plugin ID of the adapter that answered
	Usage    EmbeddingsUsage
	Error    string // non-empty when the call failed
}

EmbeddingsRequest is an outbound embeddings request. The consumer fires it as a pointer payload on "embeddings.request"; the capability-resolved provider fills Vectors / Provider / Model / Error in place before Emit returns. Mirrors the synchronous fill pattern used by SearchRequest and HistoryQuery — embeddings are a one-shot lookup with no streaming surface.

type EmbeddingsUsage

type EmbeddingsUsage struct {
	PromptTokens int
	TotalTokens  int
}

EmbeddingsUsage reports token accounting for an embeddings call when the provider returns it. Zero values are fine when unknown.

type ErrorInfo

type ErrorInfo struct {
	SchemaVersion int `json:"_schema_version"`

	Source           string // plugin ID
	Err              error
	Fatal            bool
	Retryable        bool           // whether this error class is retryable (429, 5xx)
	RetriesExhausted bool           // provider's own retry logic gave up
	RequestMeta      map[string]any // echo of LLMRequest.Metadata for correlation
	// RequestID is set on errors that originated from a specific LLMRequest
	// so subscribers (token budget reservations, cancel registries) can
	// release per-request state without scanning RequestMeta. Empty for
	// errors not tied to a specific request.
	RequestID string
	// EventType is set when ErrorInfo describes a panic recovered during
	// event dispatch — names the event whose handler panicked. Empty for
	// errors that did not originate from a recovered handler panic.
	EventType string
	// Stack is the goroutine stack (debug.Stack output) captured at panic
	// recovery time. Empty for non-panic ErrorInfo records.
	Stack string
}

ErrorInfo describes an error originating from a specific source.

type FileAttachment

type FileAttachment struct {
	Name     string
	MimeType string
	Data     []byte
}

FileAttachment is a file attached to user input.

type HITLCancel

type HITLCancel struct {
	SchemaVersion int    `json:"_schema_version"`
	RequestID     string `json:"request_id"`
	Reason        string `json:"reason,omitempty"`
}

HITLCancel is emitted by the requesting plugin to retract a pending HITLRequest. The control/hitl plugin subscribes, removes any persisted request file, and emits a synthetic hitl.responded{Cancelled: true, CancelReason: Reason} so any in-flight waiter unblocks cleanly.

Use when the requester decides the prompt is no longer needed (parent context cancelled, upstream stage failed, deadline elapsed in caller code, etc.). Idempotent: subsequent HITLCancel events for the same ID are no-ops once the request has been resolved.

type HITLChoice

type HITLChoice struct {
	ID            string         `json:"id"`
	Label         string         `json:"label"`
	Kind          ChoiceKind     `json:"kind,omitempty"`
	EditedPayload map[string]any `json:"edited_payload,omitempty"`
}

HITLChoice is one option presented to the operator in a multi-choice HITLRequest. The ID is canonical and machine-stable; the Label is the human-readable text the UI shows. EditedPayload, when non-nil, is the override the requesting plugin should apply to its action when this choice is picked — used by "edit" choices to carry trimmed args, swapped models, and similar.

type HITLMode

type HITLMode string

HITLMode controls what shape of response a HITLRequest accepts.

const (
	// HITLModeFreeText accepts a single string answer. Choices ignored.
	HITLModeFreeText HITLMode = "free_text"
	// HITLModeChoices restricts the response to one of the provided Choices.
	HITLModeChoices HITLMode = "choices"
	// HITLModeBoth accepts either a chosen ID or freeform text (or both —
	// e.g., "edit" choice with an explanatory note).
	HITLModeBoth HITLMode = "both"
)

type HITLRequest

type HITLRequest struct {
	SchemaVersion int `json:"_schema_version"`
	// ID is stable across the request's lifetime and is what the response
	// correlates against. Generated by the requesting plugin.
	ID string `json:"id"`
	// SessionID is the owning session. Mostly cosmetic — the bus is
	// already session-scoped — but useful for out-of-band CLI tooling.
	SessionID string `json:"session_id,omitempty"`
	// TurnID, when set, ties the request to a specific agent turn so IO
	// plugins can render it inline with the turn it interrupted.
	TurnID string `json:"turn_id,omitempty"`
	// RequesterPlugin is the dotted plugin ID that emitted the request.
	RequesterPlugin string `json:"requester_plugin,omitempty"`
	// ActionKind discriminates what kind of action is awaiting human
	// input: "free_text", "tool.invoke", "memory.longterm.write",
	// "llm.request", or any plugin-defined extension. The control/hitl
	// plugin does not interpret this — it's surfaced verbatim to the IO
	// plugin and to the prompt synthesizer (when configured).
	ActionKind string `json:"action_kind,omitempty"`
	// ActionRef is the opaque payload describing the pending action.
	// Carried alongside the request so the synthesizer can render a
	// context-aware prompt and so the resumed plugin can apply
	// EditedPayload overrides on response.
	ActionRef map[string]any `json:"action_ref,omitempty"`
	// Mode controls whether the response is freeform, multi-choice, or
	// either. Defaults to free_text when zero.
	Mode HITLMode `json:"mode,omitempty"`
	// Choices is the list of options when Mode != free_text.
	Choices []HITLChoice `json:"choices,omitempty"`
	// DefaultChoiceID is the choice picked when the deadline expires
	// without a response. Must reference an existing Choices entry.
	DefaultChoiceID string `json:"default_choice_id,omitempty"`
	// Prompt is the literal rendered question/approval text shown to
	// the operator.
	Prompt string `json:"prompt,omitempty"`
	// PromptTemplate is a Go text/template applied over ActionRef. Set
	// by gates that prefer declarative messaging; control/hitl renders
	// it before forwarding to IO plugins.
	PromptTemplate string `json:"prompt_template,omitempty"`
	// PromptSynthesizer names a registered prompt-synthesizer capability
	// (e.g. "hitl.prompt_synthesizer"). When set, control/hitl invokes
	// the capability and uses the returned text as the rendered Prompt.
	// Falls back to a generic prompt if the capability is unavailable.
	PromptSynthesizer string `json:"prompt_synthesizer,omitempty"`
	// Deadline is an optional absolute timeout. When elapsed, the
	// request auto-resolves with DefaultChoiceID.
	Deadline time.Time `json:"deadline,omitzero"`
	// Metadata is for plugin-specific extensions. Not interpreted by
	// the engine.
	Metadata map[string]any `json:"metadata,omitempty"`
	// CallID, when set, is the ToolCall.ID of the tool call this request
	// was raised on or for: ask_user's own call, the call an approval gate
	// is holding at before:tool.invoke, the delegate call whose remote
	// asked a question. nexus.control.hitl cancels every pending request
	// naming a call when a tool.timeout fires for it, so a prompt for a
	// call that is already over does not stay open until shutdown. Empty
	// for requests that belong to no tool call.
	CallID string `json:"call_id,omitempty"`
}

HITLRequest is the unified human-in-the-loop request payload. It supersedes the retired io.ask (AskUser) event and the design-doc-only ApprovalRequest: any plugin that needs an operator's input — clarifying a question, approving a destructive tool call, picking among curated plans, or signing off on a memory write — emits this single event type.

Exactly one of Prompt, PromptTemplate, or PromptSynthesizer should be set. The control/hitl plugin renders the final string at request time; IO plugins receive the rendered Prompt and need not understand the other two fields.

type HITLResponse

type HITLResponse struct {
	SchemaVersion int `json:"_schema_version"`
	// RequestID matches HITLRequest.ID.
	RequestID string `json:"request_id"`
	// ChoiceID, when non-empty, is the picked choice's ID.
	ChoiceID string `json:"choice_id,omitempty"`
	// FreeText is the operator's freeform answer when applicable.
	FreeText string `json:"free_text,omitempty"`
	// EditedPayload, when non-nil, supersedes the matching choice's
	// EditedPayload (lets the operator hand-edit on response). The
	// requesting plugin treats this as the action override.
	EditedPayload map[string]any `json:"edited_payload,omitempty"`
	// Cancelled is true when the request was cancelled rather than
	// answered (deadline expired with no DefaultChoiceID, operator
	// invoked `nexus hitl cancel`, etc.).
	Cancelled bool `json:"cancelled,omitempty"`
	// CancelReason carries the cancellation reason when Cancelled.
	CancelReason string `json:"cancel_reason,omitempty"`
}

HITLResponse is the operator's answer to a HITLRequest. Exactly one of ChoiceID or FreeText is meaningful in HITLModeChoices / HITLModeFreeText; in HITLModeBoth either or both may be set.

type HistoryQuery

type HistoryQuery struct {
	SchemaVersion int `json:"_schema_version"`

	// SessionID scopes the query when multiple sessions share a bus. Empty
	// means "the current session". Set by caller.
	SessionID string
	// Messages is filled by the handler. Caller should treat it as nil on
	// input; a nil result after Emit means no history plugin answered.
	Messages []Message
}

HistoryQuery is a synchronous request for LLM-native conversation history. Emitted as a pointer payload on "memory.history.query"; the handler fills Messages in place before the Emit call returns. This follows the same pointer-mutation pattern as VetoablePayload. Callers consume Messages after Emit returns.

type HistoryReplay

type HistoryReplay struct {
	SchemaVersion int `json:"_schema_version"`

	Messages []Message
}

HistoryReplay carries persisted conversation messages for UI display on session recall.

type HybridMatch

type HybridMatch struct {
	ID         string
	Content    string
	Metadata   map[string]string
	Score      float32
	Similarity float32
	Lexical    float32
	Sources    []string
}

HybridMatch is one fused result returned by a hybrid search. Score is the fused relevance (RRF or weighted, per orchestrator config); Similarity and Lexical preserve the raw per-backend scores so downstream consumers can re-weight or report them. Sources lists which backends contributed (e.g. ["vector"], ["lexical"], ["vector","lexical"]).

type HybridQuery

type HybridQuery struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace   string
	Query       string
	Vector      []float32
	K           int
	Filter      map[string]string
	LexicalBias float32

	Matches  []HybridMatch
	Provider string
	Error    string
}

HybridQuery requests a fused retrieval against both vector and lexical stores in a single namespace. Fired as a pointer payload on "hybrid.query"; the search.hybrid provider fills Matches / Provider / Error in place before Emit returns.

The orchestrator embeds Query when Vector is empty. Callers that have already embedded (e.g. memory recall reusing a turn-level vector) pass Vector to skip the embed call. LexicalBias in [-1, 1] tilts the per-query fusion weights — positive favors lexical, negative favors vector.

type LLMRequest

type LLMRequest struct {
	SchemaVersion int `json:"_schema_version"`

	// RequestID correlates an LLMRequest with its LLMResponse and any related
	// gate state (cancel registries, token reservations). Providers MUST copy
	// it onto the response. Originators may leave it empty; providers generate
	// one when absent. Required for correctness under concurrent in-flight
	// requests on the same provider instance.
	RequestID string

	Role           string // Model role (e.g., "reasoning", "balanced", "quick")
	Model          string // Explicit model ID override (takes precedence over Role)
	Messages       []Message
	Tools          []ToolDef
	ToolChoice     *ToolChoice     // nil = provider default (auto)
	ToolFilter     *ToolFilter     // nil = no filtering
	ResponseFormat *ResponseFormat // nil = no structured output constraint
	MaxTokens      int

	// Effort is an opaque, provider-interpreted reasoning-depth hint. It is an
	// internal carrier, not an operator-facing key: operators set it on a
	// `core.models` chain entry (engine.ModelConfig.Effort) and the fallback
	// and fanout coordinators copy the serving entry's value onto the outgoing
	// request, so a provider knows which chain entry it is answering for.
	// Core never validates it — each provider owns its own vocabulary and any
	// clamping. Empty means "not set": providers must leave their reasoning
	// configuration untouched. A value already present on an inbound request
	// wins; a chain entry only fills in a value the request lacks.
	Effort string

	// Overrides carries the rest of the serving chain entry's configuration —
	// the native provider blocks and the API-surface selector, which have no
	// dedicated field here. Same rule as Effort in both directions: a value
	// already on the request wins outright, and a chain entry only fills an
	// axis the request arrived without. Added in schema v2.
	Overrides ModelOverrides

	// Temperature is the sampling temperature. nil means "not set": the
	// provider leaves its own default alone. It is a pointer because 0.0 is a
	// meaningful temperature and so cannot double as "unset". Anything that
	// already put a value here — an agent posture, a gate — wins over a
	// `core.models` entry, which only fills the gap.
	Temperature *float64
	Stream      bool
	Prediction  string // OpenAI-only: known-content prediction for low-latency edits.
	// Other providers ignore this field. Empty = no prediction.
	Metadata map[string]any

	// Tags carries cost-attribution dimensions attached at request creation
	// per the DigitalApplied "tags must be attached at request creation, not
	// retroactively" guidance. The engine seeds baseline tags from session
	// metadata (`tenant`, `project`, `user`, `session_id`); plugins layer
	// their own (`source_plugin`, `task_kind`, `parent_call_id`).
	//
	// Propagates onto LLMResponse.Tags, OTEL spans, and journal records so
	// that the cost report CLI and the multi-dimensional budget gate can
	// roll up by any tag dimension.
	Tags map[string]string
}

LLMRequest describes a request to a language model.

SchemaVersion bumped to 2 when Overrides was added. The field is a struct of optional scalars and maps, so a v1 payload still parses cleanly into the v2 struct (every axis reads as unset) and a v1 consumer ignores the extra JSON object — the addition is forward- and backward-compatible in the journal.

type LLMResponse

type LLMResponse struct {
	SchemaVersion int `json:"_schema_version"`

	// RequestID is copied verbatim from LLMRequest.RequestID. Subscribers that
	// must correlate request and response (provider in-flight tracking, the
	// blocking sync-RPC helper, the token-budget reserve/commit gate) key on
	// it.
	RequestID string

	Content      string
	ToolCalls    []ToolCallRequest
	Usage        Usage
	CostUSD      float64 // provider-computed cost for this request
	Model        string
	FinishReason string
	Metadata     map[string]any

	// Citations carries native source attributions emitted by providers that
	// support them (currently Anthropic). Nil when the provider doesn't emit
	// citations or the request didn't include citation-enabled documents.
	Citations []Citation

	// Alternatives holds additional responses from parallel fanout providers.
	// Nil for normal (non-fanout) requests. When populated, the primary fields
	// above contain the first successful response (or selected winner), and
	// Alternatives contains the remaining responses.
	Alternatives []LLMResponse

	// Tags carries cost-attribution dimensions copied from the originating
	// LLMRequest. Providers must propagate the request Tags onto the response
	// they emit so downstream subscribers (cost CLI, budget gate, OTEL
	// exporter) can attribute usage without re-correlating by call id.
	Tags map[string]string
}

LLMResponse is the complete response from a language model.

type LexicalDelete

type LexicalDelete struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string
	IDs       []string

	Provider string
	Error    string
}

LexicalDelete requests removal of documents by ID from a namespace. Fired as a pointer payload on "lexical.delete".

type LexicalDoc

type LexicalDoc struct {
	ID       string
	Content  string
	Metadata map[string]string
}

LexicalDoc is a single document in a lexical (keyword / BM25) index. Identifiers and metadata mirror VectorDoc so the dual-write ingest pipeline can build both records from one chunk. Vector is intentionally absent — lexical stores rank by token overlap, not similarity.

type LexicalMatch

type LexicalMatch struct {
	ID       string
	Content  string
	Metadata map[string]string
	Score    float32
}

LexicalMatch is one hit returned by a lexical query. Score is BM25-style relevance — higher is better, range backend-dependent.

type LexicalNamespaceDrop

type LexicalNamespaceDrop struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string

	Provider string
	Error    string
}

LexicalNamespaceDrop requests removal of an entire namespace. Fired as a pointer payload on "lexical.namespace.drop". Idempotent: dropping an unknown namespace is not an error.

type LexicalQuery

type LexicalQuery struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string
	Query     string
	K         int
	Filter    map[string]string // exact-match metadata filter; empty means no filter

	Matches  []LexicalMatch
	Provider string
	Error    string
}

LexicalQuery requests a BM25 nearest-keyword lookup in a namespace. Fired as a pointer payload on "lexical.query"; the provider fills Matches / Provider / Error in place before Emit returns.

type LexicalUpsert

type LexicalUpsert struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string
	Docs      []LexicalDoc

	Provider string
	Error    string
}

LexicalUpsert requests a batch insert/replace of documents into a namespace. Fired as a pointer payload on "lexical.upsert"; the search.lexical provider fills Provider / Error in place before Emit returns.

Upsert semantics: documents with an ID already present in the namespace are replaced. Adapters without native upsert implement this as delete-then-add.

type LongTermMemoryDeleteRequest

type LongTermMemoryDeleteRequest struct {
	SchemaVersion int    `json:"_schema_version"`
	Key           string `json:"key"`
}

LongTermMemoryDeleteRequest is a request to delete a memory entry.

type LongTermMemoryDeleted

type LongTermMemoryDeleted struct {
	SchemaVersion int    `json:"_schema_version"`
	Key           string `json:"key"`
}

LongTermMemoryDeleted confirms a memory entry was deleted.

type LongTermMemoryEntry

type LongTermMemoryEntry struct {
	SchemaVersion int `json:"_schema_version"`

	Key           string            `json:"key"`
	Content       string            `json:"content"`
	Tags          map[string]string `json:"tags"`
	Created       time.Time         `json:"created"`
	Updated       time.Time         `json:"updated"`
	SourceSession string            `json:"source_session"`
}

LongTermMemoryEntry is a full memory record.

type LongTermMemoryIndex

type LongTermMemoryIndex struct {
	Key     string            `json:"key"`
	Preview string            `json:"preview"` // first line of content
	Tags    map[string]string `json:"tags"`
	Updated time.Time         `json:"updated"`
}

LongTermMemoryIndex is a lightweight reference to a memory entry.

type LongTermMemoryListResult

type LongTermMemoryListResult struct {
	SchemaVersion int                   `json:"_schema_version"`
	Entries       []LongTermMemoryIndex `json:"entries"`
}

LongTermMemoryListResult carries filtered memory index entries.

type LongTermMemoryLoaded

type LongTermMemoryLoaded struct {
	SchemaVersion int                   `json:"_schema_version"`
	Entries       []LongTermMemoryIndex `json:"entries"`
	Scope         string                `json:"scope"` // "agent", "global", or "both"
}

LongTermMemoryLoaded signals that the memory index has been injected into the system prompt.

type LongTermMemoryQuery

type LongTermMemoryQuery struct {
	SchemaVersion int               `json:"_schema_version"`
	Tags          map[string]string `json:"tags,omitempty"`
}

LongTermMemoryQuery is a request to list or filter memories.

type LongTermMemoryReadRequest

type LongTermMemoryReadRequest struct {
	SchemaVersion int    `json:"_schema_version"`
	Key           string `json:"key"`
}

LongTermMemoryReadRequest is a request to read a memory entry by key.

type LongTermMemoryReadResult

type LongTermMemoryReadResult struct {
	SchemaVersion int               `json:"_schema_version"`
	Key           string            `json:"key"`
	Content       string            `json:"content"`
	Tags          map[string]string `json:"tags"`
}

LongTermMemoryReadResult carries the full content of a memory entry.

type LongTermMemoryStoreRequest

type LongTermMemoryStoreRequest struct {
	SchemaVersion int               `json:"_schema_version"`
	Key           string            `json:"key"`
	Content       string            `json:"content"`
	Tags          map[string]string `json:"tags,omitempty"`
}

LongTermMemoryStoreRequest is a request to write or update a memory entry.

type LongTermMemoryStored

type LongTermMemoryStored struct {
	SchemaVersion int    `json:"_schema_version"`
	Key           string `json:"key"`
}

LongTermMemoryStored confirms a memory entry was written.

type MCPPromptArgument

type MCPPromptArgument struct {
	Name        string
	Description string
	Required    bool
}

MCPPromptArgument mirrors mcp.PromptArgument without depending on the SDK from the events package.

type MCPPromptDescriptor

type MCPPromptDescriptor struct {
	Command     string // includes leading slash, e.g. "/mcp.gh.review_pr"
	Server      string
	Prompt      string
	Title       string
	Description string
	Arguments   []MCPPromptArgument
}

MCPPromptDescriptor is the catalog entry returned by MCPPromptsList.

type MCPPromptsList

type MCPPromptsList struct {
	SchemaVersion int `json:"_schema_version"`

	Prompts []MCPPromptDescriptor
}

MCPPromptsList is a synchronous query event for the currently registered MCP prompt slash commands. Same fill-in-place pattern as HistoryQuery and ToolCatalogQuery: emit as a pointer payload, handler populates Prompts before Emit returns. IO plugins use this to render a /help entry without holding a reference to the mcp.client plugin directly.

type MCPResourceUpdated

type MCPResourceUpdated struct {
	SchemaVersion int `json:"_schema_version"`

	Server string
	URI    string
	Title  string
}

MCPResourceUpdated is emitted by nexus.mcp.client when a subscribed MCP resource changes upstream. No consumer is wired in Phase 1; the event is plumbed so future RAG ingest, memory, or cache-invalidation plugins can react without further core changes.

type MemoryCurated

type MemoryCurated struct {
	SchemaVersion int `json:"_schema_version"`

	// Layer names the curation layer that ran (e.g. "tool_result_clear",
	// "tool_def_pruner", "topic_pruner", "summary_buffer").
	Layer string `json:"layer"`
	// SectionsTouched describes every section the layer edited.
	SectionsTouched []CurationSection `json:"sections_touched"`
	// CacheInvalidates is true when at least one touched section is in
	// the cached prefix and the prompt builder must re-cache. False when
	// every touched section is volatile (no impact).
	CacheInvalidates bool `json:"cache_invalidates"`
	// AtTurn is the turn boundary at which the curation ran. Curations
	// batch at turn boundaries to keep cache invalidations predictable.
	AtTurn int `json:"at_turn"`
}

MemoryCurated is the envelope event emitted by every curation layer. It carries the stability-impact descriptor consumed by the cache-aware prompt builder (Idea 05) so cache invalidation cost is scoped.

type MemoryEntry

type MemoryEntry struct {
	SchemaVersion int `json:"_schema_version"`

	Key       string
	Content   string
	Metadata  map[string]any
	SessionID string
}

MemoryEntry represents a single memory record.

type MemoryQuery

type MemoryQuery struct {
	SchemaVersion int `json:"_schema_version"`

	Query     string
	Limit     int
	SessionID string
}

MemoryQuery describes a query against the memory store.

type MemoryResult

type MemoryResult struct {
	SchemaVersion int `json:"_schema_version"`

	Entries []MemoryEntry
	Query   string
}

MemoryResult carries the results of a memory query.

type MemorySummaryReplaced

type MemorySummaryReplaced struct {
	SchemaVersion int `json:"_schema_version"`

	FromTurns      [2]int   `json:"from_turns"` // [start, end] inclusive turn range
	OriginalTokens int      `json:"original_tokens"`
	SummaryTokens  int      `json:"summary_tokens"`
	PreservedKinds []string `json:"preserved_kinds"` // e.g. ["decision","rationale","error","next_step"]
}

MemorySummaryReplaced signals that a span of the conversation has been replaced with a reasoning-preserving summary. Distinct from CompactionComplete — that event reports a full-buffer rewrite; this one reports a span-level replacement.

type MemoryToolDefPruned

type MemoryToolDefPruned struct {
	SchemaVersion int `json:"_schema_version"`

	ToolID         string `json:"tool_id"`
	LastUsedTurn   int    `json:"last_used_turn"`
	DefinitionSize int    `json:"definition_size"`
}

MemoryToolDefPruned signals that a tool definition has been demoted out of the LLM-visible tool list because it has been idle too long. Restoration happens implicitly via discovery on next mention.

type MemoryToolResultCleared

type MemoryToolResultCleared struct {
	SchemaVersion int `json:"_schema_version"`

	ToolCallID    string `json:"tool_call_id"`
	Tool          string `json:"tool"`
	OriginalSize  int    `json:"original_size"`
	ClearedAtTurn int    `json:"cleared_at_turn"`
	Reason        string `json:"reason"` // "age", "subsequent_call", "no_citation", "synthesis_detected"
}

MemoryToolResultCleared signals that a tool result body has been replaced with an envelope marker by the live curator. The call/result pairing stays in history; only the body is gone.

type MemoryTopicShiftDetected

type MemoryTopicShiftDetected struct {
	SchemaVersion int `json:"_schema_version"`

	FromTurn   int     `json:"from_turn"`
	ToTurn     int     `json:"to_turn"`
	Similarity float64 `json:"similarity"`
	Signal     string  `json:"signal"` // "embedding" | "phrase" | "user_explicit"
}

MemoryTopicShiftDetected signals the topic pruner observed a topic boundary in the conversation.

type Message

type Message struct {
	Role    string // "system", "user", "assistant", "tool"
	Content string
	Parts   []MessagePart // optional multimodal parts; when non-empty, providers
	// that support multimodal serialize these alongside or instead of Content.
	// Providers without multimodal support fall back to Content (text-only path).
	ToolCallID string            // for tool result messages
	ToolCalls  []ToolCallRequest // for assistant messages with tool calls

	// Metadata carries provider-specific round-trip data that must survive a
	// turn boundary. Example: Anthropic extended-thinking emits opaque
	// `thinking` and `redacted_thinking` blocks (with cryptographic signatures)
	// that MUST be echoed back verbatim on the next assistant turn after a
	// tool result, otherwise the API rejects the request with HTTP 400.
	// Providers stash these as Metadata["thinking_blocks"] on the assistant
	// Message and read them back when serializing the next request body.
	// Keys are namespaced informally per-provider; consumers other than the
	// owning provider should treat this map as opaque.
	Metadata map[string]any
}

Message represents a single message in an LLM conversation.

type MessagePart

type MessagePart struct {
	Type     string // "text" | "image" | "audio" | "video" | "file"
	Text     string // when Type == "text"
	MimeType string // e.g. "image/png", "application/pdf"; required when Data or URI set
	Data     []byte // inline bytes
	URI      string // provider-hosted reference (e.g. Gemini Files API URI)
	FileID   string // provider-issued file id (e.g. Anthropic file_..., OpenAI file-...).

}

MessagePart carries a single piece of multimodal content. Providers that don't support a given Type should skip the part (or concatenate Text parts). Either Data (inline bytes) or URI (provider-hosted reference) is set, never both. Inline payloads beyond a provider-specific size limit are uploaded by the provider and replaced with a URI on send.

type ModelOverrides

type ModelOverrides struct {
	// Stamped reports that a coordinator has already applied the chain entry
	// it is actually serving. A consumer seeing it MUST NOT consult the model
	// registry for anything left unset here: a registry lookup always returns
	// the role's *first* entry, which for a fallback retry or a non-first
	// fanout leg is the wrong one.
	Stamped bool `json:"stamped,omitempty"`

	// API names the provider-side API surface this entry asked for, in that
	// provider's own naming. Empty means "not set".
	API string `json:"api,omitempty"`

	// Thinking, Reasoning, Cache and Retry are the entry's copies of the
	// provider's native blocks of the same names.
	Thinking  map[string]any `json:"thinking,omitempty"`
	Reasoning map[string]any `json:"reasoning,omitempty"`
	Cache     map[string]any `json:"cache,omitempty"`
	Retry     map[string]any `json:"retry,omitempty"`
}

ModelOverrides carries the configuration of the `core.models` chain entry a request is actually being served by, for every per-entry axis that has no dedicated LLMRequest field of its own.

Like Effort it is an internal carrier, not an operator-facing key: operators write these on a `core.models` entry (engine.ModelConfig) and they arrive here one of two ways — the fallback and fanout coordinators stamp the entry they are actually serving onto the outgoing request, and for the paths no coordinator touches the provider recovers them from the registry itself. engine.StampModelConfig and engine.ResolveModelConfig are the two sides of that, and the only place the precedence rule lives.

Core never looks inside a block. Each map is the provider's own native configuration block, forwarded verbatim; the provider that owns the vocabulary is the only thing that validates or rejects anything. A nil map means "nothing was set", which is deliberately distinct from a set-but-empty block, because the two differ once a role block is merged over a plugin-level one.

Treat every map reachable from here as read-only: the stamping helper copies a block's top level so a request does not alias the loaded configuration, but nested values are shared. A consumer that needs to change something builds its own map.

type OutputChunk

type OutputChunk struct {
	SchemaVersion int `json:"_schema_version"`

	Content string
	TurnID  string
	Index   int
}

OutputChunk represents a single chunk of streamed output.

type Plan

type Plan struct {
	SchemaVersion int `json:"_schema_version"`

	Steps  []PlanStep
	TurnID string
}

Plan represents a multi-step execution plan.

type PlanProgress

type PlanProgress struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID string
	PlanID string
	StepID string
	Status string // "pending", "active", "completed", "failed"
	Detail string
}

PlanProgress reports a step status change during plan execution.

type PlanRequest

type PlanRequest struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	SessionID string
	Input     string
}

PlanRequest asks an active planner to generate a plan for the given input.

type PlanResult

type PlanResult struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID   string
	PlanID   string
	Steps    []PlanResultStep
	Summary  string
	Approved bool
	Source   string // "dynamic" or "static"
}

PlanResult carries a completed plan back to the agent for execution.

type PlanResultStep

type PlanResultStep struct {
	ID           string
	Description  string // user-facing display text
	Instructions string // detailed instructions for the agent; defaults to Description if empty
	Status       string // "pending", "active", "completed", "failed"
	Order        int
}

PlanResultStep is a single step in a planner-generated plan.

type PlanStep

type PlanStep struct {
	Description string
	Status      string // "pending", "active", "completed", "failed", "skipped"
	SpawnID     string
}

PlanStep is a single step within a plan.

SpawnID is set by agents that delegate steps to subagents (the orchestrator's parallel-worker flow); the UI uses it to fold per-worker progress (iteration count, tool calls, terminal totals) into the plan step instead of rendering a parallel "workers" panel. Empty for plans emitted by agents that execute steps inline (planexec, etc.).

type ProviderFallback

type ProviderFallback struct {
	SchemaVersion int `json:"_schema_version"`

	Role           string // model role being resolved (e.g. "balanced")
	FailedProvider string // plugin ID of the provider that failed
	FailedModel    string // model that failed
	Error          string // error description
	NextProvider   string // plugin ID of the fallback provider
	NextModel      string // model being tried next
	Attempt        int    // 0-based index in the fallback chain
}

ProviderFallback notifies IO plugins and observers that a provider switch occurred due to the primary provider failing.

type ProviderFanoutChoose

type ProviderFanoutChoose struct {
	SchemaVersion int `json:"_schema_version"`

	FanoutID  string
	Role      string
	Responses []ProviderFanoutOption
}

ProviderFanoutChoose presents fanout responses for user selection. IO plugins render a picker UI when they receive this event.

type ProviderFanoutChosen

type ProviderFanoutChosen struct {
	SchemaVersion int `json:"_schema_version"`

	FanoutID    string
	ChosenIndex int // -1 means user declined to choose (fall back to "all")
}

ProviderFanoutChosen carries the user's selection from a fanout choice.

type ProviderFanoutComplete

type ProviderFanoutComplete struct {
	SchemaVersion int `json:"_schema_version"`

	FanoutID  string
	Role      string
	Strategy  string
	Succeeded int // number of providers that responded successfully
	Failed    int // number of providers that errored or timed out
}

ProviderFanoutComplete signals that all fanout providers have responded (or the deadline was reached) and the final result has been emitted.

type ProviderFanoutOption

type ProviderFanoutOption struct {
	Index    int
	Provider string
	Model    string
	Content  string // response content preview
	CostUSD  float64
}

ProviderFanoutOption describes one response available for user selection.

type ProviderFanoutResponse

type ProviderFanoutResponse struct {
	SchemaVersion int `json:"_schema_version"`

	FanoutID string
	Provider string // plugin ID that responded
	Model    string
	Success  bool   // false if provider errored or timed out
	Error    string // non-empty on failure
}

ProviderFanoutResponse signals that one provider in a fanout has responded.

type ProviderFanoutStart

type ProviderFanoutStart struct {
	SchemaVersion int `json:"_schema_version"`

	FanoutID string
	Role     string
	Strategy string // "all", "llm_judge", "heuristic", "user"
	Targets  []ProviderFanoutTarget
}

ProviderFanoutStart signals that a fanout request has been initiated.

type ProviderFanoutTarget

type ProviderFanoutTarget struct {
	Provider string // plugin ID
	Model    string
}

ProviderFanoutTarget describes one provider in a fanout request.

type RAGIngest

type RAGIngest struct {
	SchemaVersion int `json:"_schema_version"`

	Path      string
	Namespace string
	Metadata  map[string]string // extra metadata merged into every chunk's metadata

	Provider      string // plugin ID of the ingest plugin that answered
	Chunks        int    // number of chunks upserted
	SkippedCached int    // number of chunks served from the embedding cache
	Error         string
}

RAGIngest is an ingestion request for a single file. Fired as a pointer payload on "rag.ingest"; the ingest plugin fills Provider / Chunks / SkippedCached / Error in place before Emit returns. A notification event "rag.ingest.result" is emitted after the fill so observers (UI, logger) can react without coupling to the caller.

type RAGIngestDelete

type RAGIngestDelete struct {
	SchemaVersion int `json:"_schema_version"`

	Path      string
	Namespace string

	Provider string
	Deleted  int
	Error    string
}

RAGIngestDelete requests removal of all chunks produced from a given path in a given namespace. Fired when a watched file is deleted. Fills in place just like RAGIngest.

type RerankDoc

type RerankDoc struct {
	ID      string
	Content string
}

RerankDoc is one document handed to a cross-encoder reranker. Content is the text the reranker scores against the query; ID is opaque so the caller can map results back to their own structures.

type RerankRequest

type RerankRequest struct {
	SchemaVersion int `json:"_schema_version"`

	Query string
	Docs  []RerankDoc
	TopN  int
	Model string

	Results  []RerankResult
	Provider string
	Error    string
}

RerankRequest asks the active search.reranker provider to re-score a candidate pool against a query and return the top-N. Fired as a pointer payload on "reranker.rerank"; the provider fills Results / Provider / Error in place before Emit returns.

type RerankResult

type RerankResult struct {
	ID    string
	Index int
	Score float32
}

RerankResult is one scored document returned by a reranker. Index is the position the doc held in the input slice, useful when the caller wants to preserve original metadata not echoed in RerankDoc.

type ResponseFormat

type ResponseFormat struct {
	Type   string         `json:"type"`             // "text" | "json_object" | "json_schema"
	Name   string         `json:"name,omitempty"`   // schema name (OpenAI requires this)
	Schema map[string]any `json:"schema,omitempty"` // JSON Schema
	Strict bool           `json:"strict,omitempty"` // enforce strict schema adherence
}

ResponseFormat specifies the desired output format for an LLM request. Providers map this to their native structured output mechanism when supported, or simulate via tool-use-as-schema when not.

type RetrievalContext

type RetrievalContext struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID string
	// ParentTurnID, when set, is the turn a nested loop (subagent,
	// delegate) serves while TurnID is that loop's private tool turn — the
	// ToolCall's ParentTurnID. Consumers index on TurnID and use this only
	// to release the index when the parent turn ends: no agent.turn.end
	// ever names the private turn.
	ParentTurnID string
	Source       string // emitter plugin ID for debug
	Chunks       []RetrievedChunk
}

RetrievalContext is emitted by knowledge_search and memory.vector after each successful retrieval pass so the citation plugin can tally which chunks the LLM had access to. Multiple emissions per turn merge.

Bus event type: "rag.retrieved".

type RetrievedChunk

type RetrievedChunk struct {
	Source    string
	DocID     string
	ChunkIdx  string
	TrustTier string // optional, per Idea 03
}

RetrievedChunk is one piece of context a retrieval plugin pulled for the current turn. The citation plugin uses it as the validation set: cited references must point at chunks that were actually retrieved during the turn or they are dropped.

type SchemaDeregistration

type SchemaDeregistration struct {
	SchemaVersion int `json:"_schema_version"`

	Name   string // schema name to remove
	Source string // plugin ID that registered it
}

SchemaDeregistration is emitted to remove a schema from the registry. Event type: schema.deregister

type SchemaRegistration

type SchemaRegistration struct {
	SchemaVersion int `json:"_schema_version"`

	Name   string         // e.g. "skill.code_review.output"
	Schema map[string]any // JSON Schema
	Source string         // plugin ID that registered it
}

SchemaRegistration is emitted to register an output schema with the schema registry. Event type: schema.register

type SearchRequest

type SearchRequest struct {
	SchemaVersion int `json:"_schema_version"`

	Query      string
	Count      int    // max results; zero means provider default
	SafeSearch string // "off" | "moderate" | "strict"
	Language   string // BCP-47 tag, e.g. "en", "en-US"
	Freshness  string // "day" | "week" | "month" | "" — best-effort, provider-dependent

	// Results / Provider / Error are populated by the provider handler.
	// Callers should treat them as zero on input.
	Results  []SearchResult
	Provider string // plugin ID of the adapter that answered
	Error    string // non-empty when the lookup failed
}

SearchRequest is an outbound web search request. The tool plugin fires it as a pointer payload on "search.request"; the capability-resolved provider fills Results / Provider / Error in place before Emit returns. Mirrors the synchronous fill pattern used by ToolCatalogQuery and HistoryQuery rather than the async LLMRequest/LLMResponse pair, since search is a one-shot lookup with no streaming surface.

type SearchResult

type SearchResult struct {
	Title       string
	URL         string
	Snippet     string
	PublishedAt time.Time // zero when the provider does not supply a date
	Source      string    // provider-specific hostname or domain, optional
}

SearchResult is one hit returned by a search provider.

type SessionFile

type SessionFile struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID string // the session this file belongs to
	// Path is relative to the session root and slash-separated, so it can be
	// used directly as an object key under the session's prefix.
	Path string
	// Size is the file's size after the write.
	//
	// int, not int64, because int is what has always been on the wire: this
	// struct never reached a subscriber, and every subscriber reading the map
	// type-asserts .(int). Widening the field here would widen the payload and
	// turn every one of those assertions into a silent zero -- a wire break
	// dressed up as a type cleanup. The declared int64 was decorative.
	Size int
	// Offset is where the write began: 0 for a whole-file write, the previous
	// length for an append. BytesAdded is how much it added. Together they let
	// a subscriber upload a delta instead of re-reading the whole file; a
	// subscriber that ignores both is still correct, just slower.
	Offset     int
	BytesAdded int
}

SessionFile describes a file event within a session workspace: the payload of session.file.created and session.file.updated.

It goes on the wire as a map rather than as this struct, via Map below. That is not an oversight -- every existing subscriber type-asserts map[string]any, and changing the payload type would break all of them for no gain. The struct is the *definition* of that map, and Map is the only place the keys are spelled.

Before that, this struct was declared and nothing used it, while four call sites each spelled the same keys out by hand. `make check-events` guards structs in this package, so it was guarding a type no subscriber could ever see, and guarding nothing at all about the shape that actually shipped. Two hand-built emitters had already drifted -- one publishing a bare basename as path, one an absolute host path with no session_id -- and the guard could not have caught either.

There is deliberately no Action field. The action is the event type (session.file.created vs .updated), and a duplicate of it in the payload is a second source of truth that can disagree with the first -- which is exactly what nexus.tool.pdf did, hardcoding "created" on every write including updates.

func (SessionFile) Map

func (f SessionFile) Map() map[string]any

Map renders the payload in the form that goes on the bus.

The keys here are the wire contract. TestSessionFileMapCoversEveryField asserts one key per exported field, so a field added to the struct without a key here fails the build rather than shipping a payload that silently omits it; a field renamed or retyped trips `make check-events`, which is what binds the guard to the shape that actually ships.

type SessionInfo

type SessionInfo struct {
	SchemaVersion int `json:"_schema_version"`

	ID          string
	Transport   string
	ConnectedAt time.Time
	UserAgent   string
}

SessionInfo describes a connected session.

type SessionOwnerConflict

type SessionOwnerConflict struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID string `json:"session_id"`

	// HolderHost, HolderPID and HolderInstanceID identify the process that
	// wrote the owner marker found in the store. HolderInstanceID is unique
	// per engine run, which is what makes two containers that happen to share
	// a hostname and a PID still distinguishable.
	HolderHost       string `json:"holder_host"`
	HolderPID        int    `json:"holder_pid"`
	HolderInstanceID string `json:"holder_instance_id"`
	// HolderHeartbeatAt is the last heartbeat the holder recorded, by the
	// holder's own clock.
	HolderHeartbeatAt time.Time `json:"holder_heartbeat_at"`
	// HeartbeatAgeSeconds is how old that heartbeat looked from here. Carried
	// alongside the timestamp because the two clocks are not the same one, and
	// the age is the number the staleness decision was actually made on.
	HeartbeatAgeSeconds float64 `json:"heartbeat_age_seconds"`

	// LocalHost, LocalPID and LocalInstanceID identify this process — the one
	// that went ahead anyway.
	LocalHost       string `json:"local_host"`
	LocalPID        int    `json:"local_pid"`
	LocalInstanceID string `json:"local_instance_id"`
}

SessionOwnerConflict reports that a second host appears to hold the session this process just opened against the object store.

Detection, not prevention

Single-writer is assumed by the object-store design and deliberately not enforced. Nothing about this event refuses, blocks, retries or fences: by the time it is emitted the engine has already claimed the session and is running normally. It exists because the failure it describes is otherwise completely silent — two hosts snapshot the same session at their own turn boundaries and the loser's whole tree, per-plugin databases included, is overwritten with no error anywhere. A subscriber that wants to act (page an operator, stop the run) has to do so itself.

Emitted at most once per run, and only when an object-store backend is configured.

type SessionSnapshotRequest

type SessionSnapshotRequest struct {
	SchemaVersion int `json:"_schema_version"`

	// Reason is free-form and appears in the log line and in the resulting
	// SessionSnapshotResult, so an operator can tell one caller from another.
	Reason string `json:"reason,omitempty"`
}

SessionSnapshotRequest asks the engine to snapshot the whole session tree to the configured object store and wait for it to be durable.

The engine snapshots at every turn boundary on its own, so nothing needs to emit this in a normal run. It exists for the two cases the turn boundary does not cover: an embedder driving the engine outside an agent loop, and a custom agent that does not emit agent.turn.end. Ignored — not an error — when no object-store backend is configured.

type SessionSnapshotResult

type SessionSnapshotResult struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID string `json:"session_id"`
	// Trigger is what caused the snapshot: "turn", "shutdown", "request" or
	// "retry" (the recovery worker healing a degraded store).
	Trigger string `json:"trigger"`
	// Sequence is the per-run snapshot counter, starting at 1.
	Sequence uint64 `json:"sequence"`
	// Generation is the session's commit generation: unlike Sequence it is
	// seeded from the manifest the previous holder of the session committed,
	// so it keeps increasing across a resume onto a different host. It is the
	// stamp the commit marker and the per-object manifest in the bucket both
	// carry, so a subscriber can name the exact remote state a snapshot
	// produced. Zero when a snapshot failed before it could claim one.
	Generation uint64 `json:"generation"`
	// TurnID is the turn whose boundary triggered the snapshot. Empty for the
	// shutdown and request triggers.
	TurnID string `json:"turn_id,omitempty"`
	// Objects is the size of the committed object set — every object the
	// snapshot asserts is durably present, excluding the commit marker. It
	// counts objects that immutable-skip did not re-upload, because they are
	// still part of the stored session.
	Objects int `json:"objects"`
	// Bytes is the total size of those objects: how big the stored session is.
	Bytes int64 `json:"bytes"`
	// ObjectsUploaded and BytesUploaded are the share of the set this snapshot
	// actually transferred. This, not Bytes, is the per-turn cost.
	ObjectsUploaded int   `json:"objects_uploaded"`
	BytesUploaded   int64 `json:"bytes_uploaded"`
	// ObjectsSkipped and BytesSkipped are what immutable-skip saved: files
	// whose identity proves they cannot have changed (sealed journal segments,
	// content-addressed blobs) and which the store was listed to confirm it
	// already holds.
	ObjectsSkipped int   `json:"objects_skipped"`
	BytesSkipped   int64 `json:"bytes_skipped"`
	// DurationMs is the wall time of the whole snapshot, staging included.
	DurationMs float64 `json:"duration_ms"`
	// OK reports whether the snapshot was made durable. When false the remote
	// commit marker still names the previous snapshot.
	OK bool `json:"ok"`
	// ErrorMessage is empty on success.
	ErrorMessage string `json:"error,omitempty"`
}

SessionSnapshotResult reports the outcome of one whole-tree snapshot.

Emitted after the snapshot has either been made durable or failed, so a subscriber observing OK can rely on the remote copy being restorable. Not emitted at all when no object-store backend is configured.

type SessionStorageDegraded

type SessionStorageDegraded struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID string `json:"session_id"`
	// Backend is the registered backend name from core.object_store.backend.
	Backend string `json:"backend"`
	// FailurePolicy is the resolved core.object_store.failure_policy:
	// "degrade" or "strict".
	FailurePolicy string `json:"failure_policy"`

	// Since is when the episode opened — the first failure, not this event.
	Since time.Time `json:"since"`
	// ConsecutiveFailures is how many persistence failures the episode has
	// seen so far.
	ConsecutiveFailures uint64 `json:"consecutive_failures"`

	// QueuedPushes is the depth of the bounded retry queue at emission.
	QueuedPushes int `json:"queued_pushes"`
	// DroppedPushes counts individual pushes discarded because the queue was
	// full. A drop is not lost work: it escalates to a whole-tree snapshot,
	// which re-uploads everything the store does not already hold.
	DroppedPushes uint64 `json:"dropped_pushes"`
	// SnapshotPending reports that a whole-tree snapshot is owed — the
	// backstop that covers anything the queue could not.
	SnapshotPending bool `json:"snapshot_pending"`

	// TurnsBlocked reports that further input is being refused. Only ever true
	// under failure_policy: strict.
	TurnsBlocked bool `json:"turns_blocked"`

	// Error is the most recent failure's message.
	Error string `json:"error,omitempty"`
}

SessionStorageDegraded reports that the configured object store stopped accepting this session's state, and that the engine is running against the local working copy while it retries.

Emitted at most once per outage — an "episode" runs from the first failure to the first success after it, so a subscriber counts outages rather than failed requests — and only when `core.object_store.backend` names a backend. `session.storage.recovered` closes the episode.

What it means under each failure policy

Under `degrade` the session keeps taking turns. The honest caveat is that the durability guarantee is *not* being met for as long as this state lasts, even though nothing is failing: turns the user watched happen exist only on local disk. That is the trade the operator chose.

Under `strict` `TurnsBlocked` is true and every subsequent `io.input` is vetoed until the state is durably stored. Note carefully what that does and does not mean: the turn that hit the outage ALREADY RAN — its output was streamed, its tools executed and its side effects are in the world. The engine cannot un-run it. What `strict` guarantees is that no *further* turn runs against state whose predecessor is not stored, and that the divergence is never silent.

Recovery is automatic under both policies. Nothing here needs an operator.

type SessionStorageRecovered

type SessionStorageRecovered struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID     string `json:"session_id"`
	Backend       string `json:"backend"`
	FailurePolicy string `json:"failure_policy"`

	// DegradedForSeconds is the wall time from the first failure to recovery.
	DegradedForSeconds float64 `json:"degraded_for_seconds"`
	// Failures is how many persistence failures the episode saw in total.
	Failures uint64 `json:"failures"`
	// RetryAttempts is how many backoff attempts the recovery worker made.
	// Zero when an ordinary turn-boundary snapshot healed it first.
	RetryAttempts uint64 `json:"retry_attempts"`
	// DrainedPushes is how many deferred pushes the retries got through.
	DrainedPushes uint64 `json:"drained_pushes"`
	// DroppedPushes is how many were discarded on queue overflow and covered
	// by a whole-tree snapshot instead.
	DroppedPushes uint64 `json:"dropped_pushes"`
}

SessionStorageRecovered closes the episode a SessionStorageDegraded opened: the backlog drained, the session is durably stored again, and under `strict` input is accepted again.

Emitted only when the matching degraded event went out, so the two always pair. Recovery needs no operator action — the retry worker gets there on its own, and an outage that heals before the next turn boundary is closed by that turn's ordinary snapshot with no retry at all.

type SessionTagDeleteRequest

type SessionTagDeleteRequest struct {
	SchemaVersion int `json:"_schema_version"`

	Key string
}

SessionTagDeleteRequest is the payload of before:session.tag.delete — a request to remove one key from SessionMeta.Labels. Same reserved-key rejection rule and same single core handler as SessionTagSetRequest; see its doc comment.

type SessionTagDeleted

type SessionTagDeleted struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID string
	Key       string
}

SessionTagDeleted announces that a session label was removed — the general or reserved path, same as SessionTagSet. It is also the end-of-run signal for AG-UI's identity binding: a transport that set `_principal_id` on run start deletes it on run end, and this is what a subscriber watching for "this principal's run finished" observes.

type SessionTagSet

type SessionTagSet struct {
	SchemaVersion int `json:"_schema_version"`

	SessionID string
	Key       string
	Value     string
}

SessionTagSet announces that a session label was written — the general (bus-request) path via before:session.tag.set, or the reserved (direct-Go-call) path via SessionWorkspace.SetReservedLabel. Both routes end at the same internal apply-and-announce step, so this is the one channel anything watching session labels needs to subscribe to, regardless of which path produced the write.

type SessionTagSetRequest

type SessionTagSetRequest struct {
	SchemaVersion int `json:"_schema_version"`

	Key   string
	Value string
}

SessionTagSetRequest is the payload of before:session.tag.set — a request to write one key/value pair into SessionMeta.Labels.

This rides the bus as the struct itself, not a hand-spelled map: it is carried as VetoablePayload.Original (an any), the same way events.LLMRequest rides before:llm.request, and there is no legacy map[string]any subscriber to keep compatible the way SessionFile has.

The one and only handler for this event lives in the core engine (installSessionTagHandlers in pkg/engine): it rejects Key outright when it matches the reserved ("_"-prefixed) namespace — see engine.IsReservedLabelKey — and otherwise applies the write and fires SessionTagSet. There is no other sanctioned way to reach Labels through the bus.

type ShutdownReason

type ShutdownReason struct {
	SchemaVersion int `json:"_schema_version"`

	Reason string // "user", "error", "signal"
	Error  error
}

ShutdownReason describes why the system is shutting down.

type SkillActivation

type SkillActivation struct {
	SchemaVersion int `json:"_schema_version"`

	Name        string
	RequestedBy string // plugin ID or "user"
}

SkillActivation requests activation of a skill.

type SkillCatalog

type SkillCatalog struct {
	SchemaVersion int `json:"_schema_version"`

	Skills []SkillSummary
}

SkillCatalog lists all available skills.

type SkillContent

type SkillContent struct {
	SchemaVersion int `json:"_schema_version"`

	Name      string
	Body      string
	Resources []string
	Scope     string
	BaseDir   string
	// Runtime selects the codeexec runtime for this skill's helpers.
	// Empty defaults to "yaegi" at the consumer for backwards compatibility;
	// "wasm" routes the skill's run_code through ctx.Sandbox when codeexec
	// is configured with compiler: yaegi-wasm.
	Runtime string
}

SkillContent carries the full content of an activated skill.

type SkillRef

type SkillRef struct {
	SchemaVersion int `json:"_schema_version"`

	Name string
}

SkillRef is a lightweight reference to a skill by name.

type SkillResourceData

type SkillResourceData struct {
	SchemaVersion int `json:"_schema_version"`

	SkillName string
	Path      string
	Content   []byte
	MimeType  string
}

SkillResourceData carries the content of a skill resource.

type SkillResourceReq

type SkillResourceReq struct {
	SchemaVersion int `json:"_schema_version"`

	SkillName string
	Path      string
}

SkillResourceReq requests a specific resource from a skill.

type SkillSummary

type SkillSummary struct {
	Name        string
	Description string
	Location    string
	Scope       string // "project", "user", "builtin", "config"
	Class       string // Semantic class for progressive discovery.
	Subclass    string // Optional grouping within class.
}

SkillSummary provides a brief description of a skill.

type StatusUpdate

type StatusUpdate struct {
	SchemaVersion int `json:"_schema_version"`

	State  string // "idle", "thinking", "tool_running", "streaming"
	Detail string
	ToolID string
}

StatusUpdate describes the current operational state of the agent.

type StreamChunk

type StreamChunk struct {
	SchemaVersion int `json:"_schema_version"`

	Content  string
	ToolCall *ToolCallRequest // partial tool call
	Index    int
	TurnID   string
}

StreamChunk is a single chunk from a streaming LLM response.

type StreamEnd

type StreamEnd struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID       string
	Usage        Usage
	FinishReason string
}

StreamEnd signals the completion of a streaming LLM response.

type StreamHold

type StreamHold struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	RequestID string
	// Held is the number of bytes currently withheld. Zero on the resume
	// edge.
	Held int
	// Reason is the handler-supplied explanation, when one was given. Never
	// contains the withheld text — see the warning on
	// engine.PublishLLMResponse about routing blocked content through a
	// reason string.
	Reason string
	// Resumed distinguishes the edge out of a hold from the edge into one.
	Resumed bool
}

StreamHold announces both edges of a suspended stream on "llm.stream.hold". A UI that renders nothing while a gate is deliberating is indistinguishable from a hung turn, so the publisher says so rather than simply going quiet.

Resumed is false on the edge into a hold and true on the edge out of one. Every hold is followed by exactly one of: a resume, an llm.stream.retract, or the turn's llm.stream.end (a hold still standing when the stream closes is released by the publisher's final flush, which emits the resume edge).

type StreamRef

type StreamRef struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID   string
	Metadata map[string]any
}

StreamRef marks the start of a streaming response.

type StreamRetract

type StreamRetract struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	RequestID string
	// ReleasedLen is how many bytes of this turn's text had already been
	// emitted when the block landed — the size of the residue a transport is
	// being asked to disown.
	ReleasedLen int
	// Reason is the vetoing handler's VetoResult.Reason. Like every veto
	// reason it must not quote the blocked text.
	Reason string
}

StreamRetract is published on "llm.stream.retract" when a before:llm.stream.chunk handler blocks a stream mid-flight. It tells transports that the text they have rendered for this turn is disowned.

What a transport can do with it varies, and the difference is worth being honest about. A transport that owns its render buffer (TUI, browser) can erase the released prefix outright. A transport speaking a protocol with no retraction verb can only signal: nexus.io.agui emits an AG-UI CustomEvent and closes the text message; nexus.io.a2a replaces the streamed artifact in place, which the A2A artifact-update semantics permit. None of them can recall what a human already read.

That residue is bounded, not eliminated, and bounding it is what StreamSegment.Hold is for: text a handler held was never released, so a gate that holds its full pattern window has nothing to retract.

type StreamSegment

type StreamSegment struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	RequestID string
	// Index is the sequence number the resulting llm.stream.chunk will carry.
	Index int

	// Released is every byte of this turn's text already emitted as
	// llm.stream.chunk, post-redaction. It is lookbehind only: it has left
	// the engine and mutating it does nothing. Handlers scan Full() rather
	// than Content so a pattern spanning the boundary is still visible.
	Released string

	// Content is the candidate release. Handlers may rewrite it to redact.
	Content string

	// Hold is the number of trailing bytes of Content to withhold. The
	// publisher takes the maximum across handlers and clamps it to
	// len(Content). Bytes held are re-offered on the next segment.
	Hold int
}

StreamSegment is the vetoable payload of "before:llm.stream.chunk". It is offered to handlers by engine.StreamPublisher once per candidate text release, before any of that text reaches the bus as an llm.stream.chunk.

This is the streaming counterpart of before:llm.response, and it exists because a veto at end-of-stream cannot unsay text a UI has already rendered. A handler here adjudicates text that has not left the engine yet, so a block is real prevention rather than a retraction — including for transports whose wire protocol has no retraction verb.

Handlers have four moves, in increasing severity:

  • Pass. Return without touching the payload. Content is emitted verbatim; with no handler subscribed this is byte-for-byte the chunking the provider produced.

  • Redact. Rewrite Content in place. The rewritten text is what the bus (and every UI) sees; the stream continues.

  • Suspend. Set Hold to the number of trailing bytes of Content that must not be released yet. The publisher withholds them and re-offers them, prepended to the next delta, on the following segment. This is how a handler defers a decision it cannot yet make — a trailing "123-45-" that may or may not become a credit card number — without either leaking it or blocking the whole turn. A handler may hold the same text across arbitrarily many segments, but only while segments keep arriving: the publisher's final flush ignores Hold, so a handler still undecided at end of stream must release or block, not defer.

  • Block. Set VetoablePayload.Veto. Nothing more is emitted for this turn: the publisher drops the held text, emits llm.stream.retract, and swallows every later delta. The provider still accumulates the real text and still publishes it through engine.PublishLLMResponse, so the response-level gate substitutes as it does today.

Because Hold is honored before anything is emitted, a handler that holds a window at least as long as its longest pattern can never be defeated by a pattern straddling a delta boundary: the publisher only releases a byte once the handler has seen that byte plus its full hold window.

func (*StreamSegment) Full

func (s *StreamSegment) Full() string

Full returns the turn's text as it would read if Content were released: everything already emitted, plus the candidate. Handlers scan this so a pattern straddling a delta boundary is matched whole, and use PendingOffset to tell which matches they can still act on.

func (*StreamSegment) HoldFrom

func (s *StreamSegment) HoldFrom(i int)

HoldFrom asks the publisher to withhold Content from byte offset i to the end. It is the form handlers actually want — "defer everything from where the suspicious run starts" — and it composes, since the publisher keeps the largest hold any handler asked for. Offsets are into Content, not Full(); out-of-range values are clamped.

func (*StreamSegment) PendingOffset

func (s *StreamSegment) PendingOffset() int

PendingOffset is the index into Full() at which Content begins. A match ending at or after this offset is still preventable; one ending before it has already been emitted and only a block (plus a best-effort llm.stream.retract) can address it.

type SubagentComplete

type SubagentComplete struct {
	SchemaVersion int `json:"_schema_version"`

	SpawnID      string
	Result       string
	Error        string
	Iterations   int
	TokensUsed   Usage
	CostUSD      float64
	ParentTurnID string
}

SubagentComplete signals that a subagent has finished execution.

type SubagentIteration

type SubagentIteration struct {
	SchemaVersion int `json:"_schema_version"`

	SpawnID      string
	Iteration    int
	Content      string            // assistant text content, if any
	ToolCalls    []ToolCallRequest // tool calls made this iteration
	ParentTurnID string
}

SubagentIteration reports a single subagent iteration for observability.

ParentTurnID echoes the spawning agent's turn so UI bridges can group iteration events with the started/complete events for the same worker. Without it, frontends that key panels by parent_turn_id end up fragmenting a single worker's lifecycle across multiple UI elements.

type SubagentSpawn

type SubagentSpawn struct {
	SchemaVersion int `json:"_schema_version"`

	SpawnID      string
	Task         string   // what the subagent should accomplish
	SystemPrompt string   // optional system prompt override
	Tools        []string // allowed tool names (empty = all available)
	ModelRole    string   // model role override (empty = plugin default)
	ParentTurnID string
	ParentDepth  int
}

SubagentSpawn requests spawning a new subagent.

ParentDepth is the causation depth of the spawning context (0 for a top-level agent, N for a subagent nested at depth N). The subagent plugin pushes a CausationContext with Depth = ParentDepth+1 onto its worker goroutine so emitted events carry accurate AgentID and Depth provenance.

type SubagentStarted

type SubagentStarted struct {
	SchemaVersion int `json:"_schema_version"`

	SpawnID      string
	Task         string
	ParentTurnID string
}

SubagentStarted signals that a subagent has begun execution.

type ThinkingStep

type ThinkingStep struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	Source    string // plugin ID that generated this thinking step
	Content   string
	Phase     string // "planning", "executing", "reasoning"
	Timestamp time.Time
	// Index is the sequence number of this step within a single TurnID.
	// Providers that emit one event per logical thinking block (or chunk
	// thereof) use this to order steps for reconstruction; planners that
	// emit a single thinking event per turn leave it at 0.
	Index int
}

ThinkingStep represents an intermediate reasoning step visible to the user.

type TickInfo

type TickInfo struct {
	SchemaVersion int `json:"_schema_version"`

	Sequence int
	Time     time.Time
}

TickInfo carries periodic tick metadata.

type ToolCall

type ToolCall struct {
	SchemaVersion int `json:"_schema_version"`

	ID        string
	Name      string
	Arguments map[string]any
	// TurnID correlates this call's tool.result back to the loop that
	// issued it. Nested loops (subagent, delegate) use a private turn
	// ("subagent_<id>", "delegate_<id>") here so their results never
	// collide with the parent's — a turn no transport ever saw start.
	TurnID string
	// ParentTurnID, when set, is the turn this call is BOUND to for
	// anything a transport scopes by turn — chiefly a HITL request raised
	// on the call (approval_policy, ask_user). Nested loops set it to the
	// turn they serve, because a hitl.requested carrying the private
	// TurnID above is dropped by turn-scoped transports (nexus.io.agui)
	// and the parent run never sees the approval. Empty for calls issued
	// directly by a top-level loop, where TurnID already is that turn.
	// Read it through BindingTurnID, never directly.
	ParentTurnID string
	// ParentCallID, when set, marks this call as internal to another tool
	// (e.g. dispatched by a run_code script). Conversation history omits
	// these so the LLM never sees tool_use_ids it didn't originate — gates
	// and observers still fire on the bus as usual.
	ParentCallID string
	// Sequence is the LLM-returned position of this call within its batch
	// (0-based). Set by the agent when a single LLM response contains
	// multiple tool calls; lets observers reorder completion-order events
	// back into request order under parallel dispatch.
	Sequence int
}

ToolCall represents a tool invocation.

func (ToolCall) BindingTurnID added in v0.31.0

func (tc ToolCall) BindingTurnID() string

BindingTurnID is the turn a HITL request (or any other turn-scoped, transport-visible emission) raised on this call should carry: ParentTurnID when a nested loop set it, otherwise TurnID. It is NOT the key for matching tool results — that stays TurnID.

type ToolCallRequest

type ToolCallRequest struct {
	ID        string
	Name      string
	Arguments string // JSON string
}

ToolCallRequest represents a tool invocation requested by the LLM.

type ToolCatalogQuery

type ToolCatalogQuery struct {
	SchemaVersion int `json:"_schema_version"`

	// Tools is filled by the handler. Caller should treat it as nil on
	// input; a nil result after Emit means no catalog plugin answered.
	Tools []ToolDef
}

ToolCatalogQuery is a synchronous request for the currently registered tool definitions. Emitted as a pointer payload on "tool.catalog.query"; the handler fills Tools in place before Emit returns. Same pattern as HistoryQuery — no correlation IDs, no round-trip via a response event.

type ToolChoice

type ToolChoice struct {
	Mode string `json:"mode"`           // "auto" | "required" | "none" | "tool"
	Name string `json:"name,omitempty"` // tool name when Mode == "tool"
}

ToolChoice controls which tools the LLM is allowed or required to use.

type ToolDef

type ToolDef struct {
	Name         string
	Description  string
	Parameters   map[string]any // JSON Schema for inputs
	OutputSchema map[string]any // Optional JSON Schema for structured outputs. When
	// set, the tool commits to populating ToolResult.OutputStructured with a
	// value that validates against this schema. Consumers like run_code use
	// it to generate typed bindings; omit for tools that only produce text.
	Class    string   // Semantic class (e.g. "filesystem", "memory"). Empty = classless.
	Subclass string   // Optional grouping within class (e.g. "read", "write").
	Tags     []string // Cross-cutting metadata for filtering.
}

ToolDef describes a tool available to the LLM.

func (ToolDef) HasTag added in v0.31.0

func (d ToolDef) HasTag(tag string) bool

HasTag reports whether the tool definition carries tag.

type ToolFilter

type ToolFilter struct {
	Include []string `json:"include,omitempty"` // only these tools (empty = all)
	Exclude []string `json:"exclude,omitempty"` // remove these tools
}

ToolFilter restricts which tools are available for an LLM request. Include and Exclude are mutually exclusive; Include takes precedence.

type ToolResult

type ToolResult struct {
	SchemaVersion int `json:"_schema_version"`

	ID         string // matches ToolCall.ID
	Name       string
	Output     string
	Error      string
	OutputFile string // optional: file written to session workspace
	OutputData []byte // optional: binary data
	// OutputStructured carries typed result data when the tool declared an
	// OutputSchema in its ToolDef. Consumers that care about types (e.g.
	// run_code's typed bindings) prefer this over parsing Output.
	// Content should validate against the tool's declared OutputSchema.
	OutputStructured map[string]any

	// OutputParts carries multimodal content the tool produced (image,
	// audio, document, video). When non-empty, the memory plugin copies
	// these into the resulting tool-role Message.Parts so the next LLM
	// request includes the multimodal content alongside (or in place of)
	// Output. Empty for text-only tools.
	//
	// Large payloads should be stored via pkg/engine/blobs and referenced
	// here as `MessagePart{URI: "nexus-blob:<sha>", MimeType: "..."}` so
	// the journal stays compact; small payloads can ride inline as Data.
	// Provider plugins resolve nexus-blob URIs at request-assembly time.
	OutputParts []MessagePart

	TurnID string
}

ToolResult carries the outcome of a tool invocation.

type ToolTimeout

type ToolTimeout struct {
	SchemaVersion int `json:"_schema_version"`

	ToolName string
	CallID   string
	Timeout  time.Duration
	Override string // e.g. "nexus.gate.tool_timeout.per_tool.<name>"
	TurnID   string
}

ToolTimeout signals that a tool invocation exceeded its configured per-call deadline. Emitted by nexus.gate.tool_timeout alongside a synthetic tool.result error so observers can distinguish a tool's own timeout from a gate-enforced one. Override names the exact YAML key the operator should set to lift the limit.

type TurnInfo

type TurnInfo struct {
	SchemaVersion int `json:"_schema_version"`

	TurnID    string
	Iteration int
	SessionID string
}

TurnInfo describes a single agent turn.

type Usage

type Usage struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
	ReasoningTokens  int // thinking/reasoning tokens (Gemini 2.5 thoughtTokenCount, etc.)
	CachedTokens     int // tokens served from a prompt cache (billed at a discount)
	CacheWriteTokens int // tokens written into a prompt cache (billed at a premium over plain input)

	// ModalityBreakdown carries per-modality token counts when the provider
	// exposes them. Keys are stable lowercase modality identifiers
	// ("text", "image", "audio", "video", "document"); each key value is the
	// number of tokens the provider attributed to that modality across the
	// turn (input + output combined when a provider does not split them).
	//
	// Empty when the provider does not report modality breakdowns
	// (Anthropic rolls image / document tokens into input_tokens) or when the
	// request was text-only.
	//
	// Cost-attribution consumers (cost CLI, multi-dim budget gate) read this
	// to bill image / audio turns separately from text. Additive map; new
	// modality keys can be introduced without an LLMResponse schema bump.
	ModalityBreakdown map[string]int
}

Usage tracks token consumption for an LLM call.

type UserInput

type UserInput struct {
	SchemaVersion int `json:"_schema_version"`

	Content   string
	Files     []FileAttachment
	SessionID string

	// PreloadMessages, when non-empty, are appended to memory.history in
	// order before Content. Each message keeps its declared Role so
	// assistant-role priming, few-shot examples, or recorded transcripts
	// can be replayed without abusing the user channel. Multimodal parts
	// ride on Message.Parts. Memory plugins consume PreloadMessages first,
	// then fall through to the existing Content append + agent trigger.
	//
	// Added in v2 for MCP prompt expansion; also useful for scripted
	// oneshot IO and replay.
	PreloadMessages []Message

	// Headers carries the X-Nexus-* request headers of the HTTP request that
	// opened this turn, keyed by normalized name (`X-Nexus-Tenant-ID` ->
	// `tenant-id`). See pkg/nexusheaders for the convention and the bounds,
	// and engine.SessionWorkspace.SetRequestHeaders for the parallel binding
	// every web transport performs before emitting this event.
	//
	// Nil for a transport with no HTTP request behind it (TUI, oneshot)
	// and for a web request that carried no X-Nexus-* header. A handler must
	// treat it as a hint from the caller, never as an authenticated claim:
	// nothing verifies these values, which is why the engine binds them into
	// the reserved, prompt-invisible label namespace rather than the general
	// one.
	//
	// Added in v3.
	Headers map[string]string
}

UserInput represents input submitted by the user.

SchemaVersion bumped to 2 when PreloadMessages was added, and to 3 when Headers was. Producers that only set the older fields remain forward- compatible: every added field is an optional map or slice, so a v1 or v2 emitter still parses cleanly into the v3 struct (the newer fields are nil). Consumers that emit fresh v3 payloads stamp UserInputVersion.

type VectorDelete

type VectorDelete struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string
	IDs       []string

	Provider string
	Error    string
}

VectorDelete requests removal of documents by ID from a namespace. Fired as a pointer payload on "vector.delete".

type VectorDoc

type VectorDoc struct {
	ID       string
	Vector   []float32
	Content  string
	Metadata map[string]string
}

VectorDoc is a single document in a vector store: opaque ID, the embedding vector, the original textual content (optional — stores may persist it for re-ranking or provenance), and string-keyed metadata. Metadata is scoped to map[string]string to match the common denominator across backends (chromem, sqlite-vec, pgvector, Qdrant all support string→string).

type VectorMatch

type VectorMatch struct {
	ID         string
	Content    string
	Metadata   map[string]string
	Similarity float32 // cosine similarity in [-1, 1] when the backend uses it
}

VectorMatch is one hit returned by a nearest-neighbor query.

type VectorMemoryStore

type VectorMemoryStore struct {
	SchemaVersion int `json:"_schema_version"`

	Content  string
	Source   string
	Metadata map[string]string // optional extra metadata, merged into the stored doc

	Provider string
	Error    string
}

VectorMemoryStore is an explicit request to persist a piece of salient content into the vector memory for this agent. Fired as a pointer payload on "memory.vector.store"; the memory.vector plugin fills Provider / Error in place before Emit returns.

Source is a short label recorded in metadata ("user", "agent", "compaction", "tool", …) and used for filtering on retrieval.

type VectorNamespaceDrop

type VectorNamespaceDrop struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string

	Provider string
	Error    string
}

VectorNamespaceDrop requests removal of an entire namespace. Fired as a pointer payload on "vector.namespace.drop". Idempotent: dropping an unknown namespace is not an error.

type VectorQuery

type VectorQuery struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string
	Vector    []float32
	K         int
	Filter    map[string]string // exact-match metadata filter; empty means no filter

	Matches  []VectorMatch
	Provider string
	Error    string
}

VectorQuery requests a nearest-neighbor lookup in a namespace. Fired as a pointer payload on "vector.query"; the provider fills Matches / Provider / Error in place before Emit returns.

type VectorUpsert

type VectorUpsert struct {
	SchemaVersion int `json:"_schema_version"`

	Namespace string
	Docs      []VectorDoc

	Provider string
	Error    string
}

VectorUpsert requests a batch insert/replace of documents into a namespace. Fired as a pointer payload on "vector.upsert"; the capability-resolved provider fills Provider / Error in place before Emit returns.

Upsert semantics: documents with an ID already present in the namespace are replaced. Adapters without native upsert implement this as delete-then-add.

type VoiceAudioInputChunk

type VoiceAudioInputChunk struct {
	SchemaVersion int `json:"_schema_version"`

	// TurnID groups consecutive chunks belonging to the same utterance.
	TurnID string
	// Sequence is the 0-based ordinal of this chunk within the turn.
	Sequence int
	// AudioBase64 is the base64-encoded raw audio frame. Decoders should
	// trust MimeType for the container/codec; this field is opaque.
	AudioBase64 string
	// MimeType identifies the container/codec, e.g. "audio/webm;codecs=opus".
	MimeType string
	// Final marks the last chunk of a turn. Consumers should treat any
	// chunks emitted after Final=true as the start of a new turn.
	Final bool
}

VoiceAudioInputChunk carries a chunk of microphone-captured audio from a realtime client. Phase 4 (nexus.io.voice) consumes these, runs voice- activity detection, and hands a final segment to ASR. The audio frame is base64-encoded so the chunk can ride a JSON envelope without any binary framing concerns; MIME type is supplied by the producer (typically "audio/webm;codecs=opus" from a browser MediaRecorder, or "audio/wav" from a native client).

Bus event type: "voice.audio.input.chunk".

type VoiceAudioOutputChunk

type VoiceAudioOutputChunk struct {
	SchemaVersion int `json:"_schema_version"`

	// TurnID correlates the output with the assistant turn it speaks.
	TurnID string
	// Sequence is the 0-based ordinal of this chunk within the turn.
	Sequence int
	// AudioBase64 is the base64-encoded raw audio frame.
	AudioBase64 string
	// MimeType identifies the container/codec the producer chose.
	MimeType string
	// Final marks the last chunk of a turn.
	Final bool
}

VoiceAudioOutputChunk is emitted by Phase 4 (nexus.io.voice) when a TTS stream produces audio for a given assistant response. The realtime IO plugin forwards these to connected clients for playback.

Bus event type: "voice.audio.output.chunk".

type WorkflowProgress

type WorkflowProgress struct {
	SchemaVersion int `json:"_schema_version"`

	// WorkflowID identifies the producer (plugin instance ID, e.g.
	// "nexus.workflows.icm" or "nexus.workflows.icm/script").
	WorkflowID string `json:"workflow_id"`
	// WorkflowName is a human-readable label for the workflow as a
	// whole (the workspace name for ICM, the plan summary for planexec).
	WorkflowName string `json:"workflow_name,omitempty"`
	// RunID identifies this particular run within the workflow.
	RunID string `json:"run_id"`

	// Stage is the machine ID of the current stage (e.g. "04_assemble").
	// Empty when Status is Started before any stage dispatches, or
	// Completed/Halted at run end.
	Stage string `json:"stage,omitempty"`
	// StageLabel is the human-readable display string for the stage.
	StageLabel string `json:"stage_label,omitempty"`
	// StageIndex is the 1-based position of the current stage.
	StageIndex int `json:"stage_index,omitempty"`
	// StageTotal is the total number of stages in this workflow.
	StageTotal int `json:"stage_total,omitempty"`

	// Iteration is the current loop iteration within Stage. 0 when the
	// stage is not iterating.
	Iteration int `json:"iteration,omitempty"`
	// MaxIterations is the loop cap for the current stage. 0 when
	// non-looping.
	MaxIterations int `json:"max_iterations,omitempty"`

	// Turn is the current inner turn within the current stage
	// invocation. 0 when not tracked.
	Turn int `json:"turn,omitempty"`
	// MaxTurns is the inner-turn cap. 0 when non-bounded.
	MaxTurns int `json:"max_turns,omitempty"`

	// ItemsDone / ItemsTotal report fan-out progress; both 0 when the
	// stage is not a fan-out.
	ItemsDone  int `json:"items_done,omitempty"`
	ItemsTotal int `json:"items_total,omitempty"`
	// CurrentItem is the ID of the most recently completed item, when
	// fan-out applies.
	CurrentItem string `json:"current_item,omitempty"`

	// Status is the lifecycle marker. One of WorkflowStatus* constants
	// above. Required.
	Status string `json:"status"`
	// Detail is a short free-form one-liner suitable for display.
	Detail string `json:"detail,omitempty"`
	// Failures lists predicate names that caused the most recent
	// non-converging iteration or turn. Empty when not applicable.
	Failures []string `json:"failures,omitempty"`
}

WorkflowProgress is a workflow-agnostic progress payload that any multi-stage workflow plugin can emit. Subscribers — typically IO plugins — render a dedicated workflow status surface (a sticky panel in the TUI right rail, an indicator chip in the browser) from a single canonical event class, regardless of which plugin produced the event.

ICM emits WorkflowProgress *alongside* its detailed icm.* events: the icm.* stream feeds the scrollback audit trail, WorkflowProgress feeds the dedicated panel. Future workflow plugins (planexec, orchestrator) can emit just this event and inherit the same UI treatment without a per-plugin event subscription.

Directories

Path Synopsis
Package compat carries field-level migrations between event-payload schema versions.
Package compat carries field-level migrations between event-payload schema versions.

Jump to

Keyboard shortcuts

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