modes

package
v0.1.0-alpha.23 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: GPL-3.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package modes implements autonomous motion behaviors (Freestyle, continuous chat) as clients of the motion engine. Modes emit bounded, named segments that deterministic code applies through the engine's retarget API — never a parallel sampler, never transport commands, and never per-turn low-level stream replacement (docs/motion-retargeting.md, "Route Policy Learned On Hardware").

Index

Constants

View Source
const (
	SpeedTrendSteady = "steady"
	SpeedTrendRising = "rising"
	SpeedTrendEasing = "easing"
)

SpeedTrend summarizes where speed has been going, so the model can answer "have I been sitting still?" without being told to guess.

View Source
const (
	// ModeFreestyle is the autonomous arrangement planner.
	ModeFreestyle = "freestyle"
	// ModeAutopilot is Freestyle's loop with the segment choice delegated to
	// an injected LLM curation step; every failure falls back to the
	// deterministic planner (see autopilot.go).
	ModeAutopilot = "autopilot"
	// ModeChat keeps chat-driven motion alive between turns: it re-applies the
	// last chat target only after transport recovery, never after a user stop
	// or pause.
	ModeChat = "chat"
)

Mode identifiers.

Variables

This section is empty.

Functions

This section is empty.

Types

type Announcement

type Announcement struct {
	Published     bool
	RequestID     string
	AwaitPlayback bool
}

Announcement reports whether a line entered canonical chat and whether the scheduler must wait for browser playback before starting the next interval.

type Arrangement

type Arrangement struct {
	Label    string    `json:"label"`
	Segments []Segment `json:"segments"`
}

Arrangement is a bounded, inspectable sequence of segments. Planners and (later) LLM curation produce arrangements; deterministic code compiles them into engine retargets with explicit transition rules.

func NormalizeArrangement

func NormalizeArrangement(arrangement Arrangement) (Arrangement, error)

NormalizeArrangement validates the bounded contract for a whole arrangement.

type DecideFunc

type DecideFunc func(ctx context.Context, input DecisionInput) (Decision, error)

DecideFunc produces one bounded autonomous decision.

type Decision

type Decision struct {
	Segment Segment
	Pattern *motion.PatternDefinition
	Say     string
	Hold    bool
	Next    TimingPreference
	// Variability is how much the target should wander before the next boundary.
	Variability VariabilityPreference
}

Decision is one motion or speech curation outcome. Hold is scheduler-only: it must never produce an engine retarget.

type DecisionInput

type DecisionInput struct {
	Style            string
	SegmentIndex     int
	RecentPatternIDs []string
	SpeedMinPercent  int
	SpeedMaxPercent  int
	LastSay          string
	CurrentPatternID motion.PatternID
	CurrentSpeed     int
	CurrentAreaFocus *motion.AreaFocus
	CurrentDynamic   *motion.DynamicDefinition
	MotionMinSeconds int
	MotionMaxSeconds int
	// SessionSeconds, SecondsAtCurrentSpeed, and SpeedTrend are backend-computed
	// session facts. They are read-only input: the model cannot fabricate them,
	// they appear in traces, and they authorize nothing on their own. This is
	// deliberately not a model-maintained score — an accumulating counter that
	// feeds back into intensity is the hidden-escalation shape
	// docs/goals-and-guardrails.md rules out.
	SessionSeconds        int
	SecondsAtCurrentSpeed int
	SpeedTrend            string
	// SessionTracking reports whether the three fields above are meaningful. When
	// it is false the prompt omits them rather than sending zeros, because a model
	// cannot act on a field it never saw.
	SessionTracking bool
	// ArcEnabled and ArcPercent describe the visible session buildup. Absent from the
	// prompt entirely when disabled.
	ArcEnabled bool
	ArcPercent int
}

DecisionInput is bounded, semantic context for one autonomous decision.

type Engine

type Engine interface {
	Start(ctx context.Context, target motion.MotionTarget, settings config.MotionSettings) (motion.ActiveMotionState, error)
	ApplyTarget(ctx context.Context, target motion.MotionTarget, reason string) (motion.ActiveMotionState, error)
	Snapshot() motion.ActiveMotionState
}

Engine is the narrow motion-engine surface modes may use. Modes never see the transport; the engine owns every dispatch decision.

type Manager

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

Manager owns at most one active mode loop.

func NewManager

func NewManager(options Options) (*Manager, error)

NewManager creates an idle mode manager.

func (*Manager) BeginUserStop

func (m *Manager) BeginUserStop() func()

BeginUserStop marks autonomous work unable to restart and cancels its loop without waiting. The caller can stop the motion engine first, then invoke the returned function to drain and trace the mode goroutine.

func (*Manager) CancelChatTarget

func (m *Manager) CancelChatTarget(generation uint64)

