voice

package
v0.1.0-alpha.46 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: GPL-3.0 Imports: 18 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 voice implements the optional voice worker boundary (ADR 0003): worker process lifecycle, the core-owned request queue, and status. The wire format lives in the leaf package internal/voice/protocol; this package re-exports it so the HTTP edge deals with one voice import. Voice model runtimes are separate processes; a missing or failed worker never affects chat, settings, motion, transport, or diagnostics.

Index

Constants

View Source
const (
	RequestStateQueued   = "queued"
	RequestStateActive   = "active"
	RequestStateDone     = "done"
	RequestStateCanceled = "canceled"
	RequestStateFailed   = "failed"
)

Request lifecycle states shown to the API and UI.

View Source
const (
	RoleTTS = protocol.RoleTTS
	RoleASR = protocol.RoleASR
)

Worker roles.

View Source
const (
	RequestHello      = protocol.RequestHello
	RequestHealth     = protocol.RequestHealth
	RequestLoad       = protocol.RequestLoad
	RequestUnload     = protocol.RequestUnload
	RequestSpeak      = protocol.RequestSpeak
	RequestTranscribe = protocol.RequestTranscribe
	RequestCancel     = protocol.RequestCancel
	RequestShutdown   = protocol.RequestShutdown
)

Request frame types.

View Source
const (
	ResponseHello      = protocol.ResponseHello
	ResponseHealth     = protocol.ResponseHealth
	ResponseAudioChunk = protocol.ResponseAudioChunk
	ResponseTranscript = protocol.ResponseTranscript
	ResponseDone       = protocol.ResponseDone
	ResponseCanceled   = protocol.ResponseCanceled
	ResponseError      = protocol.ResponseError
)

Response frame types.

View Source
const (
	ErrorCodeProtocolMismatch  = protocol.ErrorCodeProtocolMismatch
	ErrorCodeInvalidRequest    = protocol.ErrorCodeInvalidRequest
	ErrorCodeModelNotLoaded    = protocol.ErrorCodeModelNotLoaded
	ErrorCodeMissingDependency = protocol.ErrorCodeMissingDependency
	ErrorCodeCanceled          = protocol.ErrorCodeCanceled
	ErrorCodeTimeout           = protocol.ErrorCodeTimeout
	ErrorCodeInternal          = protocol.ErrorCodeInternal
)

Structured worker error codes.

View Source
const (
	RejectedNoSpeech      = protocol.RejectedNoSpeech
	RejectedLowConfidence = protocol.RejectedLowConfidence
)

Transcript rejection reasons.

View Source
const (
	ModelStateUnloaded = protocol.ModelStateUnloaded
	ModelStateLoading  = protocol.ModelStateLoading
	ModelStateReady    = protocol.ModelStateReady
)

Model states reported by health responses.

View Source
const ProtocolVersion = protocol.Version

ProtocolVersion is the protocol version this core speaks.

Variables

This section is empty.

Functions

This section is empty.

Types

type AudioChunk

type AudioChunk struct {
	Data       []byte       `json:"data"`
	Format     string       `json:"format"`
	State      string       `json:"state"`
	Offset     int          `json:"offset"`
	NextOffset int          `json:"next_offset"`
	Done       bool         `json:"done"`
	Error      *WorkerError `json:"error,omitempty"`
}

AudioChunk is a bounded slice for progressive playback. The HTTP edge checks the live controller lease on every pull; cancellation is checked atomically with the copy so invalidated audio cannot be retrieved by a later request.

type Config

type Config struct {
	TTS WorkerConfig
	ASR WorkerConfig
}

Config is the manager-level configuration derived from settings.

func (Config) Equal

func (c Config) Equal(other Config) bool

Equal reports whether applying other would leave both worker processes on the same launch configuration. Runtime speech controls are carried on each request and therefore do not belong here.

type Manager

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

Manager owns the per-role supervisors and a bounded log of recent requests. It is the single voice entry point for the HTTP edge.

func NewManager

func NewManager() *Manager

NewManager creates supervisors for every role, all idle.

func (*Manager) CancelInvalidated

func (m *Manager) CancelInvalidated(role Role, requests []*PendingRequest)

CancelInvalidated sends worker-side cancellation after the caller has completed its higher-priority safety work.

func (*Manager) CancelPending

func (m *Manager) CancelPending(role Role) []*PendingRequest

CancelPending cancels only queued or active work for one role. Unlike the Emergency Stop invalidation path, it preserves completed audio and history; interactive chat uses it as an optional speech barge-in policy.

func (*Manager) Configure

func (m *Manager) Configure(config Config)

Configure applies settings to both supervisors.

func (*Manager) InvalidateAll

func (m *Manager) InvalidateAll(role Role) []*PendingRequest

InvalidateAll marks every visible request for a role canceled immediately and returns work that still needs a worker-side cancel frame. Emergency Stop uses this local phase before touching the transport so stale ASR results can no longer be consumed even if the worker is slow to accept cancellation.

func (*Manager) PrepareTranscriptionStaging

