network

package
v0.3.0-beta.24 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package network defines the Compozy Network v0 protocol surface shared by the transport, router, and delivery layers.

Index

Constants

View Source
const (
	// AuditDirectionSent records a successful outbound publish.
	AuditDirectionSent = "sent"
	// AuditDirectionReceived records an accepted inbound delivery.
	AuditDirectionReceived = "received"
	// AuditDirectionRejected records a rejected envelope.
	AuditDirectionRejected = "rejected"
	// AuditDirectionDelivered records a completed local delivery.
	AuditDirectionDelivered = "delivered"
)
View Source
const (
	// ExtensionKeyCapabilitiesBrief carries the compact peer capability projection.
	ExtensionKeyCapabilitiesBrief = "compozy.capabilities_brief"
	// ExtensionKeyInclude requests optional envelope projections.
	ExtensionKeyInclude = "compozy.include"
	// ExtensionKeyCapabilityIDs narrows capability discovery to selected IDs.
	ExtensionKeyCapabilityIDs = "compozy.capability_ids"
	// ExtensionKeyCapabilityCatalog carries the rich capability projection.
	ExtensionKeyCapabilityCatalog = "compozy.capability_catalog"
	// ExtensionKeyWorkflowID correlates an envelope with its workflow.
	ExtensionKeyWorkflowID = "compozy.workflow_id"
	// ExtensionKeyHandoffVersion records the handoff contract version.
	ExtensionKeyHandoffVersion = "compozy.handoff_version"
	// ExtensionKeyHandoffDigest records the handoff content digest.
	ExtensionKeyHandoffDigest = "compozy.handoff_digest"
	// ExtensionKeyHandoffSource records the handoff source identity.
	ExtensionKeyHandoffSource = "compozy.handoff_source"
)
View Source
const (
	// PeerIDMaxLength is the maximum length accepted for a Network peer id.
	PeerIDMaxLength = identifier.PeerIDMaxLength
	// PeerIDPattern is the Network peer identifier grammar.
	PeerIDPattern = identifier.PeerIDPattern
)
View Source
const (
	// DirectIDPattern is the public direct-room identifier grammar.
	DirectIDPattern = `^direct_[a-f0-9]{32}$`
	// ThreadIDPattern is the public thread identifier grammar.
	ThreadIDPattern = `^thread_[a-z0-9][a-z0-9_-]{2,95}$`
)
View Source
const (
	// StatusDisabled reports that the network runtime is intentionally disabled.
	StatusDisabled = "disabled"
	// StatusReady reports that Network is available with no Live participants.
	StatusReady = "ready"
	// StatusActive reports that Network is available with at least one Live participant.
	StatusActive = "active"
)
View Source
const (
	// DefaultMaxReplayAge is the maximum receiver replay age when expires_at is absent.
	DefaultMaxReplayAge = 5 * time.Minute
)
View Source
const ProtocolV0 = "compozy-network/v0"

ProtocolV0 is the workspace-qualified wire protocol identifier.

View Source
const (
	// RuntimePeerID is the reserved first-party Compozy runtime network peer.
	RuntimePeerID = "compozy.runtime"
)

Variables

View Source
var (
	// ErrWorkNotFound reports that no current work matched the
	// lifecycle message being applied.
	ErrWorkNotFound = errors.New("network: work not found")
	// ErrWorkActorNotAllowed reports a lifecycle actor outside the
	// initiator/target pair.
	ErrWorkActorNotAllowed = errors.New("network: work actor not allowed")
	// ErrInvalidStateTransition reports an impossible lifecycle transition.
	ErrInvalidStateTransition = errors.New("network: invalid work state transition")
	// ErrWorkContainerMismatch reports that a work_id was continued from a
	// different conversation container than the one that opened it.
	ErrWorkContainerMismatch = errors.New("network: work container mismatch")
	// ErrWorkClosed reports a message for a terminal work that must
	// be rejected instead of reopening the work.
	ErrWorkClosed = errors.New("network: work closed")
)
View Source
var (
	// ErrLocalPeerNotFound reports an unknown local session sender.
	ErrLocalPeerNotFound = errors.New("network: local peer not found")
	// ErrTargetPeerNotFound reports a directed send target missing from live presence.
	ErrTargetPeerNotFound = errors.New("network: target peer not found")
)
View Source
var (
	// ErrInvalidEnvelope reports a structurally invalid envelope.
	ErrInvalidEnvelope = errors.New("network: invalid envelope")
	// ErrMissingField reports a required protocol field is absent.
	ErrMissingField = errors.New("network: missing field")
	// ErrInvalidField reports a present field violates protocol rules.
	ErrInvalidField = identifier.ErrInvalidField
	// ErrInvalidKind reports an unknown or unsupported message kind.
	ErrInvalidKind = errors.New("network: invalid kind")
	// ErrInvalidBody reports a malformed or invalid kind-specific body.
	ErrInvalidBody = errors.New("network: invalid body")
	// ErrEnvelopeTooLarge reports an envelope exceeding the protocol size limit.
	ErrEnvelopeTooLarge = errors.New("network: envelope too large")
	// ErrExpired reports an envelope that is already expired.
	ErrExpired = errors.New("network: expired")
	// ErrReplayTooOld reports an envelope outside the receiver replay window.
	ErrReplayTooOld = errors.New("network: replay window exceeded")
	// ErrVerificationFailed reports a syntactically valid envelope whose integrity checks failed.
	ErrVerificationFailed = errors.New("network: verification failed")
	// ErrLegacyFieldRejected reports an obsolete hard-cut wire field.
	ErrLegacyFieldRejected = errors.New("network: legacy field rejected")
	// ErrDirectRoomCollision reports a direct_id bound to an unexpected peer pair.
	ErrDirectRoomCollision = errors.New("network: direct room collision")
)

