JavaScript API
Your application controls GAS through one session from @luna-estelar/gas. In a browser, createBrowserSession creates one with Web Audio playback. Run locally is a complete application; the snippets here assume the surrounding objects already exist.
Creating a session
Pass the connector for your model to createSession:
import { createSession } from '@luna-estelar/gas';
import { createLyriaRtConnector } from '@luna-estelar/gas-lyria-rt';
declare function getToken(): Promise<string>;
const session = await createSession({
connector: createLyriaRtConnector({ apiKey: () => getToken() })
});
session.on('audio', (chunk) => {
// PCM in the model's format: send chunk.bytes to your audio output.
});| Option | Behaviour |
|---|---|
connector |
The connector for your model, such as createLyriaRtConnector({ apiKey }) |
connectorConfig? |
A patch over the connector’s default configuration |
clock? |
A MonotonicClock; defaults to performance.now() |
documentDefaults? |
Tempo, time signature, and key for a document that doesn’t set them |
firstAudioTimeoutSeconds? |
How long a playing track may go without audio before the session fails with generation-failed |
firstAudioTimeoutSeconds defaults to three of the model’s chunks and is clamped to 2–15 seconds. Raise it for a connector that reaches the model through a relay or a slow network.
Outside a browser, your application plays the audio chunks itself. Supported models covers Lyria’s options.
Browser session
Import createBrowserSession from @luna-estelar/gas/browser, and call it before the first await in a user gesture, such as a click handler. Some browsers only let audio start inside the gesture.
| Option | Behaviour |
|---|---|
connector |
The connector for your model |
connectorConfig?, documentDefaults?, firstAudioTimeoutSeconds? |
As for createSession |
context? |
Use an existing AudioContext; otherwise the browser session opens and owns one |
prebufferSeconds? |
Playback margin; defaults to one model chunk, clamped to 0.25–4 seconds |
capture? |
Record generated PCM for each Play; off by default |
engine? |
A custom playback engine |
It returns session, audio, context, optional capture, and close().
audio.on('status', listener)reportsidle,buffering,playing,underrun, orstopped, with buffered seconds and underrun count.audio.on('warning', listener)reports rejected chunks, a format mismatch, or a suspended context.- The session emits
audiblePositionas the listener hears each position: every beat, and eachgenerationPositionagain. Use it to draw a playhead. close()releases the session and playback, and closes the audio context if the browser session opened it.
To release a browser session, call browser.close() rather than session.close(), so the audio engine and context are released too.
Loading and source helpers
| Method | Returns |
|---|---|
compileSource(input, options?) |
Promise<CompileResult> with the timeline and diagnostics |
loadSource(input, options?) |
Promise<LoadResult> with support warnings |
loadTimeline(timeline, options?) |
Promise<LoadResult> after validating the timeline |
Load only while stopped. A new document replaces the previous one. A compile or validation failure rejects with kind document. Commands and a second load reject while a document is loading. compileSource and loadSource take name? and timelineId?. loadTimeline takes a precompiled timeline and never loads the parser.
Both load methods take appValues, which decides what happens to the app’s values and tracks:
appValues |
Effect |
|---|---|
'keep' |
The default. App values and tracks carry over to the new document |
'clear' |
Drop them |
Command[] |
Replace them; the load and the new values apply together, or neither does |
With 'keep', a value for a track the new document doesn’t have is dropped with an app-value-dropped warning. If the new document declares an app track’s ID, the load fails with duplicate-track and nothing changes.
Each source helper returns a SourceInput:
| Source helper | Input |
|---|---|
sourceText(text, name?) |
String |
sourceBytes(bytes, name?) |
Uint8Array |
sourceBlob(blob, name?) |
Blob |
sourceFile(file) |
File |
sourceUrl(url, name?) |
URL to fetch |
sourcePath(path) |
Filesystem path, in a host with filesystem access |
Playback
| Method | Behaviour |
|---|---|
play() |
Open a new connection and play from bar 1; resolves once the connection is open |
stop() |
End the connection and silence queued audio; returns at once, and is safe while stopped |
close() |
Close the session for good |
play() rejects with kind state if nothing is loaded or the session is already playing, with provider if the connection can’t open, and with cancelled if Stop or Close came first. When it resolves, the first audio may still be a few seconds away. Supported models gives Lyria’s start-up delays.
A failure during playback emits one error event and leaves the session stopped, with ended: 'failed'. To try again, call play() on the same session. The document and app values stay.
A finite score finishes on its own: the session stops with ended: 'finished', and the browser session plays out the audio it has already received.
While no track plays, GAS writes silence and musical time keeps going. It pauses the model during a rest and resumes it early enough for the next track to come in on its bar.
Commands and app values
Commands take track IDs. A score’s track piano has the ID track.piano: track. followed by the name as reduced by slugify from /protocol. getTracks() lists every ID.
Every change your application makes is an app value. It sits above the score and lasts until your application clears it. App values and the cascade explains how they layer.
| Set | Clear | Live text |
|---|---|---|
setGlobalFlavor(value) |
clearGlobalFlavor() |
flavor "...", flavor clear |
setGlobalLevel(value) |
clearGlobalLevel() |
level 0.5, level clear |
setTrackFlavor(id, value) |
clearTrackFlavor(id) |
piano.flavor "...", piano.flavor clear |
setTrackTimbre(id, value) |
clearTrackTimbre(id) |
piano.timbre "...", piano.timbre clear |
setTrackLevel(id, value) |
clearTrackLevel(id) |
piano.level 0.5, piano.level clear |
apply with setTrackNotes |
clearTrackNotes(id) |
piano.notes alda(...), piano.notes clear |
apply with setTrackMotif |
clearTrackMotif(id) |
piano.motif alda(...), piano.motif clear |
playTrack(id), stopTrack(id) |
clearTrackPlay(id) |
piano.play, piano.stop, piano.release |
setTempo(bpm) |
clearTempo() |
tempo 96, tempo clear |
defineTrack({ id, name?, description? }) |
removeTrack(id) |
track lead "...", track lead clear |
A clear hands the value back to the score. clearTrackPlay hands back whether the track plays. defineTrack adds an app track, which starts inactive, and removeTrack removes one; a document’s track can’t be removed. Levels range from 0 to 1. Tempo is at least 1 and can be fractional. An invalid value or an unknown track rejects with kind command. There are no commands for key or time signature.
apply(commands) takes a list of Command objects from /protocol, and applies all of them or none:
import type { GasSession } from '@luna-estelar/gas';
declare const session: GasSession;
await session.apply([
{ kind: 'setTempo', bpm: 108 },
{ kind: 'setTrackFlavor', trackId: 'track.piano', value: 'tense, short phrases' }
]);Each setter is a one-command apply. Each returns Promise<CommandResult> with any warnings. During playback, it also reports the requestedPosition and appliedPosition of the change; buffered audio can still delay when it is heard.
Commands need a loaded document, and work while stopped or playing. A value set before Play sounds the same as one set during Play. clearAppValues() removes every app value and app track. getState().appValues lists them as commands, which you can pass to apply or to loadSource to restore them.
Live text
submitLiveCommands sends live GAS text, using track names from the score rather than IDs:
import { sourceText } from '@luna-estelar/gas';
import type { GasSession } from '@luna-estelar/gas';
declare const session: GasSession;
const result = await session.submitLiveCommands(sourceText('tempo 96'));
console.log(result.applied);It applies the whole fragment or none of it. It resolves with applied and warnings when every statement applied, and rejects with kind command when the text doesn’t parse or a statement fails. Live input lists what a fragment can contain.
State and events
getState() returns a SessionState:
| Field | Meaning |
|---|---|
status |
stopped, starting, playing, or closed |
loaded |
Whether a document is loaded |
ended? |
How the last Play ended: finished, stopped, or failed; absent before the first Play |
tracks |
TrackView entries with an ID, optional name and description, and a source of document or app |
appValues |
The app tracks and values in effect, as commands |
on(event, listener) returns an unsubscribe function:
| Event | Payload |
|---|---|
state |
SessionState, once for every change |
generationPosition |
Where the model has generated up to |
audiblePosition |
What the listener hears now; browser session only |
audio |
AudioChunk for your output |
warning |
A load, command, or playback warning |
error |
GasOperationError for a provider failure after Play resolved |
generationPosition runs ahead of audiblePosition by the prebuffer and output latency. Use generationPosition to reason about when a change reaches the model, and audiblePosition to drive a UI. Events from an earlier connection are dropped.
Connector and configuration
| Method | Behaviour |
|---|---|
getCapabilities() |
How the connector handles each kind of intent |
getModelInfo() |
The model, its audio format, and its start-up delays |
getConnectorConfig(), getConfigSchema() |
The connector’s configuration, and its JSON Schema |
updateConnectorConfig(patch) |
Change the configuration while stopped |
getDocumentDefaults(), updateDocumentDefaults(patch) |
Read or change the document defaults |
setConnector(connector, config?) |
Swap the connector while stopped |
A connector that implements validateConfig, as Lyria does, checks a new configuration. setConnector doesn’t carry the old configuration over, because each model has its own; config is a patch over the new connector’s defaults. App values stay. Supported models lists Lyria’s settings.
Errors and types
Every method that fails rejects with GasOperationError:
| Field | Meaning |
|---|---|
kind |
document, command, state, provider, or cancelled |
diagnostics, warnings |
Structured details from the operation |
failure |
The underlying command failure, when there is one |
reason |
Connector classification: auth, network, quota, provider, or internal |
retryable |
Whether playing again could help |
closeCode |
Raw WebSocket close code, when there is one |
code, cause |
Further classification or cause, when available |
kind |
Means |
|---|---|
document |
The document doesn’t compile, or the timeline isn’t valid |
command |
A bad value, an unknown track, or live text that doesn’t parse |
state |
The wrong time: nothing loaded, still loading, already playing, or closed |
provider |
The provider failed: Play rejects, or one error event arrives after Play resolved |
cancelled |
Stop or Close came before Play resolved |
Each failure is reported once. Connector messages are sanitised, but build your UI text from kind and reason rather than showing provider text. Troubleshooting covers what to do about each failure.
Types ship with the packages. The root exports GasSession, CreateSessionOptions, CompileOptions, LoadOptions, CompileResult, LoadResult, CommandResult, SubmitLiveCommandsResult, AppliedPosition, SourceInput, ResolvedSource, DefineTrackInput, TrackView, DocumentDefaults, SessionState, SessionStatus, SessionEnded, SessionEvent, SessionEventMap, GenerationPositionEvent, AudiblePositionEvent, SessionWarning, PlayWarning, WarningEvent, and OperationErrorKind. /browser exports BrowserSession and BrowserSessionOptions. Command, Connector, Connection, and the other protocol types come from /protocol. Most entry points also export a version for their package.