engine

package
v0.5.0-beta.5 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 23 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 engine runs audiosmith-engine, the Swift helper that does the speech work, and talks to it: a Supervisor runs one process per role and speaks protocol 2 (package proto, docs/protocol-v2.md) with it, and RegisterExecutors runs engine methods as jobs of the jobs.Scheduler.

Index

Constants

View Source
const (
	// CodeEngineUnavailable: the worker was not ready (starting after a
	// crash, failed, stopped). Retryable.
	CodeEngineUnavailable = "engine_unavailable"
)

Job error codes the executors add to the protocol's (proto.Code*).

Variables

View Source
var ErrWorkerExited = fmt.Errorf("engine worker exited: %w", core.ErrEngine)

ErrWorkerExited is wrapped by Call errors when the worker died mid-call.

ExecutorKinds are the job kinds RegisterExecutors registers: every job method of the protocol except capture.start, which is interactive and runs outside the queue (StartCapture). Submit them on the lane of their role: jobs.Lane(proto.RoleOf(kind)). Dictation runs stt.transcribe and models.load on the listen worker too, as the kinds proto.KindFor(proto.RoleListen, method) on jobs.LaneListen.

Functions

func Devices

func Devices(ctx context.Context, sup Supervisor) ([]proto.CaptureDevice, error)

Devices lists the audio inputs, the system default first (capture.devices on the listen worker).

func Executor

func Executor(sup Supervisor, role proto.Role, method string, opts ...ExecutorOptions) jobs.Executor