Functions

func FormatNetworkWakePrompt

func FormatNetworkWakePrompt(
	messages []store.NetworkMessageEntry,
	targetSessionID string,
) (string, acp.PromptNetworkMeta, error)

FormatNetworkWakePrompt renders only committed message content plus a compact wake header.

func IsTerminalState

func IsTerminalState(state WorkState) bool

IsTerminalState reports whether the state is terminal under the RFC.

func NormalizeAuditEntry

func NormalizeAuditEntry(
	profileID string,
	sessionID string,
	direction string,
	envelope Envelope,
	reason string,
	at time.Time,
) (store.NetworkAuditEntry, error)

NormalizeAuditEntry derives a consistent audit row from envelope metadata.

func PreviewTextForRawBody

func PreviewTextForRawBody(kind Kind, raw json.RawMessage) string

PreviewTextForRawBody derives operator-facing preview text from persisted JSON.

func ResolveGreetSummary

func ResolveGreetSummary(card PeerCard, summary string) string

ResolveGreetSummary returns a deterministic operator-facing summary for one greet advertisement.

func ValidateChannel

func ValidateChannel(channel string) error

ValidateChannel reports whether the channel matches the RFC grammar.

func ValidateConversationID

func ValidateConversationID(id string, field string) error

ValidateConversationID reports whether a container identifier matches its field grammar.

func ValidateConversationRef

func ValidateConversationRef(ref ConversationRef) error

ValidateConversationRef reports whether a reference identifies exactly one container.

func ValidateEnvelope

func ValidateEnvelope(env Envelope, opts ValidateOptions) error

ValidateEnvelope validates one envelope without returning a normalized copy.

func ValidateEnvelopeConversation

func ValidateEnvelopeConversation(env Envelope) error

ValidateEnvelopeConversation enforces kind-specific container and work fields.

func ValidatePeerID

func ValidatePeerID(peerID string) error

ValidatePeerID reports whether the peer identifier matches the RFC grammar.

func ValidateSurface

func ValidateSurface(surface Surface) error

ValidateSurface reports whether the surface matches the RFC conversation values.

func ValidateWorkID

func ValidateWorkID(id string) error

ValidateWorkID reports whether a work id can safely cross the network boundary.

func ValidateWorkState

func ValidateWorkState(state WorkState) error

ValidateWorkState reports whether the state is a known work lifecycle state.

func ValidateWorkTransition

func ValidateWorkTransition(from WorkState, to WorkState) error

ValidateWorkTransition reports whether a trace may advance work between states.

func ValidateWorkspaceID

func ValidateWorkspaceID(workspaceID string) error

ValidateWorkspaceID reports whether the workspace identity is safe for protocol use.

Types

type AuditStore

type AuditStore interface {
	WriteNetworkAudit(ctx context.Context, entry store.NetworkAuditEntry) error
}

AuditStore is the persistence surface consumed by the network audit writer.

type AuditWriter

type AuditWriter interface {
	RecordSent(ctx context.Context, profileID string, sessionID string, envelope Envelope) error
	RecordReceived(ctx context.Context, profileID string, sessionID string, envelope Envelope) error
	RecordRejected(ctx context.Context, profileID string, sessionID string, envelope Envelope, reason string) error
	RecordDelivered(ctx context.Context, profileID string, sessionID string, envelope Envelope) error
}

AuditWriter records network activity into the configured sinks.

type AuditWriterOption

type AuditWriterOption func(*FileAuditWriter)

type Body

type Body interface {
	Kind() Kind
}

Body is the typed representation of one envelope body.

func DecodeBody

func DecodeBody(kind Kind, raw json.RawMessage) (Body, error)

DecodeBody parses and validates one kind-specific envelope body.