CancelChatTarget releases a failed interactive handoff so the active mode can resume planning on its next tick.

func (*Manager) NotifyAutopilotSettingsChanged

func (m *Manager) NotifyAutopilotSettingsChanged()

NotifyAutopilotSettingsChanged applies saved cadence preferences to the live session without retargeting current motion.

func (*Manager) NotifyChatActivity

func (m *Manager) NotifyChatActivity()

NotifyChatActivity invalidates stale autonomous planning and postpones the independent speech clock even when the interactive turn does not change motion.

func (*Manager) NotifyChatActivityComplete

func (m *Manager) NotifyChatActivityComplete()

NotifyChatActivityComplete releases autonomous planning after the canonical interactive turn has finished. beginChat serializes interactive turns, so a boolean is sufficient and cannot release a newer chat request.

func (*Manager) NotifyChatStop

func (m *Manager) NotifyChatStop()

NotifyChatStop clears the keepalive target after a chat-driven stop.

func (*Manager) NotifyChatTarget

func (m *Manager) NotifyChatTarget(generation uint64, target motion.MotionTarget) bool

NotifyChatTarget adopts a successfully applied chat target for keepalive and as Autopilot's authoritative current segment.

func (*Manager) NotifySpeechPlaybackComplete

func (m *Manager) NotifySpeechPlaybackComplete(requestID string) bool

NotifySpeechPlaybackComplete starts the next speech interval after audible playback, not after inference or enqueue completion.

func (*Manager) NotifyUserStop

func (m *Manager) NotifyUserStop()

NotifyUserStop records an explicit user stop: the active mode ends and no keepalive may restart motion afterwards.

func (*Manager) PrepareChatTarget

func (m *Manager) PrepareChatTarget() uint64

PrepareChatTarget blocks new mode work and invalidates any in-flight decision before an interactive target enters the shared engine.

func (*Manager) ResetSessionArc

func (m *Manager) ResetSessionArc() bool

ResetSessionArc returns buildup to empty. A visible progression the user cannot restart is not really under user control.

It reports false when there is no Autopilot session to place buildup in. Start clears buildup for a fresh run, so accepting a placement beforehand would store a value that is silently discarded a moment later — a call that appears to work and does nothing is worse than one that says no.

func (*Manager) SessionArcSnapshot

func (m *Manager) SessionArcSnapshot() SessionArc

SessionArcSnapshot reports buildup for the UI.

func (*Manager) SetSessionArcPercent

func (m *Manager) SetSessionArcPercent(percent int) bool

SetSessionArcPercent lets the user place the bar directly.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown stops the loop at process exit.

func (*Manager) Start

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

Start activates a mode, replacing any active one.

func (*Manager) Status

func (m *Manager) Status() Status

Status returns the UI-facing mode state.

func (*Manager) Stop

func (m *Manager) Stop(reason string)

Stop deactivates the mode loop. It never stops the engine itself — callers own that decision (user Stop already stops the engine through its own path).

type Options

type Options struct {
	// Ensure returns a startable engine for the selected dispatch owner.
	Ensure func(ctx context.Context) (Engine, error)
	// Current returns the live engine or nil when none exists yet.
	Current func() Engine
	// Settings returns the current motion settings snapshot.
	Settings func() config.MotionSettings
	// AutopilotSettings returns durable cadence and speech-authority settings.
	AutopilotSettings func() config.AutopilotSettings
	// MotionGenerationMode keeps Autopilot fallback inside the selected model
	// vocabulary. Dynamic mode never falls through to the pattern planner.
	MotionGenerationMode func() string
	Traces               *diagnostics.TraceRing
	Now                  func() time.Time
	Tick                 time.Duration
	Seed                 int64
	// MaxSegmentDuration caps armed segment deadlines. It exists for tests
	// that need many segment boundaries quickly; production leaves it zero.
	MaxSegmentDuration time.Duration
	// Decide is Autopilot's injected LLM curation step. Autopilot cannot
	// start without it; Freestyle and chat keepalive never use it.
	Decide DecideFunc
	// DecideSpeech runs the independent autonomous speech contract.
	DecideSpeech DecideFunc
	// CanAnnounce is false while autonomous speech would deepen a TTS backlog.
	CanAnnounce func() bool
	// Announce publishes an Autopilot line and optionally queues browser audio.
	Announce func(ctx context.Context, say string) Announcement
}

Options wires the manager to the app runtime.

type Planner

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

Planner deterministically builds freestyle segments. Given the same seed, style, and settings, the segment sequence is reproducible; the seed and all candidate scores are recorded in planner trace rows.

func NewPlanner

func NewPlanner(seed int64) *Planner

NewPlanner seeds the freestyle planner; a zero seed uses the clock and the effective seed stays visible in every decision row.

func (*Planner) NextSegment

