cmdpalette

package
v0.3.0-beta.29 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package cmdpalette owns the daemon-canonical command catalog and invocation contract.

Index

Constants

View Source
const (
	ViewContractVersion  = "v1"
	MaxViewComponents    = 1500
	MaxViewMountRows     = 150
	MaxViewPatchRows     = 500
	MaxViewWireBytes     = 256 * 1024
	MaxViewTextBytes     = 4 * 1024
	MaxDetailMarkdown    = 64 * 1024
	DetailTruncationMark = "\n\n[Content truncated]"
)

Variables

View Source
var (
	ErrInvalidDescriptor          = errors.New("cmd palette: invalid descriptor")
	ErrDuplicateCommandID         = errors.New("cmd palette: duplicate command id")
	ErrCommandNotFound            = errors.New("cmd palette: command not found")
	ErrAlreadyRunning             = errors.New("cmd palette: command already running")
	ErrNoAttachedShell            = errors.New("cmd palette: no attached shell")
	ErrMultipleClients            = errors.New("cmd palette: multiple clients")
	ErrCannotDeferSecrets         = errors.New("cmd palette: cannot defer secrets")
	ErrClientUnauthorized         = errors.New("cmd palette: client unauthorized")
	ErrInvalidExecution           = errors.New("cmd palette: invalid execution result")
	ErrProfileManagementForbidden = errors.New("cmd palette: profile management is local-only")
	ErrUnsafeURL                  = errors.New("cmd palette: url must be an absolute http or https URL")
)
View Source
var (
	// ErrViewBusy reports that a session reached its independent action-event cap.
	ErrViewBusy = errors.New("cmd palette view: session is busy")
	// ErrViewSessionGone reports that a session was closed or invalidated.
	ErrViewSessionGone = errors.New("cmd palette view: session is gone")
	// ErrViewSessionForbidden reports a session ownership mismatch.
	ErrViewSessionForbidden = errors.New("cmd palette view: session access is forbidden")
	// ErrViewFrameStale reports output from a superseded causal generation.
	ErrViewFrameStale = errors.New("cmd palette view: frame is stale")
	// ErrViewEventInvalid reports a missing handler, non-positive seq, or empty revision.
	ErrViewEventInvalid = errors.New("cmd palette view: handler, positive seq, and revision are required")
	// ErrViewEventSeqNotIncreasing reports an event seq that did not advance.
	ErrViewEventSeqNotIncreasing = errors.New("cmd palette view: event seq must increase")
	// ErrViewEventRevisionStale reports an event that does not match the current revision.
	ErrViewEventRevisionStale = errors.New("cmd palette view: event revision is stale")
	// ErrViewInvalidSequence reports a negative or unparsable view stream cursor.
	ErrViewInvalidSequence = errors.New("cmd palette view: invalid sequence")
	// ErrViewStreamEpochRequired reports a replay cursor without its stream epoch.
	ErrViewStreamEpochRequired = errors.New(
		"cmd palette view: stream_epoch is required when after is greater than zero",
	)
	// ErrViewPatchStreamUnavailable reports a declarative view without a patch subscriber.
	ErrViewPatchStreamUnavailable = errors.New("cmd palette view: patch stream is unavailable")
)
View Source
var WeightsV1 = Weights{
	Version:                    1,
	FrecencyHalfLifeDays:       30,
	QueryHalfLifeDays:          14,
	Deadband:                   12,
	FallbackWeakMatchThreshold: 120,
	MatchAliasExact:            1_040,
	MatchExact:                 1_000,
	MatchPrefix:                900,
	MatchTokenPrefix:           780,
	MatchCompactPrefix:         740,
	MatchWordBoundaryMin:       620,
	MatchWordBoundaryMax:       730,
	MatchContains:              560,
	MatchSubsequenceMin:        380,
	MatchSubsequenceMax:        520,
	SecondaryFieldMultiplier:   0.72,
	SecondaryFieldCap:          720,
	FrecencyScale:              70,
	FrecencyCap:                180,
	QueryLearningCap:           260,
	ContextBoost:               80,
	PromotionCommandFloor:      500,
	PromotionPathFloor:         600,
	PromotionDefaultFloor:      700,
	PromotionTabFloor:          820,
	GhostMinScore:              900,
	MinEntityQueryLength:       2,
	MaxQueryLength:             256,
	PruneAfterDays:             120,
	PruneThreshold:             0.05,
	EntitySectionVisibleCap:    6,
	DomainViewMountCap:         150,
	GroupOrder: []string{
		"Pinned", "Recents", "Curated", "Views", "Shell", "Window", "Tabs", "Tiling", "Layout",
		"Sessions", "Desktops", "Workspaces", "Agents", "Tasks", "Loops", "Jobs", "Triggers",
		"Knowledge", "Vault", "Marketplace", "Extensions", "Apps",
		"Settings", "Commands",
	},
}

Functions

func DecayFrecency

func DecayFrecency(weight float64, last, now time.Time, halfLife time.Duration) float64

DecayFrecency applies exponential decay to a stored signal weight.

func NormalizeQuery

func NormalizeQuery(query string) string

NormalizeQuery returns the only query representation eligible for durable usage recording.

func ValidateDescriptor

func ValidateDescriptor(descriptor Descriptor) error

func ValidateViewPatch

func ValidateViewPatch(patch ViewPatch) error

ValidateViewPatch checks revision identity, size, and RFC 6902 operation shape.

Types

type Action

type Action struct {
	Kind ActionKind     `json:"kind"`
	Op   string         `json:"op,omitempty"`
	Tool string         `json:"tool,omitempty"`
	View string         `json:"view,omitempty"`
	App  string         `json:"app,omitempty"`
	URL  string         `json:"url,omitempty"`
	Args map[string]any `json:"args,omitempty"`
}

type ActionExecutor

type ActionExecutor interface {
	ExecuteAction(context.Context, ExecutionRequest) (ExecutionResult, error)
}

type ActionKind

type ActionKind string
const (
	ActionKindClientOp ActionKind = "client_op"
	ActionKindTool     ActionKind = "tool"
	ActionKindView     ActionKind = "view"
	ActionKindNavigate ActionKind = "navigate"
	ActionKindURL      ActionKind = "url"
	ActionKindCopy     ActionKind = "copy"
)