type CapabilityBody

type CapabilityBody struct {
	Capability CapabilityEnvelopePayload `json:"capability"`
}

CapabilityBody carries or advertises one transferable capability artifact.

func (CapabilityBody) Kind

func (CapabilityBody) Kind() Kind

Kind returns the wire kind for the body.

type CapabilityEnvelopePayload

type CapabilityEnvelopePayload struct {
	ID                string   `json:"id"`
	Summary           string   `json:"summary"`
	Outcome           string   `json:"outcome"`
	Version           string   `json:"version,omitempty"`
	Digest            string   `json:"digest"`
	ContextNeeded     []string `json:"context_needed,omitempty"`
	ArtifactsExpected []string `json:"artifacts_expected,omitempty"`
	ExecutionOutline  []string `json:"execution_outline,omitempty"`
	Constraints       []string `json:"constraints,omitempty"`
	Examples          []string `json:"examples,omitempty"`
	Requirements      []string `json:"requirements,omitempty"`
}

CapabilityEnvelopePayload is the transferable unified capability document.

type ChannelInfo

type ChannelInfo struct {
	WorkspaceID string
	Channel     string
	PeerCount   int
}

ChannelInfo summarizes one active runtime channel.

type ConversationRef

type ConversationRef struct {
	WorkspaceID string
	Channel     string
	Surface     Surface
	ThreadID    string
	DirectID    string
}

ConversationRef identifies exactly one conversation container.

func ConversationRefFromEnvelope

func ConversationRefFromEnvelope(env Envelope) (ConversationRef, error)

ConversationRefFromEnvelope returns the validated conversation container.

func (ConversationRef) ContainerKey

func (r ConversationRef) ContainerKey() string

ContainerKey returns a stable workspace/channel/surface/container key.

func (ConversationRef) IsDirect

func (r ConversationRef) IsDirect() bool

IsDirect reports whether the reference targets a direct room.

func (ConversationRef) IsThread

func (r ConversationRef) IsThread() bool

IsThread reports whether the reference targets a public thread.

func (ConversationRef) Validate

func (r ConversationRef) Validate() error

Validate reports whether the reference identifies exactly one container.

type Delivery

type Delivery struct {
	SessionID string
	PeerID    string
	Envelope  Envelope
	Mode      string
}

Delivery is one recipient selected from the immutable pre-message snapshot.

type Envelope

type Envelope struct {
	Protocol    string          `json:"protocol"`
	ID          string          `json:"id"`
	WorkspaceID string          `json:"workspace_id"`
	Kind        Kind            `json:"kind"`
	Channel     string          `json:"channel"`
	Surface     *Surface        `json:"surface,omitempty"`
	ThreadID    *string         `json:"thread_id,omitempty"`
	DirectID    *string         `json:"direct_id,omitempty"`
	From        string          `json:"from"`
	To          *string         `json:"to,omitempty"`
	Mentions    []string        `json:"mentions,omitempty"`
	WorkID      *string         `json:"work_id,omitempty"`
	ReplyTo     *string         `json:"reply_to,omitempty"`
	TraceID     *string         `json:"trace_id,omitempty"`
	CausationID *string         `json:"causation_id,omitempty"`
	TS          int64           `json:"ts"`
	ExpiresAt   *int64          `json:"expires_at,omitempty"`
	Body        json.RawMessage `json:"body"`
	Proof       *Proof          `json:"proof"`
	Ext         ExtensionMap    `json:"ext,omitempty"`
}

Envelope is the shared Compozy Network v0 wire envelope.

func NormalizeEnvelope

func NormalizeEnvelope(env Envelope, opts ValidateOptions) (Envelope, error)

NormalizeEnvelope trims identifier fields, validates the envelope, and returns a safe copy.

func ParseEnvelope

func ParseEnvelope(data []byte, opts ValidateOptions) (Envelope, error)

ParseEnvelope decodes, validates, and normalizes one raw envelope.

func (Envelope) DecodeBody

func (e Envelope) DecodeBody() (Body, error)

DecodeBody parses and validates the envelope body using the envelope kind.

func (Envelope) IsBroadcast

func (e Envelope) IsBroadcast() bool

IsBroadcast reports whether the envelope is channel-broadcast.

func (Envelope) IsDirected

func (e Envelope) IsDirected() bool

IsDirected reports whether the envelope targets a specific peer.

func (*Envelope) UnmarshalJSON

func (e *Envelope) UnmarshalJSON(data []byte) error

UnmarshalJSON rejects obsolete hard-cut wire fields before decoding.

type ExtensionMap

type ExtensionMap map[string]json.RawMessage

ExtensionMap preserves opaque extension payloads without interpreting them.

type FileAuditWriter

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