func (p *Planner) NextSegment(settings config.MotionSettings) (Segment, []diagnostics.PlannerScore)

NextSegment scores every pattern for the saved style and returns the next bounded segment plus the full score table for the trace row.

func (*Planner) Seed

func (p *Planner) Seed() int64

Seed returns the planner's effective seed.

func (*Planner) SegmentIndex

func (p *Planner) SegmentIndex() int

SegmentIndex reports how many segments the planner has produced.

type Segment

type Segment struct {
	PatternID           motion.PatternID          `json:"pattern_id"`
	Dynamic             *motion.DynamicDefinition `json:"dynamic,omitempty"`
	SpeedPercent        int                       `json:"speed_percent"`
	DriftToSpeedPercent int                       `json:"drift_to_speed_percent,omitempty"`
	AreaFocus           *motion.AreaFocus         `json:"area_focus,omitempty"`
	DurationMillis      int64                     `json:"duration_ms"`
}

Segment is one bounded step of a motion arrangement: a named pattern at a semantic speed, optionally focused and optionally drifting to a second speed mid-segment. A segment always runs long enough to establish a feel.

func NormalizeSegment

func NormalizeSegment(segment Segment) Segment

NormalizeSegment clamps one segment into the bounded contract.

func (Segment) DriftTarget

func (s Segment) DriftTarget(label string, source string) (motion.MotionTarget, bool)

DriftTarget is the optional mid-segment same-pattern speed nudge; phase is preserved because the pattern does not change.

func (Segment) Target

func (s Segment) Target(label string, source string) motion.MotionTarget

Target converts a segment into the engine's semantic target. The engine clamps speed into the user's limits and owns every transport decision.

type SessionArc

type SessionArc struct {
	Enabled bool `json:"enabled"`
	Percent int  `json:"percent"`
	Minutes int  `json:"minutes"`
}

SessionArc is the UI-facing buildup snapshot. Its name preserves the API schema.

type Status

type Status struct {
	Active         bool   `json:"active"`
	Mode           string `json:"mode,omitempty"`
	Style          string `json:"style,omitempty"`
	SegmentIndex   int    `json:"segment_index,omitempty"`
	SegmentEndsMs  int64  `json:"segment_ends_in_ms,omitempty"`
	LastEvent      string `json:"last_event,omitempty"`
	LastEventAt    string `json:"last_event_at,omitempty"`
	WaitingForChat bool   `json:"waiting_for_chat,omitempty"`
	// DecisionSource reports where Autopilot's current segment came from:
	// "model", "fallback" (planner after a failed decision), "hold", or
	// "interactive" when chat supplied the live target.
	DecisionSource string `json:"decision_source,omitempty"`
	// LastSay is the most recent Autopilot line. The planner uses it to avoid
	// repetition; the API retains it as diagnostic state while Chat owns display.
	LastSay string `json:"last_say,omitempty"`
	// MotionChangeMs and SpeechMs are independent backend-owned clocks.
	MotionChangeMs        int64 `json:"motion_change_in_ms,omitempty"`
	SpeechMs              int64 `json:"speech_in_ms,omitempty"`
	MotionPlanned         bool  `json:"motion_planned,omitempty"`
	SpeechWaitingPlayback bool  `json:"speech_waiting_playback,omitempty"`
	// Arc is the visible session progression bar. Absent when the user has the
	// switch off, so the UI shows nothing rather than an empty bar.
	Arc *SessionArc `json:"session_arc,omitempty"`
}

Status is the UI-facing mode state.

type TimingPreference

type TimingPreference string

TimingPreference is a model-selected semantic timing category. The manager samples the concrete delay inside the user's saved bounds.

const (
	// TimingSoon samples the early part of the configured cadence window.
	TimingSoon TimingPreference = "soon"
	// TimingNormal samples the middle of the configured cadence window.
	TimingNormal TimingPreference = "normal"
	// TimingLater samples the late part of the configured cadence window.
	TimingLater TimingPreference = "later"
)

type VariabilityPreference

type VariabilityPreference string

VariabilityPreference is a model-selected category for how much the motion should wander *inside* the current target, as distinct from how often the target is reconsidered. The two are independent: a persona can hold one pattern for a long stretch while still breathing within it, or change target often while each stretch stays flat.

Like TimingPreference it is a category rather than a number, because a local model emits a category reliably and the backend samples the concrete values — so a model that always answers "normal" still produces varied motion.

const (
	// VariabilitySettled holds the target flat until the next boundary.
	VariabilitySettled VariabilityPreference = "settled"
	// VariabilityNormal takes about half the earned waypoint allowance.
	VariabilityNormal VariabilityPreference = "normal"
	// VariabilityRestless takes the full allowance at a wider amplitude.
	VariabilityRestless VariabilityPreference = "restless"
)

Jump to

Keyboard shortcuts

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