type ApprovalCompletionReader

type ApprovalCompletionReader interface {
	ApprovalCompletionStatus(context.Context, ProfileLens, string) (string, error)
}

type ApprovalPreflight

type ApprovalPreflight interface {
	ApprovalRequired(context.Context, ExecutionRequest) (bool, error)
}

type Argument

type Argument struct {
	Name        string       `json:"name"`
	Type        ArgumentType `json:"type"`
	Placeholder string       `json:"placeholder,omitempty"`
	Required    bool         `json:"required"`
	Options     []string     `json:"options,omitempty"`
}

type ArgumentType

type ArgumentType string
const (
	ArgumentTypeText     ArgumentType = "text"
	ArgumentTypePassword ArgumentType = "password"
	ArgumentTypeDropdown ArgumentType = "dropdown"
	ArgumentTypeCheckbox ArgumentType = "checkbox"
)

type BindableCatalog

type BindableCatalog interface {
	BindableIDs(context.Context, ProfileLens, WorkspaceID) ([]CommandID, error)
}

type BindingsResolver

type BindingsResolver interface {
	Bindings(context.Context, ProfileLens, WorkspaceID) (map[CommandID][]string, map[CommandID]string, error)
}

type CallerKind

type CallerKind string
const (
	CallerControlPlane   CallerKind = "control_plane"
	CallerAttachedClient CallerKind = "attached_client"
)

type CapabilityGapReporter

type CapabilityGapReporter interface {
	RecordCapabilityGap(path string, requires map[string]string)
}

CapabilityGapReporter records an authored element that the current host cannot render.

type Catalog

type Catalog struct {
	Commands        []ResolvedCommand `json:"commands"`
	Sources         []SourceStatus    `json:"sources"`
	Revision        string            `json:"catalog_revision"`
	ContextRevision string            `json:"context_revision,omitempty"`
	ProfileLens     ProfileLens       `json:"profile_lens"`
}

type CatalogRequest

type CatalogRequest struct {
	ProfileLens ProfileLens
	WorkspaceID WorkspaceID
	ClientID    ClientID
}

CatalogRequest identifies one complete command projection.

type Chip

type Chip struct {
	ID       string            `json:"id"`
	Label    string            `json:"label"`
	Count    *int              `json:"count,omitempty"`
	Requires map[string]string `json:"requires,omitempty"`
	Fallback string            `json:"fallback,omitempty"`
}

type Client

type Client struct {
	ID              ClientID    `json:"client_id"`
	Kind            string      `json:"kind"`
	WorkspaceID     WorkspaceID `json:"workspace"`
	AttachedAt      time.Time   `json:"attached_at"`
	ContextRevision string      `json:"context_revision"`
}

type ClientDirectory

type ClientDirectory interface {
	Clients(context.Context, WorkspaceID) ([]Client, error)
	Context(context.Context, WorkspaceID, ClientID) (ContextSnapshot, error)
	Authorize(context.Context, WorkspaceID, ClientID, string) error
}

type ClientID

type ClientID string

type CommandID

type CommandID string

type Confirmation

type Confirmation struct {
	Title   string `json:"title"`
	Body    string `json:"body,omitempty"`
	Confirm string `json:"confirm"`
}

type ContextKey

type ContextKey string
const (
	ContextWindowFocused      ContextKey = "window.focused"
	ContextWindowFloating     ContextKey = "window.floating"
	ContextWindowStacked      ContextKey = "window.stacked"
	ContextDesktopWindowCount ContextKey = "desktop.windowCount"
	ContextScopeGlobal        ContextKey = "scope.global"
	ContextShellDesktop       ContextKey = "shell.desktop"
	ContextSessionState       ContextKey = "session.focused.state"
	ContextWorkspaceTrusted   ContextKey = "workspace.trusted"
)

type ContextSnapshot

type ContextSnapshot struct {
	Revision string
	Values   map[ContextKey]any
}

type Contribution

type Contribution struct {
	Commands []Descriptor
	Sources  []SourceStatus
	Defaults []ExtensionDefaultShortcut
}

Contribution is one atomic extension catalog snapshot.

type ContributionProvider

type ContributionProvider interface {
	Provider
	ProvideContribution(context.Context, CatalogRequest) (Contribution, error)
}

ContributionProvider returns a complete multi-source extension projection.

type CopyEffect

type CopyEffect struct {
	Content string `json:"content"`
}

type Descriptor

type Descriptor struct {
	ID                        CommandID       `json:"id"`
	Title                     string          `json:"title"`
	Section                   string          `json:"section"`
	Icon                      string          `json:"icon"`
	Keywords                  []string        `json:"keywords,omitempty"`
	Source                    Source          `json:"source"`
	Action                    Action          `json:"action"`
	Arguments                 []Argument      `json:"arguments"`
	Destructive               bool            `json:"destructive"`
	Confirmation              *Confirmation   `json:"confirmation,omitempty"`
	When                      []Predicate     `json:"when,omitempty"`
	AvailabilityExempt        bool            `json:"availability_exempt"`
	Policy                    ExecutionPolicy `json:"execution"`
	ProviderUnavailableReason string          `json:"-"`
}

func CloneDescriptor

func CloneDescriptor(descriptor Descriptor) Descriptor

CloneDescriptor returns an independent copy of one command descriptor.

type DetailBody

type DetailBody struct {
	IsLoading bool        `json:"is_loading,omitempty"`
	Markdown  string      `json:"markdown,omitempty"`
	Metadata  []MetaField `json:"metadata,omitempty"`
	Actions   []RowAction `json:"actions,omitempty"`
}

type DuplicateCommandIDError

type DuplicateCommandIDError struct {
	ID     CommandID
	First  string
	Second string
}

func (*DuplicateCommandIDError) Error

func (e *DuplicateCommandIDError) Error() string

func (*DuplicateCommandIDError) Unwrap

func (e *DuplicateCommandIDError) Unwrap() error

type DynamicViewProvider

type DynamicViewProvider interface {
	ProvideViews(context.Context, CatalogRequest) ([]ViewDescriptor, error)
	ViewSourceProvider
}