FileAuditWriter writes normalized network audit records to a JSONL file and optionally mirrors them into a persistent store.

func NewAuditWriter

func NewAuditWriter(path string, auditStore AuditStore, opts ...AuditWriterOption) (*FileAuditWriter, error)

NewAuditWriter constructs the dual-path network audit writer.

func (*FileAuditWriter) RecordCommittedSent

func (w *FileAuditWriter) RecordCommittedSent(
	ctx context.Context,
	profileID string,
	sessionID string,
	envelope Envelope,
) error

RecordCommittedSent appends the post-commit sent record only to the file sink because atomic conversation acceptance already owns the durable row.

func (*FileAuditWriter) RecordDelivered

func (w *FileAuditWriter) RecordDelivered(
	ctx context.Context,
	profileID string,
	sessionID string,
	envelope Envelope,
) error

RecordDelivered stores a delivered network audit record.

func (*FileAuditWriter) RecordReceived

func (w *FileAuditWriter) RecordReceived(
	ctx context.Context,
	profileID string,
	sessionID string,
	envelope Envelope,
) error

RecordReceived stores a received network audit record.

func (*FileAuditWriter) RecordRejected

func (w *FileAuditWriter) RecordRejected(
	ctx context.Context,
	profileID string,
	sessionID string,
	envelope Envelope,
	reason string,
) error

RecordRejected stores a rejected network audit record.

func (*FileAuditWriter) RecordSent

func (w *FileAuditWriter) RecordSent(
	ctx context.Context,
	profileID string,
	sessionID string,
	envelope Envelope,
) error

RecordSent stores a sent network audit record.

func (*FileAuditWriter) RecordTaskIngress

func (w *FileAuditWriter) RecordTaskIngress(ctx context.Context, audit TaskIngressAudit) error

RecordTaskIngress stores one accepted or rejected task-ingress audit record using the existing network audit sinks.

type GreetBody

type GreetBody struct {
	PeerCard PeerCard `json:"peer_card"`
	Summary  string   `json:"summary,omitempty"`
}

GreetBody advertises peer presence and capabilities in a channel.

func (GreetBody) Kind

func (GreetBody) Kind() Kind

Kind returns the wire kind for the body.

type Kind

type Kind string

Kind identifies one normative Compozy Network message kind.

const (
	KindGreet      Kind = "greet"
	KindWhois      Kind = "whois"
	KindSay        Kind = "say"
	KindCapability Kind = "capability"
	KindReceipt    Kind = "receipt"
	KindTrace      Kind = "trace"
)

func (Kind) Validate

func (k Kind) Validate() error

Validate reports whether the kind is one of the documented RFC values.

type KindMetric

type KindMetric struct {
	Kind      Kind
	Sent      int64
	Received  int64
	Rejected  int64
	Delivered int64
}

KindMetric is the runtime per-kind network activity snapshot surfaced by status APIs.

type LifecycleAction

type LifecycleAction string

LifecycleAction explains how a lifecycle helper handled one message.

const (
	LifecycleActionOpened     LifecycleAction = "opened"
	LifecycleActionAdvanced   LifecycleAction = "advanced"
	LifecycleActionUnchanged  LifecycleAction = "unchanged"
	LifecycleActionIgnored    LifecycleAction = "ignored"
	LifecycleActionRejectWork LifecycleAction = "reject_work"
)

type LifecycleResult

type LifecycleResult struct {
	Work       Work
	Action     LifecycleAction
	ReasonCode *ReasonCode
}

LifecycleResult is the reusable lifecycle decision surface for router code.

func ApplyWorkEnvelope

func ApplyWorkEnvelope(current *Work, profileID string, env Envelope, at time.Time) (LifecycleResult, error)

ApplyWorkEnvelope applies one validated lifecycle envelope to the current work state and returns the router-facing decision.

type LocalPeer

type LocalPeer struct {
	SessionID         string
	PeerID            string
	WorkspaceID       string
	Channel           string
	PeerCard          PeerCard
	CapabilityCatalog []sessionpkg.NetworkPeerCapability
	JoinedAt          time.Time
}

LocalPeer is one daemon-local peer joined to one runtime channel.

type Manager

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

Manager owns live membership and durable-commit-then-notify dispatch.

func NewManager

func NewManager(
	ctx context.Context,
	cfg compozyconfig.NetworkConfig,
	auditPath string,
	auditStore AuditStore,
	opts ...ManagerOption,
) (*Manager, error)

NewManager constructs the broker-free network runtime. Prompt execution is owned by the daemon NetworkWakeRunner.

func (*Manager) Enabled

func (m *Manager) Enabled() bool

Enabled reports the current runtime availability switch.

func (*Manager) Inbox

func (m *Manager) Inbox(ctx context.Context, sessionID string) ([]Envelope, error)