func (m *Manager) PrepareTranscriptionStaging(dataDir string) error

PrepareTranscriptionStaging creates this manager's process-session directory and reaps only sessions old enough that no bounded ASR request can own them.

func (*Manager) Request

func (m *Manager) Request(id string) (*PendingRequest, bool)

Request finds a tracked request by ID.

func (*Manager) Requests

func (m *Manager) Requests() []RequestSnapshot

Requests lists tracked request snapshots, newest first.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown stops every worker; called at app close.

func (*Manager) Status

func (m *Manager) Status() map[Role]WorkerStatus

Status returns both workers' snapshots keyed by role.

func (*Manager) Submit

func (m *Manager) Submit(role Role, request Request) (*PendingRequest, error)

Submit queues and tracks non-staged work atomically with respect to Stop invalidation.

func (*Manager) SubmitTranscription

func (m *Manager) SubmitTranscription(audio []byte, format, dataDir string) (*PendingRequest, error)

SubmitTranscription stages raw browser audio as a private short-lived file and sends only its reference over the worker protocol. This keeps real audio below the protocol's NDJSON frame bound and avoids a second base64 copy.

func (*Manager) Track

func (m *Manager) Track(pending *PendingRequest)

Track adds a request to the recent-request log, evicting the oldest and dropping retained audio beyond the newest accepted TTS workload. ASR history never evicts speech that may still be waiting for ordered playback.

func (*Manager) Worker

func (m *Manager) Worker(role Role) *Supervisor

Worker returns the supervisor for a role.

type PendingRequest

type PendingRequest struct {
	ID   string
	Role Role
	Type string
	// contains filtered or unexported fields
}

PendingRequest tracks one queued or completed work request. Snapshots and logs carry only metadata (chunk counts, byte counts, transcript text); retained audio is served exclusively through the lease-gated audio endpoint and is bounded by the retention constants above.

func (*PendingRequest) Audio

func (p *PendingRequest) Audio() ([]byte, string)

Audio returns a copy of the retained audio and its format ("" when none is retained). Raw audio never appears in snapshots, traces, or logs.

func (*PendingRequest) AudioChunk

func (p *PendingRequest) AudioChunk(offset int) (AudioChunk, error)

AudioChunk copies at most 32 KiB beginning at offset, with atomic lifecycle state.

func (*PendingRequest) Snapshot

func (p *PendingRequest) Snapshot() RequestSnapshot

Snapshot returns a copy safe to serialize.

func (*PendingRequest) Text

func (p *PendingRequest) Text() string

Text returns the submitted speak text (empty for other request types). The speak text is the same reply already visible in the chat log, so exposing it to in-process callers reveals nothing new; it still never enters status snapshots or logs.

type Request

type Request = protocol.Request

Request is the core → worker frame.

type RequestSnapshot

type RequestSnapshot struct {
	ID               string                `json:"id"`
	Role             Role                  `json:"role"`
	Type             string                `json:"type"`
	State            string                `json:"state"`
	CreatedAt        string                `json:"created_at"`
	AudioChunks      int                   `json:"audio_chunks,omitempty"`
	AudioBytes       int                   `json:"audio_bytes,omitempty"`
	AudioFormat      string                `json:"audio_format,omitempty"`
	FirstAudioMillis int64                 `json:"first_audio_ms,omitempty"`
	CompletionMillis int64                 `json:"completion_ms,omitempty"`
	AudioTruncated   bool                  `json:"audio_truncated,omitempty"`
	Transcript       []TranscriptCandidate `json:"transcript,omitempty"`
	Rejected         string                `json:"rejected,omitempty"`
	Error            *WorkerError          `json:"error,omitempty"`
}

RequestSnapshot is the JSON view of one request's progress.

type Response

type Response = protocol.Response

Response is the worker → core frame.

type Role

type Role = protocol.Role

Role identifies which voice capability a worker provides.

func ParseRole

func ParseRole(value string) (Role, error)

ParseRole validates a role string from the API edge.

func Roles

func Roles() []Role

Roles lists the supported worker roles in display order.

type Supervisor

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

Supervisor owns one worker process: lifecycle, handshake, the serialized request queue, crash detection, and status. All methods are safe for concurrent use.

func NewSupervisor

func NewSupervisor(role Role) *Supervisor

NewSupervisor creates a stopped supervisor for one worker role.

func (*Supervisor) Cancel

func (s *Supervisor) Cancel(pending *PendingRequest)

Cancel cancels a queued or active request by ID and tells the worker.

func (*Supervisor) Health

func (s *Supervisor) Health(ctx context.Context) (Response, error)

Health performs a live health round-trip and caches the result for status snapshots. It fails fast when the worker is not running.

func (*Supervisor) Restart

func (s *Supervisor) Restart(ctx context.Context) error

Restart is stop-then-start with the current configuration.

func (*Supervisor) SetConfig

func (s *Supervisor) SetConfig(config WorkerConfig)

SetConfig applies settings. A config change stops a running worker so the next start uses the new command; it never starts one implicitly.