DynamicViewProvider resolves workspace-scoped extension view descriptors.

type Effect

type Effect struct {
	ID        string           `json:"id"`
	Toast     *ToastEffect     `json:"toast,omitempty"`
	Copy      *CopyEffect      `json:"copy,omitempty"`
	OpenURL   *OpenURLEffect   `json:"open_url,omitempty"`
	OpenApp   *OpenAppEffect   `json:"open_app,omitempty"`
	PickFiles *PickFilesEffect `json:"pick_files,omitempty"`
}

type EffectResult

type EffectResult struct {
	EffectID string          `json:"effect_id"`
	Payload  json.RawMessage `json:"payload,omitempty"`
}

EffectResult correlates a host effect result with the originating effect.

type EmptyState

type EmptyState struct {
	Title string `json:"title"`
	Hint  string `json:"hint,omitempty"`
	Icon  string `json:"icon,omitempty"`
}

type Event

type Event struct {
	Name            EventName   `json:"-"`
	ProfileLens     ProfileLens `json:"profile_lens"`
	WorkspaceID     WorkspaceID `json:"workspace"`
	CatalogRevision string      `json:"revision,omitempty"`
	CommandID       CommandID   `json:"command_id,omitempty"`
	Pinned          *bool       `json:"pinned,omitempty"`
	Source          string      `json:"source,omitempty"`
	ExecutionSite   ActionKind  `json:"exec_site,omitempty"`
	Outcome         string      `json:"outcome,omitempty"`
	DurationMS      int64       `json:"duration_ms"`
	InvocationID    string      `json:"invocation_id,omitempty"`
	ApprovalID      string      `json:"approval_id,omitempty"`
	ClientID        ClientID    `json:"client_id,omitempty"`
	ViewID          string      `json:"view,omitempty"`
	Extension       string      `json:"extension,omitempty"`
	ViewSessionID   string      `json:"view_session,omitempty"`
	Chord           string      `json:"chord,omitempty"`
	Reason          string      `json:"reason,omitempty"`
	OccurredAt      time.Time   `json:"occurred_at"`
}

type EventName

type EventName string
const (
	EventCatalogChanged                 EventName = "cmd_palette.catalog.changed"
	EventCommandInvoked                 EventName = "cmd_palette.command.invoked"
	EventPinChanged                     EventName = "cmd_palette.pin.changed"
	EventBindingChanged                 EventName = "cmd_palette.binding.changed"
	EventAliasChanged                   EventName = "cmd_palette.alias.changed"
	EventPersonalizationReset           EventName = "cmd_palette.personalization.reset"
	EventViewSessionOpened              EventName = "cmd_palette.view_session.opened"
	EventViewSessionClosed              EventName = "cmd_palette.view_session.closed"
	EventViewSessionDegraded            EventName = "cmd_palette.view_session.degraded"
	EventViewSessionCircuitBroken       EventName = "cmd_palette.view_session.circuit_broken"
	EventGlobalHotkeyRegistrationFailed EventName = "global_hotkey.registration_failed"
)

type EventRecorder

type EventRecorder interface {
	RecordCmdPaletteEvent(context.Context, Event)
}

type EventSubscriber

type EventSubscriber interface {
	SubscribeCmdPaletteEvents(context.Context, ProfileLens, WorkspaceID) (<-chan Event, func(), error)
}

type ExecutionPolicy

type ExecutionPolicy struct {
	SingleFlight bool `json:"single_flight"`
	RetrySafe    bool `json:"retry_safe"`
}

type ExecutionRequest

type ExecutionRequest struct {
	ProfileLens  ProfileLens
	WorkspaceID  WorkspaceID
	InvocationID string
	ClientID     ClientID
	Descriptor   Descriptor
	Args         map[string]any
}

type ExecutionResult

type ExecutionResult struct {
	Result     json.RawMessage
	ApprovalID string
	Completion <-chan struct{}
}

type ExtensionDefaultCatalog

type ExtensionDefaultCatalog interface {
	ExtensionDefaults(context.Context, ProfileLens, WorkspaceID) ([]ExtensionDefaultShortcut, error)
}

ExtensionDefaultCatalog exposes ordered extension shortcut claims without resolving bindings.

type ExtensionDefaultShortcut

type ExtensionDefaultShortcut struct {
	CommandID CommandID
	Chord     string
	Source    string
	Active    bool
}

ExtensionDefaultShortcut is one bind-if-free extension shortcut claim.

type FormBody

type FormBody struct {
	Fields   []FormField `json:"fields"`
	Submit   *RowAction  `json:"submit,omitempty"`
	OnSubmit string      `json:"on_submit,omitempty"`
}

type FormField

type FormField struct {
	ID          string            `json:"id"`
	Type        string            `json:"type"`
	Label       string            `json:"label"`
	Placeholder string            `json:"placeholder,omitempty"`
	Required    bool              `json:"required,omitempty"`
	Options     []string          `json:"options,omitempty"`
	Directories bool              `json:"directories,omitempty"`
	Default     any               `json:"default,omitempty"`
	Error       string            `json:"error,omitempty"`
	EmptyHint   string            `json:"empty_hint,omitempty"`
	OnChange    string            `json:"on_change,omitempty"`
	OnBlur      string            `json:"on_blur,omitempty"`
	EventCount  int64             `json:"event_count,omitempty"`
	Requires    map[string]string `json:"requires,omitempty"`
	Fallback    string            `json:"fallback,omitempty"`
}

type GlobalShortcut

type GlobalShortcut struct {
	IntendedChord string `json:"intended_chord"`
	ActiveChord   string `json:"active_chord,omitempty"`
	Status        string `json:"status,omitempty"`
	Reason        string `json:"reason,omitempty"`
	SettingsURL   string `json:"settings_url,omitempty"`
}

GlobalShortcut projects daemon-owned intent and one shell client's registration truth.

type GlobalShortcutStatusDirectory

type GlobalShortcutStatusDirectory interface {
	GlobalShortcutStatuses(
		context.Context,
		ProfileLens,
		WorkspaceID,
		ClientID,
	) (map[CommandID]GlobalShortcut, error)
}