Inbox returns immutable delivered messages for one durable session identity.

func (*Manager) JoinChannel

func (m *Manager) JoinChannel(ctx context.Context, join sessionpkg.NetworkPeerJoin) error

JoinChannel registers one daemon-local Live execution as visible presence.

func (*Manager) LeaveChannel

func (m *Manager) LeaveChannel(ctx context.Context, sessionID string) error

LeaveChannel removes one daemon-local session from live membership.

func (*Manager) ListChannels

func (m *Manager) ListChannels(ctx context.Context, workspaceID string) ([]ChannelInfo, error)

ListChannels returns active in-process channels.

func (*Manager) ListPeers

func (m *Manager) ListPeers(ctx context.Context, workspaceID string, channel string) ([]PeerInfo, error)

ListPeers returns the current daemon-local peer snapshot.

func (*Manager) OnTurnEnd

func (m *Manager) OnTurnEnd(string)

OnTurnEnd is retained for the current daemon interface. Wake execution is lease-driven and does not maintain an in-memory delivery queue.

func (*Manager) Send

func (m *Manager) Send(ctx context.Context, req SendRequest) (string, error)

Send atomically accepts one session-originated envelope before notifying wakes.

func (*Manager) SendFromRuntimePeer

func (m *Manager) SendFromRuntimePeer(ctx context.Context, req RuntimeSendRequest) (string, error)

SendFromRuntimePeer atomically accepts one Compozy-runtime-originated envelope.

func (*Manager) SetEnabled

func (m *Manager) SetEnabled(enabled bool)

SetEnabled updates runtime availability after the durable config transition commits.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown stops live membership and releases all waiter goroutines.

func (*Manager) Status

func (m *Manager) Status(ctx context.Context) (*Status, error)

Status returns a diagnostics snapshot without transport credentials.

func (*Manager) WaitInbox

func (m *Manager) WaitInbox(
	ctx context.Context,
	sessionID string,
	channel string,
) ([]Envelope, error)

WaitInbox waits for the first durable delivery when the current inbox is empty.

type ManagerOption

type ManagerOption func(*managerOptions)

ManagerOption customizes network manager construction.

func WithManagerAcceptanceStore

func WithManagerAcceptanceStore(acceptance store.NetworkAcceptanceStore) ManagerOption

WithManagerAcceptanceStore injects the atomic acceptance repository.

func WithManagerAuditWriter

func WithManagerAuditWriter(auditor AuditWriter) ManagerOption

WithManagerAuditWriter injects a custom audit sink, primarily for tests.

func WithManagerClock

func WithManagerClock(now func() time.Time) ManagerOption

WithManagerClock overrides the manager clock, primarily for tests.

func WithManagerConversationStore

func WithManagerConversationStore(conversations store.NetworkConversationStore) ManagerOption

WithManagerConversationStore injects the durable conversation repository.

func WithManagerHookDispatcher

func WithManagerHookDispatcher(dispatcher HookDispatcher) ManagerOption

WithManagerHookDispatcher injects the network hook dispatcher.

func WithManagerLogger

func WithManagerLogger(logger *slog.Logger) ManagerOption

WithManagerLogger overrides the logger used by the network manager.

func WithManagerWakeNotifier

func WithManagerWakeNotifier(notifier WakeNotifier) ManagerOption

WithManagerWakeNotifier injects the daemon-owned post-commit wake signal.

type MetricSample

type MetricSample struct {
	Name   string
	Labels map[string]string
	Value  int64
}

MetricSample is one low-cardinality runtime network metric sample.

type PeerCard

type PeerCard struct {
	PeerID              string       `json:"peer_id"`
	DisplayName         *string      `json:"display_name,omitempty"`
	ProfilesSupported   []string     `json:"profiles_supported"`
	Capabilities        []string     `json:"capabilities"`
	ArtifactsSupported  []string     `json:"artifacts_supported"`
	TrustModesSupported []string     `json:"trust_modes_supported"`
	Ext                 ExtensionMap `json:"ext,omitempty"`
}

PeerCard advertises one peer's identity and capabilities.

func DefaultPeerCard

func DefaultPeerCard(peerID string) (PeerCard, error)

DefaultPeerCard returns the minimal protocol peer card for one peer identifier.

type PeerInfo

type PeerInfo struct {
	SessionID              *string
	PeerID                 string
	WorkspaceID            string
	Channel                string
	Local                  bool
	PeerCard               PeerCard
	CapabilityCatalog      []sessionpkg.NetworkPeerCapability
	CapabilityCatalogKnown bool
	JoinedAt               *time.Time
	PresenceState          PresenceState
}

PeerInfo is the API-facing snapshot for one daemon-local peer.

type PeerLifecycleEvent