func (*Supervisor) SetModelLoaded

func (s *Supervisor) SetModelLoaded(ctx context.Context, loaded bool) (Response, error)

SetModelLoaded asks the worker to load or unload its model.

func (*Supervisor) Shutdown

func (s *Supervisor) Shutdown()

Shutdown stops the worker without reporting an error; used at app close.

func (*Supervisor) Start

func (s *Supervisor) Start(ctx context.Context) error

Start launches the worker process and performs the hello handshake. It is an error if voice is disabled or no command is configured; a failed handshake tears the process back down.

func (*Supervisor) Status

func (s *Supervisor) Status() WorkerStatus

Status reports the current lifecycle snapshot without touching the worker.

func (*Supervisor) Stop

func (s *Supervisor) Stop(ctx context.Context) error

Stop shuts the worker down gracefully: shutdown frame, a short grace window, then a hard kill. Stopping an idle supervisor is a no-op.

func (*Supervisor) Submit

func (s *Supervisor) Submit(request Request) (*PendingRequest, error)

Submit queues one speak/transcribe request. The queue is bounded and rejects new work when full (catch-up flooding protection; a configurable drop-oldest policy arrives with real audio playback).

type TranscriptCandidate

type TranscriptCandidate = protocol.TranscriptCandidate

TranscriptCandidate is one ASR hypothesis with its confidence.

type WorkerConfig

type WorkerConfig struct {
	Enabled    bool
	Command    string
	Args       []string
	Env        map[string]string
	JobTimeout time.Duration
}

WorkerConfig is the per-role launch configuration derived from settings. Env carries provider credentials (e.g. the ElevenLabs API key) to the worker process privately — never on the command line, never in status.

type WorkerError

type WorkerError = protocol.WorkerError

WorkerError is the structured error payload carried by error responses.

type WorkerState

type WorkerState string

WorkerState is the lifecycle state shown to the API and UI.

const (
	// StateDisabled means voice is switched off in settings.
	StateDisabled WorkerState = "disabled"
	// StateNotConfigured means voice is enabled but no worker command is set.
	StateNotConfigured WorkerState = "not_configured"
	// StateStopped means the worker is configured but not running.
	StateStopped WorkerState = "stopped"
	// StateStarting means the process is up but the hello handshake is pending.
	StateStarting WorkerState = "starting"
	// StateRunning means the handshake succeeded and requests are accepted.
	StateRunning WorkerState = "running"
	// StateCrashed means the process exited without being asked to stop.
	StateCrashed WorkerState = "crashed"
)

type WorkerStatus

type WorkerStatus struct {
	Role            Role        `json:"role"`
	State           WorkerState `json:"state"`
	Configured      bool        `json:"configured"`
	Command         string      `json:"command,omitempty"`
	Provider        string      `json:"provider,omitempty"`
	ProviderVersion string      `json:"provider_version,omitempty"`
	ProtocolVersion int         `json:"protocol_version,omitempty"`
	Capabilities    []string    `json:"capabilities,omitempty"`
	ModelState      string      `json:"model_state,omitempty"`
	WorkerQueue     int         `json:"worker_queue_depth"`
	QueueDepth      int         `json:"queue_depth"`
	ActiveRequestID string      `json:"active_request_id,omitempty"`
	StartedAt       string      `json:"started_at,omitempty"`
	LastError       string      `json:"last_error,omitempty"`
	StderrTail      string      `json:"stderr_tail,omitempty"`
}

WorkerStatus is the JSON status snapshot for one worker. It never contains secrets: command lines are local user settings, stderr is capped, and no request payloads are included.

Directories

Path Synopsis
Package elevenlabsworker implements the ADR 0003 worker protocol for the ElevenLabs cloud TTS API (ADR 0007's premium non-Python path).
Package elevenlabsworker implements the ADR 0003 worker protocol for the ElevenLabs cloud TTS API (ADR 0007's premium non-Python path).
Package openaittsworker adapts an OpenAI-compatible text-to-speech HTTP service to MagicHandy's ADR 0003 worker protocol.
Package openaittsworker adapts an OpenAI-compatible text-to-speech HTTP service to MagicHandy's ADR 0003 worker protocol.
Package parakeetworker implements the ADR 0003 worker protocol for ASR by proxying to an OpenAI-compatible transcription server.
Package parakeetworker implements the ADR 0003 worker protocol for ASR by proxying to an OpenAI-compatible transcription server.
Package protocol defines the versioned voice worker wire format (ADR 0003): NDJSON frames exchanged between the core and a worker process over stdio.
Package protocol defines the versioned voice worker wire format (ADR 0003): NDJSON frames exchanged between the core and a worker process over stdio.
Package stubworker implements the ADR 0003 worker protocol with no models attached.
Package stubworker implements the ADR 0003 worker protocol with no models attached.
Package workerhost shares the bounded job lifecycle used by provider workers.
Package workerhost shares the bounded job lifecycle used by provider workers.

Jump to

Keyboard shortcuts

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