GlobalShortcutStatusDirectory resolves ephemeral registration state for one shell client.

type GridBody

type GridBody struct {
	Sections []GridSection `json:"sections"`
}

type GridSection

type GridSection struct {
	Title string     `json:"title,omitempty"`
	Tiles []GridTile `json:"tiles"`
}

type GridTile

type GridTile struct {
	ID       string            `json:"id"`
	Title    string            `json:"title"`
	Image    Image             `json:"image"`
	Badge    *ViewBadge        `json:"badge,omitempty"`
	Actions  []RowAction       `json:"actions,omitempty"`
	Requires map[string]string `json:"requires,omitempty"`
	Fallback string            `json:"fallback,omitempty"`
}

type Image

type Image struct {
	URL   string `json:"url,omitempty"`
	Token string `json:"token,omitempty"`
	Emoji string `json:"emoji,omitempty"`
}

type InvalidArgumentsError

type InvalidArgumentsError struct {
	Fields map[string]string
}

func (*InvalidArgumentsError) Error

func (e *InvalidArgumentsError) Error() string

type InvokeRequest

type InvokeRequest struct {
	ProfileLens     ProfileLens    `json:"profile_lens"`
	WorkspaceID     WorkspaceID    `json:"workspace_id"`
	CommandID       CommandID      `json:"command_id"`
	Args            map[string]any `json:"args"`
	ClientID        ClientID       `json:"client,omitempty"`
	ClientToken     string         `json:"-"`
	Caller          CallerKind     `json:"-"`
	ManagementLocal bool           `json:"-"`
}

type InvokeResult

type InvokeResult struct {
	ProfileLens  ProfileLens     `json:"profile_lens"`
	Status       InvokeStatus    `json:"status"`
	Result       json.RawMessage `json:"result,omitempty"`
	ApprovalID   string          `json:"approval_id,omitempty"`
	InvocationID string          `json:"invocation_id"`
}

type InvokeStatus

type InvokeStatus string
const (
	InvokeStatusOK              InvokeStatus = "ok"
	InvokeStatusApprovalPending InvokeStatus = "approval_pending"
)

type MetaField

type MetaField struct {
	Label    string            `json:"label"`
	Value    string            `json:"value"`
	Requires map[string]string `json:"requires,omitempty"`
	Fallback string            `json:"fallback,omitempty"`
}

type MultipleClientsError

type MultipleClientsError struct {
	Clients []ClientID
}

func (*MultipleClientsError) Error

func (e *MultipleClientsError) Error() string

func (*MultipleClientsError) Unwrap

func (e *MultipleClientsError) Unwrap() error

type OpenAppEffect

type OpenAppEffect struct {
	App string `json:"app"`
}

type OpenURLEffect

type OpenURLEffect struct {
	URL string `json:"url"`
}

type Option

type Option func(*Service) error

func WithClock

func WithClock(clock func() time.Time) Option

func WithDynamicViewProvider

func WithDynamicViewProvider(provider DynamicViewProvider) Option

WithDynamicViewProvider registers one workspace-scoped view projection.

func WithEventRecorder

func WithEventRecorder(recorder EventRecorder) Option

func WithInvocationIDGenerator

func WithInvocationIDGenerator(generator func() string) Option

func WithLogger

func WithLogger(logger *slog.Logger) Option

func WithPersonalizationPolicy

func WithPersonalizationPolicy(policy PersonalizationPolicy) Option

func WithPersonalizationStore

func WithPersonalizationStore(store PersonalizationStore) Option

func WithViewProgramProvider

func WithViewProgramProvider(provider ViewProgramProvider) Option

WithViewProgramProvider registers the single view.provider runtime.

func WithViewProviders

func WithViewProviders(registrations []ViewProviderRegistration) Option

WithViewProviders registers static declarative and programmable view descriptors.

type Pagination

type Pagination struct {
	HasMore  bool `json:"has_more"`
	PageSize int  `json:"page_size,omitempty"`
}

type PatchOp

type PatchOp struct {
	Op    string          `json:"op"`
	Path  string          `json:"path"`
	Value json.RawMessage `json:"value,omitempty"`
}

type PersonalizationPolicy

type PersonalizationPolicy interface {
	PersonalizationEnabled(context.Context, ProfileLens, WorkspaceID) (bool, error)
}

PersonalizationPolicy resolves whether workspace ranking signals are active.

type PersonalizationRows

type PersonalizationRows struct {
	Usage     []UsageSignal
	QueryHits []QueryHit
	Pins      []Pin
}

type PersonalizationStore

type PersonalizationStore interface {
	RecordCmdPaletteUsage(context.Context, Usage, Weights) error
	CmdPalettePersonalization(context.Context, ProfileLensID, WorkspaceID) (PersonalizationRows, error)
	PutCmdPalettePin(context.Context, ProfileLensID, WorkspaceID, CommandID, time.Time) error
	DeleteCmdPalettePin(context.Context, ProfileLensID, WorkspaceID, CommandID) error
	PruneCmdPaletteCommand(context.Context, ProfileLensID, WorkspaceID, CommandID) error
	PruneCmdPaletteUsage(context.Context, ProfileLensID, WorkspaceID, CommandID) error
	PruneCmdPaletteQueryHit(context.Context, ProfileLensID, WorkspaceID, string, CommandID) error
	ResetCmdPalettePersonalization(context.Context, ProfileLensID, WorkspaceID) error
}

type PersonalizationSummary

type PersonalizationSummary struct {
	ProfileLens       ProfileLens `json:"profile_lens"`
	Workspace         WorkspaceID `json:"workspace"`
	Pins              []CommandID `json:"pins"`
	Recents           int         `json:"recents"`
	FrecencyEntries   int         `json:"frecency_entries"`
	QueryAssociations int         `json:"query_associations"`
}

type PickFilesEffect

type PickFilesEffect struct {
	Directories bool `json:"directories,omitempty"`
}

type Pin

type Pin struct {
	CommandID CommandID `json:"command_id"`
	PinnedAt  int64     `json:"pinned_at"`
}

type Predicate

type Predicate struct {
	Key      ContextKey        `json:"key"`
	Operator PredicateOperator `json:"operator,omitempty"`
	Value    any               `json:"value"`
	Reason   string            `json:"reason,omitempty"`
}