type PeerLifecycleEvent struct {
	Kind      PeerLifecycleKind
	Peer      PeerInfo
	Timestamp time.Time
}

PeerLifecycleEvent is the runtime-local representation of one membership transition.

type PeerLifecycleKind

type PeerLifecycleKind string

PeerLifecycleKind describes one daemon-local membership transition.

const (
	PeerLifecycleJoined PeerLifecycleKind = "joined"
	PeerLifecycleLeft   PeerLifecycleKind = "left"
)

type PeerRegistry

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

PeerRegistry tracks daemon-local session membership only.

func NewPeerRegistry

func NewPeerRegistry(opts ...PeerRegistryOption) (*PeerRegistry, error)

NewPeerRegistry constructs the in-process membership registry.

func (*PeerRegistry) LeaveLocal

func (r *PeerRegistry) LeaveLocal(sessionID string) (LocalPeer, bool)

LeaveLocal removes one local session peer from the registry.

func (*PeerRegistry) ListChannels

func (r *PeerRegistry) ListChannels(workspaceID string) []ChannelInfo

ListChannels returns active in-process channels plus local member counts.

func (*PeerRegistry) ListPeers

func (r *PeerRegistry) ListPeers(workspaceID string, channel string) []PeerInfo

ListPeers returns daemon-local peers, optionally filtered by workspace and channel.

func (*PeerRegistry) LocalByPeer

func (r *PeerRegistry) LocalByPeer(workspaceID string, channel string, peerID string) (LocalPeer, bool)

LocalByPeer resolves one local peer by workspace, channel, and peer ID.

func (*PeerRegistry) LocalBySession

func (r *PeerRegistry) LocalBySession(sessionID string) (LocalPeer, bool)

LocalBySession resolves one local peer by session ID.

func (*PeerRegistry) LocalPeers

func (r *PeerRegistry) LocalPeers(workspaceID string, channel string) []LocalPeer

LocalPeers returns local peers currently joined to one workspace channel.

func (*PeerRegistry) RegisterLocal

func (r *PeerRegistry) RegisterLocal(
	sessionID string,
	workspaceID string,
	channel string,
	card PeerCard,
	joinedAt time.Time,
) (LocalPeer, error)

RegisterLocal upserts one local peer membership keyed by session ID.

func (*PeerRegistry) RegisterLocalWithCapabilityCatalog

func (r *PeerRegistry) RegisterLocalWithCapabilityCatalog(
	sessionID string,
	workspaceID string,
	channel string,
	card PeerCard,
	capabilityCatalog []sessionpkg.NetworkPeerCapability,
	joinedAt time.Time,
) (LocalPeer, error)

RegisterLocalWithCapabilityCatalog upserts one local membership and its runtime-owned catalog.

type PeerRegistryOption

type PeerRegistryOption func(*PeerRegistry)

PeerRegistryOption customizes the registry runtime.

func WithPeerRegistryClock

func WithPeerRegistryClock(now func() time.Time) PeerRegistryOption

WithPeerRegistryClock overrides the time source used by the registry.

type PresenceState

type PresenceState string

PresenceState is the daemon-derived activity state for one network peer.

const (
	PresenceStateLocal PresenceState = "local"
)

type Proof

type Proof map[string]json.RawMessage

Proof preserves the opaque protocol proof payload for forward compatibility.

type ReasonCode

type ReasonCode string

ReasonCode identifies one registered protocol rejection reason.

const (
	ReasonCodeMalformed             ReasonCode = "malformed"
	ReasonCodeExpired               ReasonCode = "expired"
	ReasonCodeDuplicate             ReasonCode = "duplicate"
	ReasonCodeUnsupportedKind       ReasonCode = "unsupported_kind"
	ReasonCodeUnsupportedProfile    ReasonCode = "unsupported_profile"
	ReasonCodeVerificationFailed    ReasonCode = "verification_failed"
	ReasonCodeNotTarget             ReasonCode = "not_target"
	ReasonCodeNotFound              ReasonCode = "not_found"
	ReasonCodeBusy                  ReasonCode = "busy"
	ReasonCodeInternal              ReasonCode = "internal"
	ReasonCodeInvalidSurface        ReasonCode = "invalid_surface"
	ReasonCodeConversationNotFound  ReasonCode = "conversation_not_found"
	ReasonCodeWorkClosed            ReasonCode = "work_closed"
	ReasonCodeWorkContainerMismatch ReasonCode = "work_container_mismatch"
	ReasonCodeLegacyFieldRejected   ReasonCode = "legacy_field_rejected"
)

func (ReasonCode) Validate

func (r ReasonCode) Validate() error

Validate reports whether the reason code belongs to the v0 registry.

type ReceiptBody