Executor runs jobs of kind method as requests to the worker of role, with the job's id as request id. job.progress becomes the job's progress, tts.chunk, llm.token and tts.turn its chunks (the notification's params JSON); a log line naming the job is left to the bus. Errors become *jobs.Error with the protocol's code: oom and busy are retryable, and so is the worker dying mid-job (jobs.CodeInterrupted) or not being ready (CodeEngineUnavailable) — the job's MaxAttempts decides whether it runs again. opts, when given, are RegisterExecutors's: the app's renders, transcripts and dub steps fill their models' paths themselves but pass AuxPaths, so their auxiliary repos load at the pinned snapshots too.

func Find

func Find(resources string) string

Find looks for audiosmith-engine: $AUDIOSMITH_ENGINE, then the app's resources (packaged, mygo dev, or go run from the project). It returns an absolute path, or "" when there is none.

func KindExecutor

func KindExecutor(sup Supervisor, kind string, opts ...ExecutorOptions) jobs.Executor

KindExecutor runs jobs of kind (a method, or "role:method" from proto.KindFor) on the worker its kind names, as RegisterExecutors's executors do (with opts, when given).

func Probe

func Probe(ctx context.Context, sup Supervisor, path string) (proto.ProbeResult, error)

Probe describes a media file (media.probe on the media worker).

func RegisterExecutors

func RegisterExecutors(sched jobs.Scheduler, sup Supervisor, opts ...ExecutorOptions)

RegisterExecutors registers the engine-backed job kinds (ExecutorKinds) on sched, each run on the worker of its role (proto.RoleOf). A job's Params are the method's params (proto.LoadParams, proto.SynthesizeParams, proto.TranscribeParams…) and its Result the method's result.

Types

type Config

type Config struct {
	Bin   string       // audiosmith-engine executable (Find)
	Roles []proto.Role // roles Start runs; default gpu
	// OnDemand roles start with the first Call to them (and after Restart),
	// not with Start: the listen and media workers, which most sessions
	// never need. Status lists them (stopped until then).
	OnDemand   []proto.Role
	AppVersion string    // sent in engine.hello
	CacheDir   string    // HF hub cache (hub.CacheDir), sent in engine.hello
	Offline    bool      // engines never download; the Go hub does (M0 goal)
	LogDir     string    // stderr of role r goes to LogDir/engine-<r>.log (rotated)
	Bus        *core.Bus // StatusChanged (and log lines when Log is nil)
	// Log receives the engines' log notifications and stderr lines, with
	// Source "engine:<role>" (the app's logs.Ring.Append). nil publishes
	// them on Bus as core.LogAppended.
	Log func(core.LogEntry)
	// Prepare runs before every start of a worker, e.g. to remove what a
	// failed model load left in the HF cache (hub.CleanEngineCopies).
	Prepare func(proto.Role)
	// MemoryBudget is the bytes resident models of all workers may take
	// together; above it the supervisor unloads the least recently used
	// idle models (models.unload). 0 means 60% of physical memory.
	MemoryBudget int64
	// Family, when set, shares the budget with the other ActNow family
	// apps (supervise_family.go): it caps MemoryBudget, hears what the
	// workers hold, and is asked for memory before a load that does not
	// fit; its requests unload the models idle for a minute.
	Family Family
	// IdleUnload unloads a model nobody used for this long (settings:
	// "Unload idle models"); 0 keeps models until the budget needs room.
	IdleUnload time.Duration
	// HelloTimeout bounds the handshake (default 30 s: first launch
	// compiles Metal shaders).
	HelloTimeout time.Duration
	// MaxRestarts bounds automatic restarts within RestartWindow (default 3
	// in 10 min); beyond it the worker stays failed until Restart.
	MaxRestarts   int
	RestartWindow time.Duration
	// CancelGrace is how long a cancelled job may take to end before its
	// worker is killed and restarted (default 5 s).
	CancelGrace time.Duration
	// WriteTimeout bounds one request's write to the engine's stdin
	// (default 10 s): an engine that stops reading is killed (FailStuck)
	// and restarted instead of blocking every caller, cancel and shutdown.
	WriteTimeout time.Duration
	// StopTimeout is how long Stop waits for a process to exit after
	// engine.shutdown and closing its stdin before killing it (default 3 s).
	StopTimeout time.Duration
	// StatsEvery is how often engine.stats is polled while jobs run
	// (default 2 s); it is also polled when a job starts and ends.
	// Negative: never (tests).
	StatsEvery time.Duration
	// Env is added to the engine processes' environment (HF_HUB_CACHE,
	// proxies…; tests select a fake engine with it).
	Env  []string
	Logf func(format string, args ...any) // supervisor diagnostics; default log.Printf
}

Config configures a Supervisor.

type ExecutorOptions

type ExecutorOptions struct {
	// ModelPath returns the local snapshot directory of a model (repo id),
	// or an error wrapping core.ErrNotDownloaded. When set, every job with
	// a model gets the path filled in (proto.LoadParams.Path, the others'
	// modelPath) as it
	// starts, so engines running offline load what the app downloaded. A
	// model that is not on disk fails the job with model_not_downloaded
	// without asking the engine. nil leaves params as submitted.
	ModelPath func(ctx context.Context, model string) (string, error)
	// AuxPaths returns the snapshot directories of a model's auxiliary
	// repos (repo id → directory: Kokoro's G2P, Whisper's tokenizer),
	// filled into the job as auxPaths (proto.ParamAuxPaths) with its
	// path: the engine links mlx-audio-swift's folders of those repos to
	// them instead of letting it pick a snapshot (the ActNow family spec
	// §7.1). nil or empty sends none.
	AuxPaths func(ctx context.Context, model string) map[string]string
	// Licences, when set, is asked again before a job loads or runs a
	// model (the services ask first; jobs submitted some other way, or
	// re-run after the acceptance was withdrawn, are caught here): a
	// refusal fails the job with licence_required.
	Licences core.LicenceService
}

ExecutorOptions configure the engine executors.

type FailReason

type FailReason string

FailReason classifies a failed worker, so the UI can explain it in the user's language and offer the right fix.

const (
	FailMissing   FailReason = "missing"   // no executable: build it (scripts/build-engine.sh) or set AUDIOSMITH_ENGINE
	FailStart     FailReason = "start"     // the executable could not be started
	FailProtocol  FailReason = "protocol"  // it speaks another protocol version or role: rebuild it; not restarted
	FailHandshake FailReason = "handshake" // engine.hello was not answered in time
	FailCrashed   FailReason = "crashed"   // it exited without being asked to
	FailStuck     FailReason = "stuck"     // killed because a cancelled job did not stop within the grace period
)

type Family

type Family interface {
	// Budget is the bytes this app's models may take: at most own (the
	// setting; 0 = none), and the family's share of physical memory (the
	// engine's report; 0 = unknown) less what the other running family
	// apps have loaded.
	Budget(own, physical int64) int64
	// Publish records the models the workers hold now, by role, and the
	// budget (the app's runtime file).
	Publish(loaded map[proto.Role][]proto.LoadedModel, budget int64)
	// RequestMemory asks the other family apps to unload their idle
	// models and waits a moment for them to do so.
	RequestMemory(ctx context.Context)
	// Requested receives the other apps' requests for memory.
	Requested() <-chan struct{}
	// UnloadIdleAfter is how long a model must have been idle to be
	// unloaded on another app's request (a minute).
	UnloadIdleAfter() time.Duration
}

Family is the ActNow family's memory coordination (Config.Family). Methods may read and write small files; the supervisor calls them without its lock held.

type Recording

type Recording struct {
	ID string // the capture.start request id
	// contains filtered or unexported fields
}

Recording is a microphone recording running on the listen worker (capture.start). Stop ends it and keeps the file; Cancel discards it.

func StartCapture

func StartCapture(ctx context.Context, sup Supervisor, id string, p proto.CaptureParams, level func(proto.LevelParams)) (*Recording, error)

StartCapture starts recording p and returns once the engine reports the device running (after macOS asked for microphone access, the first time), or with its error: CodePermissionDenied, CodeDeviceUnavailable… level receives the meter (capture.level, about 20 Hz) on the engine's reader goroutine: it must not block (post to the UI). ctx bounds the start only; the recording runs until Stop, Cancel, p.MaxSeconds, or the device going away (Done, Result). id "" picks a new ULID.

func (*Recording) Cancel

func (r *Recording) Cancel()

Cancel discards the recording (job.cancel) and waits for it to end.

func (*Recording) Done

func (r *Recording) Done() <-chan struct{}

Done is closed when the recording has ended (Result is then set).

func (*Recording) Result

func (r *Recording) Result() (proto.CaptureResult, error)

Result is the recording's outcome once Done is closed: the file, or the error (context.Canceled after Cancel).

func (*Recording) Stop

Stop ends the recording and returns it (capture.stop, then the job's result). It is safe after the recording ended by itself.

type StatusChanged

type StatusChanged struct{ Status WorkerStatus }

StatusChanged is published on the core.Bus whenever a worker's State, PID, loaded models or Err change. Topic "engine.status".

func (StatusChanged) Topic

func (StatusChanged) Topic() string

type Supervisor

type Supervisor interface {
	// Start spawns the configured roles and returns; handshakes complete in
	// the background and are reported as StatusChanged.
	Start(ctx context.Context) error

	// Call sends a request to the worker of role and waits for its
	// response, returning the raw result or an error:
	//   - *proto.Error for an error response (use errors.Is with a code);
	//   - an error wrapping core.ErrEngine when the worker is not ready,
	//     or exits before answering (a job then counts as interrupted).
	// id is the request id; job methods pass the jobs.Job id so logs and
	// notifications correlate, "" lets the supervisor number control
	// requests. notify receives the job's notifications (job.progress,
	// tts.chunk, log lines naming it) on the reader goroutine, in order,
	// before Call returns; it must not block. Cancelling ctx sends
	// job.cancel for job methods and Call returns once the engine answers
	// (or after a 5 s grace, killing the worker if it is stuck).
	Call(ctx context.Context, role proto.Role, id, method string, params any, notify func(proto.Message)) (json.RawMessage, error)

	// Status returns a snapshot of every configured worker.
	Status() []WorkerStatus
	// Restart stops the worker of role (cancelling its calls) and starts a
	// fresh one; it resets the restart budget.
	Restart(role proto.Role) error
	// SetMemoryBudget changes Config.MemoryBudget at run time (settings);
	// 0 is automatic. Models over the new budget are unloaded at once.
	SetMemoryBudget(bytes int64)
	// SetIdleUnload changes Config.IdleUnload at run time.
	SetIdleUnload(d time.Duration)
	// Hold keeps the models of roles resident until release is called
	// (once; more calls do nothing): the supervisor unloads none of them,
	// for the idle limit, the budget or the ActNow family, while
	// something uses them between jobs (a dictation that records, a live
	// call). Holds of a role add up.
	Hold(roles ...proto.Role) (release func())
	// HoldModels is Hold for some models of role only (a dictation
	// pins its recogniser and the clean-up language model, not every
	// model the gpu worker has; code review 1102 M1). A model not
	// resident yet is held once it loads.
	HoldModels(role proto.Role, models ...string) (release func())
	// SetCacheDir changes Config.CacheDir; it applies to the workers
	// started (or restarted) after the call.
	SetCacheDir(dir string)
	// Stop asks every worker to shut down (engine.shutdown), then kills
	// what is left after a grace period. Calls in flight fail with core.ErrEngine.
	Stop()
}

Supervisor runs and talks to the engine workers. Goroutine-safe.

func NewSupervisor

func NewSupervisor(cfg Config) Supervisor

NewSupervisor returns a Supervisor for cfg. Nothing runs until Start.

type WorkerState

type WorkerState string

WorkerState is where an engine process is in its life.

const (
	WorkerStopped  WorkerState = "stopped"  // not started, or stopped on purpose
	WorkerStarting WorkerState = "starting" // spawned, engine.hello not answered yet
	WorkerReady    WorkerState = "ready"    // handshake done, accepting requests
	WorkerFailed   WorkerState = "failed"   // exited or refused; Err and StderrTail say why
)

type WorkerStatus

type WorkerStatus struct {
	Role       proto.Role
	State      WorkerState
	PID        int
	Hello      *proto.HelloResult // nil until ready
	Stats      *proto.StatsResult // last engine.stats, polled while jobs run; nil before the first
	Running    []string           // ids of requests in flight
	Err        string             // why it failed, in English (details for logs and bug reports)
	Reason     FailReason         // why it failed, for a translated message; "" unless failed
	StderrTail string             // last stderr lines after a crash
	Restarts   int                // automatic restarts since Start
	RestartAt  time.Time          // when the next automatic restart happens; zero = none planned
	Since      time.Time          // when State last changed
}

WorkerStatus is a snapshot of one worker, for the status bar, the ⌘E switcher and the Engine/Diagnostics pages.

Directories

Path Synopsis
Package enginetest is a scripted protocol-2 audiosmith-engine for tests: a test binary runs it instead of its tests when AUDIOSMITH_FAKE_ENGINE is set, so the supervisor spawns a real process and talks to it over real pipes, without MLX.
Package enginetest is a scripted protocol-2 audiosmith-engine for tests: a test binary runs it instead of its tests when AUDIOSMITH_FAKE_ENGINE is set, so the supervisor spawns a real process and talks to it over real pipes, without MLX.
Package proto is the wire format of protocol v2 between AudioSmith and audiosmith-engine: JSON-RPC-shaped messages, one per line, over the engine's stdin (app → engine) and stdout (engine → app).
Package proto is the wire format of protocol v2 between AudioSmith and audiosmith-engine: JSON-RPC-shaped messages, one per line, over the engine's stdin (app → engine) and stdout (engine → app).

Jump to

Keyboard shortcuts

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