type PredicateOperator

type PredicateOperator string
const (
	PredicateEquals             PredicateOperator = "equals"
	PredicateNotEquals          PredicateOperator = "not_equals"
	PredicateGreaterThanOrEqual PredicateOperator = "greater_than_or_equal"
)

type ProfileLens

type ProfileLens struct {
	ID   ProfileLensID `json:"profile_lens_id"`
	Name string        `json:"profile_name"`
}

ProfileLens is the required profile axis for every command-palette projection. ID is either one stable profile ULID or the reserved aggregate identity @all.

func AggregateProfileLens

func AggregateProfileLens() ProfileLens

AggregateProfileLens constructs the only valid aggregate lens.

func ScopedProfileLens

func ScopedProfileLens(profileID ProfileLensID, profileName string) ProfileLens

ScopedProfileLens constructs one real-profile lens.

func (ProfileLens) IsAggregate

func (lens ProfileLens) IsAggregate() bool

IsAggregate reports whether the lens explicitly widens reads across profiles.

func (ProfileLens) Validate

func (lens ProfileLens) Validate() error

Validate rejects absent or malformed profile identity before any provider is called.

type ProfileLensID

type ProfileLensID string

ProfileLensID partitions personalization by one real profile or the explicit aggregate lens.

const (
	DefaultProfileLensID   ProfileLensID = "00000000000000000000000000"
	AggregateProfileLensID ProfileLensID = "@all"
)

func (ProfileLensID) Validate

func (id ProfileLensID) Validate() error

Validate rejects absent or malformed profile lenses before persistence.

type Provider

type Provider interface {
	ProvideCommands(context.Context, CatalogRequest) ([]Descriptor, error)
}

type ProviderRegistration

type ProviderRegistration struct {
	Source   Source
	Provider Provider
}

type QueryHit

type QueryHit struct {
	Query      string    `json:"query"`
	CommandID  CommandID `json:"command_id"`
	Weight     float64   `json:"weight"`
	LastUsedAt int64     `json:"-"`
}

type ResolvedCommand

type ResolvedCommand struct {
	Descriptor
	Available         bool            `json:"available"`
	UnavailableReason string          `json:"reason,omitempty"`
	Bindings          []string        `json:"bindings"`
	Alias             *string         `json:"alias"`
	GlobalShortcut    *GlobalShortcut `json:"global_shortcut,omitempty"`
}

type Row

type Row struct {
	ID          string            `json:"id"`
	Title       string            `json:"title"`
	Subtitle    string            `json:"subtitle,omitempty"`
	Icon        string            `json:"icon,omitempty"`
	Badge       *ViewBadge        `json:"badge,omitempty"`
	Keywords    []string          `json:"keywords,omitempty"`
	Accessories []string          `json:"accessories,omitempty"`
	Detail      *DetailBody       `json:"detail,omitempty"`
	Actions     []RowAction       `json:"actions,omitempty"`
	Requires    map[string]string `json:"requires,omitempty"`
	Fallback    string            `json:"fallback,omitempty"`
}

type RowAction

type RowAction struct {
	Title        string            `json:"title"`
	Icon         string            `json:"icon,omitempty"`
	Section      string            `json:"section,omitempty"`
	Primary      bool              `json:"primary,omitempty"`
	Destructive  bool              `json:"destructive,omitempty"`
	Confirmation *Confirmation     `json:"confirmation,omitempty"`
	Shortcut     string            `json:"shortcut,omitempty"`
	Action       *Action           `json:"action,omitempty"`
	Handler      string            `json:"handler,omitempty"`
	SubmitForm   bool              `json:"submit_form,omitempty"`
	Requires     map[string]string `json:"requires,omitempty"`
	Fallback     string            `json:"fallback,omitempty"`
}

type Section

type Section struct {
	Title string `json:"title,omitempty"`
	Rows  []Row  `json:"rows"`
}

type Service

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

func NewRegistry

func NewRegistry(
	providers []ProviderRegistration,
	clients ClientDirectory,
	bindings BindingsResolver,
	executor ActionExecutor,
	options ...Option,
) (*Service, error)

func (*Service) AckEffects

func (s *Service) AckEffects(ctx context.Context, token SessionToken, effectIDs []string) error

AckEffects fences acknowledged effect ids from every replay path.

func (*Service) AdmitEvent

func (s *Service) AdmitEvent(ctx context.Context, token SessionToken, event ViewEvent) error

AdmitEvent applies effect acknowledgements, enforces admission caps, and starts the extension handler without tying its lifetime to the HTTP request.

func (*Service) BindableIDs

func (s *Service) BindableIDs(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) ([]CommandID, error)

BindableIDs returns the current workspace catalog ids in deterministic order.

func (*Service) Catalog

func (s *Service) Catalog(
	ctx context.Context,
	request CatalogRequest,
) (Catalog, error)

Catalog returns the workspace command projection, optionally scoped to one attached client's context, with commands sorted by id.

func (*Service) Clients

func (s *Service) Clients(ctx context.Context, workspaceID WorkspaceID) ([]Client, error)

Clients returns the attached shells for a workspace in deterministic id order.

func (*Service) CloseClientSessions

func (s *Service) CloseClientSessions(
	ctx context.Context,
	profileLens ProfileLens,
	workspace WorkspaceID,
	client ClientID,
) error

CloseClientSessions tears down every programmable view owned by a detached client.

func (*Service) CloseSession

func (s *Service) CloseSession(ctx context.Context, token SessionToken, reason string) error

CloseSession tears down one session. A repeated close is successful.

func (*Service) ExtensionDefaults

func (s *Service) ExtensionDefaults(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) ([]ExtensionDefaultShortcut, error)

ExtensionDefaults returns the active and dormant extension shortcut claims in enable order.

func (*Service) InvalidateInstance

func (s *Service) InvalidateInstance(
	ctx context.Context,
	profileLens ProfileLens,
	workspace WorkspaceID,
	extension string,
	generation uint64,
) error

InvalidateInstance disposes sessions from every replaced process generation.

func (*Service) Invoke

func (s *Service) Invoke(ctx context.Context, request InvokeRequest) (InvokeResult, error)