type ReceiptBody struct {
	ForID      string        `json:"for_id"`
	Status     ReceiptStatus `json:"status"`
	ReasonCode *ReasonCode   `json:"reason_code,omitempty"`
	Detail     *string       `json:"detail,omitempty"`
}

ReceiptBody acknowledges or rejects protocol-level admission.

func (ReceiptBody) Kind

func (ReceiptBody) Kind() Kind

Kind returns the wire kind for the body.

type ReceiptStatus

type ReceiptStatus string

ReceiptStatus identifies one receipt admission status.

const (
	ReceiptStatusAccepted    ReceiptStatus = "accepted"
	ReceiptStatusRejected    ReceiptStatus = "rejected"
	ReceiptStatusDuplicate   ReceiptStatus = "duplicate"
	ReceiptStatusExpired     ReceiptStatus = "expired"
	ReceiptStatusUnsupported ReceiptStatus = "unsupported"
	ReceiptStatusCanceled    ReceiptStatus = "canceled"
)

func (ReceiptStatus) Validate

func (s ReceiptStatus) Validate() error

Validate reports whether the receipt status is documented by the RFC.

type RouteResult

type RouteResult struct {
	Envelope     Envelope
	Deliveries   []Delivery
	Dispositions []RoutingDisposition
	// contains filtered or unexported fields
}

RouteResult is the pure routing decision consumed by atomic acceptance.

type Router

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

Router validates outbound envelopes and computes recipients without side effects.

func NewRouter

func NewRouter(peers *PeerRegistry, maxReplayAge time.Duration, opts ...RouterOption) (*Router, error)

NewRouter constructs a broker-free router over daemon-local live presence.

func (*Router) Leave

func (r *Router) Leave(sessionID string) (LocalPeer, bool)

Leave removes the local sender presence for one session.

func (*Router) PrepareRuntimeSend

func (r *Router) PrepareRuntimeSend(ctx context.Context, req RuntimeSendRequest) (SendResult, error)

PrepareRuntimeSend validates an Compozy-runtime-originated envelope before persistence.

func (*Router) PrepareSend

func (r *Router) PrepareSend(ctx context.Context, req SendRequest) (SendResult, error)

PrepareSend validates a session-originated envelope before persistence.

func (*Router) RoutePrepared

func (r *Router) RoutePrepared(ctx context.Context, prepared SendResult) (RouteResult, error)

RoutePrepared computes the exact local recipient set from pre-message state.

type RouterOption

type RouterOption func(*Router)

RouterOption customizes the pure router.

func WithRouterClock

func WithRouterClock(now func() time.Time) RouterOption

WithRouterClock overrides the clock used for validation decisions.

func WithRouterLogger

func WithRouterLogger(logger *slog.Logger) RouterOption

WithRouterLogger overrides the logger used for routing diagnostics.

func WithRouterThreadParticipantResolver

func WithRouterThreadParticipantResolver(resolver ThreadParticipantResolver) RouterOption

WithRouterThreadParticipantResolver injects the durable participant snapshot reader.

type RoutingDisposition

type RoutingDisposition struct {
	SessionID string
	PeerID    string
	Decision  string
}

RoutingDisposition records one selected or ignored local recipient.

type RuntimeSendRequest

type RuntimeSendRequest struct {
	WorkspaceID string
	Channel     string
	Surface     *Surface
	ThreadID    *string
	DirectID    *string
	Kind        Kind
	To          *string
	Mentions    []string
	Body        json.RawMessage
	WorkID      *string
	ReplyTo     *string
	TraceID     *string
	CausationID *string
	ExpiresAt   *int64
	ID          *string
	Ext         ExtensionMap
}

RuntimeSendRequest carries one outbound envelope emitted by the Compozy runtime peer.

type SayBody

type SayBody struct {
	Text      string            `json:"text"`
	Artifacts []json.RawMessage `json:"artifacts,omitempty"`
	Intent    string            `json:"intent,omitempty"`
}

SayBody carries broadcast chat-first communication.

func (SayBody) Kind

func (SayBody) Kind() Kind

Kind returns the wire kind for the body.

type SendRequest

type SendRequest struct {
	SessionID   string
	WorkspaceID string
	Channel     string
	Surface     *Surface
	ThreadID    *string
	DirectID    *string
	Kind        Kind
	To          *string
	Mentions    []string
	Body        json.RawMessage
	WorkID      *string
	ReplyTo     *string
	TraceID     *string
	CausationID *string
	ExpiresAt   *int64
	ID          *string
	Ext         ExtensionMap
}

SendRequest carries one caller-supplied outbound envelope request.

type SendResult

type SendResult struct {
	ID       string
	Envelope Envelope
}

SendResult is one validated envelope ready for atomic acceptance.

type Status

