modes

package
v0.1.0-alpha.53 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: GPL-3.0 Imports: 11 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
	// Requested marks a hold the human asked for in chat, so status can say why
	// Autopilot is leaving the motion alone. It behaves exactly like Hold.
	Requested 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
	CurrentFlow       *motion.FlowSpec
	MotionMinSeconds  int
	MotionMaxSeconds  int
	MotionChangeLevel int
	// These session facts are backend-computed read-only input. Phrase age
	// measures unchanged semantic shape/texture, excluding pace and the scheduler
	// horizon; the decision counts let the model distinguish one sensible hold
	// from accumulated sameness without requiring a change. None of these facts
	// authorizes motion or feeds an automatic intensity score.
	SessionSeconds           int
	SecondsAtCurrentSpeed    int
	SecondsAtCurrentPhrase   int
	DecisionsAtCurrentPhrase int
	ConsecutiveHolds         int
	SpeedTrend               string
	// SessionTracking reports whether the session 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
	// CurrentPerceptual is computed from the shared engine's compiled curve,
	// after selected-device speed and safety fitting. It lets the model reason
	// from felt commanded motion rather than treating any changed JSON field as
	// proof of novelty.
	CurrentPerceptual *motion.PerceptualSummary
	// RecentPositionBands is bounded memory of hidden autonomous outcomes. Chat
	// history cannot supply it because motion-only decisions are intentionally
	// not published as dialogue.
	RecentPositionBands []PositionBand
	// RecentSpeeds is the same kind of memory for pace: the speed each recent
	// stretch used and how long ago it began, oldest first. Without it every
	// planning turn after "that's too much" looked like the moment it was said.
	RecentSpeeds []SpeedStep
	// MotionFeedback is populated only for one semantic quality retry after a
	// model-elected update compiled as continuity.
	MotionFeedback string
}

DecisionInput is bounded, semantic context for one autonomous decision.

type EarlierScore

type EarlierScore struct {
	Flow              *motion.FlowSpec
	StartedSecondsAgo int
	PlayedSeconds     int
}

EarlierScore is a distinct continuous score that played earlier in the run.

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) BeginUserPause

func (m *Manager) BeginUserPause() (func(keepPaused bool), bool)

BeginUserPause blocks autonomous recovery before Engine.Pause performs its transport Stop. During that round-trip the engine is intentionally neither running nor fully marked paused; relying on Snapshot alone lets a mode start a replacement stream in that gap. The completion callback keeps the latch when the engine reached a paused state and rolls it back after an ordinary pause failure. The admission result is false when a newer Pause, Resume, or Stop superseded this request while it waited for another control operation.

func (*Manager) BeginUserResume

func (m *Manager) BeginUserResume() (func(resumed bool), bool)

BeginUserResume returns a completion callback that releases the mode-level latch only when the engine successfully resumes and no newer Pause intent is pending. The next scheduler tick then continues the preserved phrase and clocks instead of creating a replacement start. A false admission result means the engine call must be skipped because a newer control intent won.

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) EarlierScores

func (m *Manager) EarlierScores() []EarlierScore

EarlierScores reports the run's earlier distinct continuous scores, newest first, for a live chat turn. Planning turns do not see them: they re-read an old "go back" and recalled again after chat had already answered it.

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() uint64

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(activityID uint64)

NotifyChatActivityComplete releases autonomous planning after the canonical owning interactive turn has finished. An invalidated turn may unwind after its replacement has started, so completion must carry its activity ID.

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) ReconsiderAfterChat

func (m *Manager) ReconsiderAfterChat()

ReconsiderAfterChat brings Autopilot's next planning boundary forward to now after a live chat turn that left the motion unchanged. The planner reads the human's latest words, and without this a remark such as "that's too much" waited for the rest of the current segment, up to the cadence maximum. Chat that changes the motion re-arms its own segment instead. The planner still runs only after the chat activity completes.

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 PositionBand

type PositionBand struct {
	MinimumPercent float64
	MaximumPercent float64
}

PositionBand describes the compiled position envelope of one recent target. It is an observation for the model, never a target or transport payload.

type Segment

type Segment struct {
	PatternID           motion.PatternID          `json:"pattern_id"`
	Dynamic             *motion.DynamicDefinition `json:"dynamic,omitempty"`
	Flow                *motion.FlowSpec          `json:"flow,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 SpeedStep

type SpeedStep struct {
	SpeedPercent int
	SecondsAgo   int
}

SpeedStep is one recent stretch's speed and how long ago it began.

type Status

type Status struct {
	Active bool   `json:"active"`
	Mode   string `json:"mode,omitempty"`
	Style  string `json:"style,omitempty"`
	// StatusAt and the absolute deadlines let a client render a smooth clock
	// between backend snapshots without inventing its own schedule. The legacy
	// remaining fields stay as a compatibility and clock-skew fallback.
	StatusAt       string `json:"status_at,omitempty"`
	SegmentIndex   int    `json:"segment_index,omitempty"`
	SegmentEndsMs  int64  `json:"segment_ends_in_ms,omitempty"`
	SegmentDueAt   string `json:"segment_due_at,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",
	// "requested_hold" while the human asked chat to keep the motion as it is,
	// 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"`
	MotionChangeDueAt     string `json:"motion_change_due_at,omitempty"`
	SpeechMs              int64  `json:"speech_in_ms,omitempty"`
	SpeechDueAt           string `json:"speech_due_at,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