func (*Service) NotifyAliasChanged

func (s *Service) NotifyAliasChanged(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	commandID CommandID,
)

NotifyAliasChanged records one effective alias mutation.

func (*Service) NotifyBindingChanged

func (s *Service) NotifyBindingChanged(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	commandID CommandID,
)

NotifyBindingChanged records one effective shortcut mutation.

func (*Service) NotifyCatalogChanged

func (s *Service) NotifyCatalogChanged(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) error

func (*Service) NotifyGlobalHotkeyRegistrationFailed

func (s *Service) NotifyGlobalHotkeyRegistrationFailed(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	clientID ClientID,
	commandID CommandID,
	chord string,
	reason string,
)

NotifyGlobalHotkeyRegistrationFailed records one shell registration failure.

func (*Service) OpenSession

func (s *Service) OpenSession(
	ctx context.Context,
	request ViewSessionOpenRequest,
) (ViewSessionOpenResult, error)

OpenSession creates one client- and extension-instance-bound program session.

func (*Service) OpenSource

func (s *Service) OpenSource(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	viewID string,
) (ViewSnapshot, error)

func (*Service) Personalization

func (s *Service) Personalization(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) (Snapshot, error)

func (*Service) PersonalizationSummary

func (s *Service) PersonalizationSummary(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) (PersonalizationSummary, error)

func (*Service) Pin

func (s *Service) Pin(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	commandID CommandID,
) error

func (*Service) PublishFrame

func (s *Service) PublishFrame(ctx context.Context, token SessionToken, frame ViewFrame) error

PublishFrame validates extension ownership, causal freshness, revision order, and effect acknowledgement before fanning a frame out to session subscribers.

func (*Service) RecordUsage

func (s *Service) RecordUsage(ctx context.Context, usage Usage) error

func (*Service) ResetPersonalization

func (s *Service) ResetPersonalization(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) error

func (*Service) ResolveView

func (s *Service) ResolveView(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	viewID string,
) (ViewDescriptor, error)

func (*Service) SubscribeCmdPaletteEvents

func (s *Service) SubscribeCmdPaletteEvents(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
) (<-chan Event, func(), error)

func (*Service) SubscribeSessionFrames

func (s *Service) SubscribeSessionFrames(
	ctx context.Context,
	token SessionToken,
) (ViewFrame, <-chan ViewFrame, func(), error)

SubscribeSessionFrames authorizes one SSE reader and returns a replay-safe frame.

func (*Service) SubscribeViewPatches

func (s *Service) SubscribeViewPatches(
	ctx context.Context,
	request ViewPatchSubscribeRequest,
) (ViewSnapshot, <-chan ViewPatchEvent, func(), error)

func (*Service) Unpin

func (s *Service) Unpin(
	ctx context.Context,
	profileLens ProfileLens,
	workspaceID WorkspaceID,
	commandID CommandID,
) error

type SessionToken

type SessionToken struct {
	ViewSession     string `json:"view_session"`
	StreamToken     string `json:"stream_token,omitempty"`
	AttachmentToken string `json:"-"`
	Extension       string `json:"-"`
}

SessionToken carries exactly one proof used to access a view session. AttachmentToken is supplied by the owning client, StreamToken by the SSE reader, and Extension by the owning extension's Host API call.

type Snapshot

type Snapshot struct {
	ProfileLens ProfileLens   `json:"profile_lens"`
	Weights     Weights       `json:"weights"`
	Usage       []UsageSignal `json:"usage"`
	QueryHits   []QueryHit    `json:"query_hits"`
	Pins        []Pin         `json:"pins"`
	Revision    string        `json:"revision"`
}

type SnapshotBindingsResolver

type SnapshotBindingsResolver interface {
	BindingsForCatalogSnapshot(
		context.Context,
		ProfileLens,
		WorkspaceID,
		[]CommandID,
		[]ExtensionDefaultShortcut,
	) (map[CommandID][]string, map[CommandID]string, error)
}

SnapshotBindingsResolver resolves bindings from the exact contribution snapshot used by Catalog.

type SnapshotGlobalBindingsResolver

type SnapshotGlobalBindingsResolver interface {
	GlobalBindingsForCatalogSnapshot(
		context.Context,
		ProfileLens,
		WorkspaceID,
		[]CommandID,
	) (map[CommandID]string, error)
}

SnapshotGlobalBindingsResolver resolves intended global bindings from the catalog snapshot.

type Source

type Source struct {
	Kind      SourceKind `json:"kind"`
	Extension string     `json:"extension,omitempty"`
}

func (Source) ID

func (s Source) ID() string

type SourceHealth

type SourceHealth string
const (
	SourceHealthy   SourceHealth = "healthy"
	SourceDegraded  SourceHealth = "degraded"
	SourceUnhealthy SourceHealth = "unhealthy"
	SourceDisabled  SourceHealth = "disabled"
)

type SourceKind

type SourceKind string
const (
	SourceKindCore      SourceKind = "core"
	SourceKindExtension SourceKind = "extension"
)

type SourceStatus

type SourceStatus struct {
	Source string       `json:"source"`
	Status SourceHealth `json:"status"`
	Reason string       `json:"reason,omitempty"`
}

type StaticProvider

type StaticProvider interface {
	Provider
	StaticCommands() []Descriptor
}

type ToastEffect

type ToastEffect struct {
	Tone    string `json:"tone"`
	Message string `json:"message"`
}

type UnavailableError

type UnavailableError struct {
	Reason string
}

func (*UnavailableError) Error

func (e *UnavailableError) Error() string

type UnknownViewKindError

type UnknownViewKindError struct {
	Kind ViewKind
}

UnknownViewKindError reports a view kind this host cannot render. Match with errors.As.

func (*UnknownViewKindError) Error

func (e *UnknownViewKindError) Error() string

type Usage

type Usage struct {
	ProfileLens ProfileLens
	WorkspaceID WorkspaceID
	CommandID   CommandID
	Query       string
	UsedAt      time.Time
}

type UsageSignal

type UsageSignal struct {
	CommandID  CommandID `json:"command_id"`
	UseCount   int64     `json:"-"`
	Weight     float64   `json:"weight"`
	LastUsedAt int64     `json:"last_used_at"`
}