type Status struct {
	Enabled              bool
	Status               string
	LocalPeers           int
	Channels             int
	MessagesSent         int64
	MessagesReceived     int64
	MessagesRejected     int64
	MessagesDelivered    int64
	WorkflowTaggedEvents int64
	HandoffTaggedEvents  int64
	OpenThreads          int64
	OpenDirectRooms      int64
	OpenWorkItems        int64
	ConversationMessages int64
	WorkTransitions      int64
	DirectResolves       int64
	KindMetrics          []KindMetric
	Metrics              []MetricSample
}

Status is the manager-facing diagnostics snapshot.

type Surface

type Surface string

Surface identifies the conversation container class for one message.

const (
	SurfaceThread Surface = "thread"
	SurfaceDirect Surface = "direct"
)

func (Surface) Validate

func (s Surface) Validate() error

Validate reports whether the surface is one of the documented values.

type TaskIngressAudit

type TaskIngressAudit struct {
	ProfileID   string
	Action      string
	Direction   string
	PeerID      string
	WorkspaceID string
	Channel     string
	RequestID   string
	Reason      string
	Payload     any
}

TaskIngressAudit captures one task-domain ingress decision originating from a validated network peer.

type TaskIngressAuditWriter

type TaskIngressAuditWriter interface {
	RecordTaskIngress(ctx context.Context, audit TaskIngressAudit) error
}

TaskIngressAuditWriter is the optional audit extension used by task-aware network ingress. Existing protocol-message auditing remains unchanged.

type ThreadParticipantResolver

type ThreadParticipantResolver interface {
	ListThreadParticipants(
		ctx context.Context,
		ref store.NetworkChannelRef,
		threadID string,
	) ([]store.NetworkThreadParticipant, error)
}

ThreadParticipantResolver supplies the pre-message public-thread membership snapshot.

type TraceBody

type TraceBody struct {
	State        WorkState         `json:"state"`
	Message      string            `json:"message,omitempty"`
	Result       json.RawMessage   `json:"result,omitempty"`
	ArtifactRefs []json.RawMessage `json:"artifact_refs,omitempty"`
}

TraceBody reports progress or terminal outcome for work.

func (TraceBody) Kind

func (TraceBody) Kind() Kind

Kind returns the wire kind for the body.

type ValidateOptions

type ValidateOptions struct {
	Now          time.Time
	MaxReplayAge time.Duration
}

ValidateOptions configures envelope validation and normalization.

type WakeNotifier

type WakeNotifier interface {
	NotifyNetworkWake(store.CommittedNetworkNotification)
}

WakeNotifier receives post-commit wake notifications. The durable task run remains authoritative if notification is delayed or lost.

type WhoisBody

type WhoisBody struct {
	Type     WhoisType `json:"type"`
	Query    string    `json:"query,omitempty"`
	PeerCard *PeerCard `json:"peer_card,omitempty"`
}

WhoisBody requests or returns peer card information.

func (WhoisBody) Kind

func (WhoisBody) Kind() Kind

Kind returns the wire kind for the body.

type WhoisType

type WhoisType string

WhoisType identifies the request or response shape for `whois`.

const (
	WhoisTypeRequest  WhoisType = "request"
	WhoisTypeResponse WhoisType = "response"
)

func (WhoisType) Validate

func (t WhoisType) Validate() error

Validate reports whether the whois type is a documented value.

type Work

type Work struct {
	ID         string
	ProfileID  string
	Ref        ConversationRef
	Initiator  string
	Target     string
	State      WorkState
	CreatedAt  time.Time
	UpdatedAt  time.Time
	TerminalAt *time.Time
}

Work tracks one directed work inside one channel.

func OpenWork

func OpenWork(profileID string, env Envelope, at time.Time) (Work, error)

OpenWork opens a new work from the first directed message.

func (Work) IsParticipant

func (i Work) IsParticipant(peerID string) bool

IsParticipant reports whether the peer owns the work lifecycle.

func (Work) Validate

func (i Work) Validate() error

Validate reports whether the work carries a usable identity and state.

type WorkState

type WorkState string

WorkState identifies one RFC work lifecycle state.

const (
	WorkStateSubmitted  WorkState = "submitted"
	WorkStateWorking    WorkState = "working"
	WorkStateNeedsInput WorkState = "needs_input"
	WorkStateCompleted  WorkState = "completed"
	WorkStateFailed     WorkState = "failed"
	WorkStateCanceled   WorkState = "canceled"
)

func (WorkState) Validate

func (s WorkState) Validate() error

Validate reports whether the work state is documented by the RFC.

Directories

Path Synopsis
Package participation owns the shared Network participation contract.
Package participation owns the shared Network participation contract.
Package usage owns the shared public Network usage query and response projection.
Package usage owns the shared public Network usage query and response projection.

Jump to

Keyboard shortcuts

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