type ViewBadge

type ViewBadge struct {
	Label string `json:"label"`
	Tone  string `json:"tone"`
}

type ViewChrome

type ViewChrome struct {
	IsLoading   bool        `json:"is_loading,omitempty"`
	SearchText  *string     `json:"search_text,omitempty"`
	EventCount  int64       `json:"event_count,omitempty"`
	Placeholder string      `json:"search_placeholder,omitempty"`
	ThrottleMs  int         `json:"throttle_ms,omitempty"`
	Filtering   *bool       `json:"filtering,omitempty"`
	Complete    bool        `json:"complete,omitempty"`
	ActiveChip  string      `json:"active_chip,omitempty"`
	Columns     int         `json:"columns,omitempty"`
	Pagination  *Pagination `json:"pagination,omitempty"`
	OnSearch    string      `json:"on_search,omitempty"`
	OnChip      string      `json:"on_chip,omitempty"`
	OnSelection string      `json:"on_selection,omitempty"`
	OnLoadMore  string      `json:"on_load_more,omitempty"`
}

type ViewCloseRequest

type ViewCloseRequest struct {
	ViewSession string      `json:"view_session"`
	ProfileLens ProfileLens `json:"profile_lens"`
	Reason      string      `json:"reason,omitempty"`
}

ViewCloseRequest is the extension-facing view/close request.

type ViewDescriptor

type ViewDescriptor struct {
	ID        string          `json:"id"`
	Title     string          `json:"title"`
	Kind      ViewKind        `json:"kind"`
	Source    *ViewToolSource `json:"source,omitempty"`
	Program   bool            `json:"program,omitempty"`
	Extension string          `json:"extension,omitempty"`
}

type ViewEvent

type ViewEvent struct {
	ViewSession  string        `json:"view_session"`
	Handler      string        `json:"handler"`
	Args         []any         `json:"args,omitempty"`
	Revision     string        `json:"revision"`
	Seq          int64         `json:"seq"`
	Generation   uint64        `json:"generation"`
	AckEffects   []string      `json:"ack_effects,omitempty"`
	EffectResult *EffectResult `json:"effect_result,omitempty"`
}

ViewEvent is the extension-facing view/event request.

type ViewFrame

type ViewFrame struct {
	ViewSession string       `json:"view_session"`
	Revision    string       `json:"revision"`
	InReplyTo   int64        `json:"in_reply_to,omitempty"`
	Generation  uint64       `json:"generation"`
	Payload     *ViewPayload `json:"payload,omitempty"`
	Patch       *ViewPatch   `json:"patch,omitempty"`
	Effects     []Effect     `json:"effects,omitempty"`
	Handlers    []string     `json:"handlers"`
}

ViewFrame is one full or incremental programmable-view render.

type ViewKind

type ViewKind string
const (
	ViewKindList   ViewKind = "list"
	ViewKindDetail ViewKind = "detail"
	ViewKindForm   ViewKind = "form"
	ViewKindGrid   ViewKind = "grid"
)

type ViewNotFoundError

type ViewNotFoundError struct {
	ViewID string
}

ViewNotFoundError reports a missing view id. Match with errors.As.

func (*ViewNotFoundError) Error

func (e *ViewNotFoundError) Error() string

type ViewOpenRequest

type ViewOpenRequest struct {
	ViewSession string         `json:"view_session"`
	View        string         `json:"view"`
	ProfileLens ProfileLens    `json:"profile_lens"`
	Workspace   WorkspaceID    `json:"workspace"`
	Client      ClientID       `json:"client"`
	Args        map[string]any `json:"args,omitempty"`
}

ViewOpenRequest is the extension-facing view/open request.

type ViewPatch

type ViewPatch struct {
	ViewID string    `json:"view_id"`
	From   string    `json:"from"`
	To     string    `json:"to"`
	Ops    []PatchOp `json:"ops"`
}

type ViewPatchEvent

type ViewPatchEvent struct {
	ProfileLens ProfileLens
	Sequence    int64
	StreamEpoch string
	Patch       ViewPatch
}

type ViewPatchSubscribeRequest

type ViewPatchSubscribeRequest struct {
	ProfileLens ProfileLens
	Workspace   WorkspaceID
	ViewID      string
	After       int64
	StreamEpoch string
}

type ViewPatchSubscriber

type ViewPatchSubscriber interface {
	SubscribeViewPatches(
		context.Context,
		ViewPatchSubscribeRequest,
	) (<-chan ViewPatchEvent, func(), error)
}

type ViewPayload

type ViewPayload struct {
	View     string      `json:"view"`
	Chrome   *ViewChrome `json:"chrome,omitempty"`
	Sections []Section   `json:"sections,omitempty"`
	Chips    []Chip      `json:"chips,omitempty"`
	Empty    *EmptyState `json:"empty,omitempty"`
	Detail   *DetailBody `json:"detail,omitempty"`
	Form     *FormBody   `json:"form,omitempty"`
	Grid     *GridBody   `json:"grid,omitempty"`
}

ViewPayload is the frozen v1 view wire shared by declarative and programmable views.

func ApplyViewPatch

func ApplyViewPatch(
	kind ViewKind,
	currentRevision string,
	current ViewPayload,
	patch ViewPatch,
	capabilities map[string]string,
	reporter CapabilityGapReporter,
) (payload ViewPayload, revision string, resync bool, err error)

ApplyViewPatch applies an RFC 6902 patch only when its revision fence matches. The resync result is true for every fence gap so callers can request a full payload.

func UnknownViewKindPayload

func UnknownViewKindPayload(kind ViewKind) ViewPayload

UnknownViewKindPayload is the renderer-safe Null Object for a runtime kind gap.

func ValidateViewPayload

func ValidateViewPayload(
	kind ViewKind,
	payload ViewPayload,
	capabilities map[string]string,
	reporter CapabilityGapReporter,
) (ViewPayload, error)

ValidateViewPayload validates and normalizes one payload before it crosses a transport.

type ViewProgramProvider

type ViewProgramProvider interface {
	OpenProgram(context.Context, string, ViewOpenRequest) (ViewFrame, uint64, error)
	HandleProgramEvent(context.Context, ProfileLens, WorkspaceID, string, ViewEvent) (*ViewFrame, error)
	CloseProgram(context.Context, ProfileLens, WorkspaceID, string, ViewCloseRequest) error
}

ViewProgramProvider calls the negotiated view.provider service.

type ViewProviderRegistration

type ViewProviderRegistration struct {
	Descriptor ViewDescriptor
	Provider   ViewSourceProvider
}

type ViewRevisionMismatchError

type ViewRevisionMismatchError struct {
	Current string
	From    string
}

ViewRevisionMismatchError reports a patch fence gap. Match with errors.As.

func (*ViewRevisionMismatchError) Error

func (e *ViewRevisionMismatchError) Error() string

type ViewService

type ViewService interface {
	ViewSourceService
	ViewSessionService
}

ViewService owns both declarative views and programmable sessions.

type ViewSessionOpenRequest

type ViewSessionOpenRequest struct {
	ProfileLens     ProfileLens
	Workspace       WorkspaceID
	Client          ClientID
	AttachmentToken string
	View            string
	Args            map[string]any
}

ViewSessionOpenRequest is the authenticated host request to create a session.

type ViewSessionOpenResult

type ViewSessionOpenResult struct {
	ProfileLens ProfileLens  `json:"profile_lens"`
	Token       SessionToken `json:"-"`
	FirstFrame  ViewFrame    `json:"first_frame"`
}

ViewSessionOpenResult is returned to the attached client after view/open.

type ViewSessionService

type ViewSessionService interface {
	OpenSession(context.Context, ViewSessionOpenRequest) (ViewSessionOpenResult, error)
	AdmitEvent(context.Context, SessionToken, ViewEvent) error
	PublishFrame(context.Context, SessionToken, ViewFrame) error
	AckEffects(context.Context, SessionToken, []string) error
	SubscribeSessionFrames(
		context.Context,
		SessionToken,
	) (ViewFrame, <-chan ViewFrame, func(), error)
	CloseSession(context.Context, SessionToken, string) error
	CloseClientSessions(context.Context, ProfileLens, WorkspaceID, ClientID) error
	InvalidateInstance(context.Context, ProfileLens, WorkspaceID, string, uint64) error
}

ViewSessionService is the Tier-2 programmable-view session authority.

type ViewSnapshot

type ViewSnapshot struct {
	ProfileLens ProfileLens
	Descriptor  ViewDescriptor
	Payload     ViewPayload
	Revision    string
	StreamEpoch string
}

type ViewSourceProvider

type ViewSourceProvider interface {
	OpenSource(context.Context, ProfileLens, WorkspaceID, string) (ViewPayload, error)
}

type ViewSourceService

type ViewSourceService interface {
	ResolveView(context.Context, ProfileLens, WorkspaceID, string) (ViewDescriptor, error)
	OpenSource(context.Context, ProfileLens, WorkspaceID, string) (ViewSnapshot, error)
	SubscribeViewPatches(
		context.Context,
		ViewPatchSubscribeRequest,
	) (ViewSnapshot, <-chan ViewPatchEvent, func(), error)
}

ViewSourceService is the Tier-1 read surface consumed by both API transports.

type ViewToolSource

type ViewToolSource struct {
	Tool     string `json:"tool"`
	ReadOnly bool   `json:"read_only"`
}

type ViewValidationError

type ViewValidationError struct {
	Path    string
	Message string
}

ViewValidationError names the failing wire path. Match with errors.As.

func (*ViewValidationError) Error

func (e *ViewValidationError) Error() string

type Weights

type Weights struct {
	Version                    int      `json:"version"`
	FrecencyHalfLifeDays       int      `json:"frecency_half_life_days"`
	QueryHalfLifeDays          int      `json:"query_half_life_days"`
	Deadband                   float64  `json:"deadband"`
	FallbackWeakMatchThreshold float64  `json:"fallback_weak_match_threshold"`
	MatchAliasExact            float64  `json:"match_alias_exact"`
	MatchExact                 float64  `json:"match_exact"`
	MatchPrefix                float64  `json:"match_prefix"`
	MatchTokenPrefix           float64  `json:"match_token_prefix"`
	MatchCompactPrefix         float64  `json:"match_compact_prefix"`
	MatchWordBoundaryMin       float64  `json:"match_word_boundary_min"`
	MatchWordBoundaryMax       float64  `json:"match_word_boundary_max"`
	MatchContains              float64  `json:"match_contains"`
	MatchSubsequenceMin        float64  `json:"match_subsequence_min"`
	MatchSubsequenceMax        float64  `json:"match_subsequence_max"`
	SecondaryFieldMultiplier   float64  `json:"secondary_field_multiplier"`
	SecondaryFieldCap          float64  `json:"secondary_field_cap"`
	FrecencyScale              float64  `json:"frecency_scale"`
	FrecencyCap                float64  `json:"frecency_cap"`
	QueryLearningCap           float64  `json:"query_learning_cap"`
	ContextBoost               float64  `json:"context_boost"`
	PromotionCommandFloor      float64  `json:"promotion_command_floor"`
	PromotionPathFloor         float64  `json:"promotion_path_floor"`
	PromotionDefaultFloor      float64  `json:"promotion_default_floor"`
	PromotionTabFloor          float64  `json:"promotion_tab_floor"`
	GhostMinScore              float64  `json:"ghost_min_score"`
	MinEntityQueryLength       int      `json:"min_entity_query_length"`
	MaxQueryLength             int      `json:"max_query_length"`
	PruneAfterDays             int      `json:"prune_after_days"`
	PruneThreshold             float64  `json:"prune_threshold"`
	EntitySectionVisibleCap    int      `json:"entity_section_visible_cap"`
	DomainViewMountCap         int      `json:"domain_view_mount_cap"`
	GroupOrder                 []string `json:"group_order"`
}

Weights is the versioned scorer configuration served to attached clients.

type WorkspaceID

type WorkspaceID string

Directories

Path Synopsis
Package corecmds provides the complete daemon-owned core command inventory.
Package corecmds provides the complete daemon-owned core command inventory.

Jump to

Keyboard shortcuts

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