Changelog
v0.4.0
Section titled “v0.4.0”Voice that plays audio: a bot can join a voice channel, play a file or stream, and receive audio, end to end and end-to-end encrypted.
⚠️ Breaking
Section titled “⚠️ Breaking”@lunibee/voiceis rewritten. The 0.3 package modelled connections but carried no audio. See Upgrading:VoiceConnectionStateis gone;VoiceConnectionStatushas the valuessignalling,connecting,ready,disconnectedanddestroyed.attachTransports(),AudioStream,VoiceUdpTransportandVoiceGatewayTransportare removed: the package speaks the voice gateway and UDP itself.joinVoiceChannel()needs anadapterCreator; with a LunibeeClient, useclient.voice.join().createAudioResource(input, options?)takes a path, URL, bytes or stream, and returns anAudioResource.- The player’s statuses are
idle,buffering,playing,pausedandautopaused;stoppedis gone, andplay()is synchronous. receiver.subscribe(userId, options?)returns aReadableStreamof Opus packets.
⚠️ Changed (reliability audit)
Section titled “⚠️ Changed (reliability audit)”-
Clusters split shards in contiguous blocks (they were dealt round-robin):
- 10 shards over 3 clusters are
[0-3] [4-6] [7-9]; shardsPerCluster: 4gives[0-3] [4-7] [8-9](it gave 4/3/3 before);allocateShards()returns the same blocks.
Code that assumed shard
iruns in clusteri % clusterCountmust useclusterForShard()orassignments(). - 10 shards over 3 clusters are
-
A
Clientinside a cluster worker must run one of that cluster’s shards:gateway: { shardId, shardCount }, withshardCountthe deployment’s total. Without them,login()throws instead of IDENTIFYing outside the cluster’s assignment. In a coordinated cluster its IDENTIFYs (the first, and after a lost session) now wait for the parent’s queue likeShardManager’s. -
guildsPerShardnever gives fewer shards than Discord recommends. -
Interactions:
followUp()throws before the interaction is acknowledged.update()anddeferUpdate()reject on interactions that are not components, or modals opened from one.editReply(),deleteReply()andfetchReply()throw after a modal or autocomplete answer.- A Discord 40060 (“already acknowledged”) marks the interaction acknowledged.
-
Restart limits:
ShardSupervisor’smaxRestartscounts restarts with no stablewindowbetween them. Before, it counted restarts inside a sliding window, which the backoff itself could empty.clusterUnstableuses the same count. -
Gateway:
- A heartbeat that is not acknowledged by the next one closes the connection (4900) and resumes, even with a long
heartbeatAckTimeout. connect()while a reconnect is pending joins it instead of skipping the backoff.- Reconnects keep the connect URL’s query (
v,encoding,compress), and IDENTIFY reconnects use the caller’s URL.
- A heartbeat that is not acknowledged by the next one closes the connection (4900) and resumes, even with a long
-
Voice:
- While DAVE is required but its group is not ready yet, Opus frames are dropped; they are no longer sent with transport encryption only.
- Resumable voice closes back off (250 ms doubling to 10 s, 5 attempts), then end as
disconnected(closed). - An FFmpeg failure is the resource’s
error, not afinish.
-
REST: paths with an empty segment (
//) are refused.
🗑️ Removed
Section titled “🗑️ Removed”Old compatibility layers are gone. lunibee migrate --fix renames what it can and lists the rest (Upgrading).
- Compatibility aliases (old → use):
Events→ClientEventShardingManager→ShardManagerDiscordAPIError→RESTErrorCachedManager→ResourceManagerCreateStringSelectMenu→CreateStringSelectCreateUserSelectMenu/CreateRoleSelectMenu/CreateMentionableSelectMenu/CreateChannelSelectMenu→CreateUserSelect/CreateRoleSelect/CreateMentionableSelect/CreateChannelSelect(renamed)Intents→IntentBitsSendBudget→GatewaySendLimiterStatus→GatewayState- types:
CreateMessageOptions→MessageCreateOptions;ClientUser→UserData;InteractionUpdateOptionsandFollowUpOptions→InteractionReplyOptions IntentsBitField: pass an array ofGatewayIntentBits.
- REST call forms:
rest.post/put/patch(path, { body, … })→rest.post/put/patch(path, body, options). The old form is refused with aTypeErrornaming the fix, rather than sending the wrapper as the body.rest.request({ method, path | fullRoute, … })→rest.request(method, path, body, options).toRequest()always returns{ body, files? }.
- WebhookClient payload aliases:
avatarURL,threadIdandallowedMentions→avatar_url,thread_idandallowed_mentions. - CLI:
- Removed commands:
create handler,create command,sync handlers,sync commandsandhandler --fix, the generated-binder layout.lunibee initprojects find their commands and events at runtime. lunibee migratenow migrates code to 0.4.0; the 0.3.1 renames are no longer handled.
- Removed commands:
@lunibee/create: usebunx @lunibee/cli init my-bot.- Docs: the changelog and upgrade guide cover 0.4.0 only; earlier releases are in the Git history.
✨ Added
Section titled “✨ Added”-
client.voice(Voice):join()sends op 4 through the shard that owns the guild, collects the bot’sVOICE_STATE_UPDATEandVOICE_SERVER_UPDATE(in either order, with a timeout), and resolves when audio can flow.leave(),get()andconnectionsare also added. Moves and region changes reconnect. Leaving a guild andclient.destroy()release every connection. -
Voice gateway v8: IDENTIFY, READY, IP discovery, SELECT_PROTOCOL and SESSION_DESCRIPTION, with binary frames and a heartbeat that carries
seq_ack(through@lunibee/ws’sGatewayHeartbeat). It resumes (op 7) on closes below 4000 and on 4015, and follows the close-code table. -
Transport encryption: the
aead_aes256_gcm_rtpsizeandaead_xchacha20_poly1305_rtpsizemodes. AES-GCM runs on the runtime’s synchronousnode:crypto, since WebCrypto would add a promise to every 20 ms packet. XChaCha20-Poly1305 runs on@noble/ciphers, which is audited, pure JS and has no dependencies. -
DAVE end-to-end encryption through the optional peer
@snazzah/davey. Discord has required it outside stage channels since 1 March 2026; without it the voice server closes with 4017, and the error says what to install. Supported: key packages, MLS commits and welcomes, protocol transitions, per-frame encryption,endToEndEncryptedandvoicePrivacyCode. -
Audio:
createAudioResource()passes Ogg/Opus through without re-encoding. It handles raw PCM, Opus packets, and anything FFmpeg reads; FFmpeg is fed on stdin and killed when the resource ends.inlineVolumeis optional.- Lunibee’s own Opus codec,
Opus, runs on the system’s libopus throughbun:ffi: native, with nothing to compile.createOpusCodec()uses it when libopus is installed, elseopusscript, an optional peer. Measured on Bun 1.4.2: encoding a 20 ms frame takes 145–165 µs against 195–210 µs withopusscript; decoding is about the same.
-
AudioPlayer:- a 20 ms clock that corrects its drift, and no timer while idle or paused;
- five silence frames on stop and pause;
noSubscriberandmaxMissedFrames, with thestateChange,finishanderrorevents.
-
VoiceReceiver:- decrypts incoming RTP (transport and DAVE) and maps SSRC to user from op 5;
- per-user streams end after silence; buffers are bounded (
highWaterMark) and released on unsubscribe.
-
entersState()andgenerateDependencyReport(). -
Sharding startup and observability:
startup: "sequential"(ClusterManagerandShardManager) starts one shard at a time across all clusters, each holding its IDENTIFY slot until READY. How long to wait for READY isShardManager’sreadyTimeout(default 60 s); in a cluster it followsidentify.holdTimeout.- New
ClusterManagerevents:plan(total shards, cluster count and where it came from, each cluster’s shards),identify(the IDENTIFY queue, with buckets and waits) andshutdown. - New exports:
planClusters(), the allocationspawn()uses, as a pure function; andconnectInQueue().
-
Recording:
receiver.record(userId)gives an Ogg/Opus stream of a user, not re-encoded, with silence kept so recordings line up.OggOpusWriteris the muxer it uses. -
Effects and a live voice changer:
effectsoncreateAudioResource():pitchShift(),robot(),echo(),gain(), or your own; they can be changed while playing.live: trueplays a user’s voice back through effects without failing on their silence and keeps the delay low.- Video and Go Live stay unsupported: Discord does not allow them for bot accounts.
-
examples/music:/play,/skip,/queue,/stopand/leave. -
lunibee init [directory]: creates a bot project in TypeScript with:- validated configuration from the root
.env; - commands and events found recursively at runtime;
- commands registered with Discord on every start, in
GUILD_ID’s server or globally, with startup stopping when Discord refuses them; /ping, a logger that redacts the token, a README andtsconfig.json.
Existing files are never overwritten without
--force, which asks first.--installrunsbun install.lunibee checkaccepts the layout. - validated configuration from the root
🐛 Fixed
Section titled “🐛 Fixed”-
Sharding:
- A cluster whose process cannot be forked no longer stops the clusters after it:
spawn()used to reject after the first cluster. It is reported with its shards and retried by the restart policy. - Shutdown is bounded even when a killed process never reports its exit.
- The worker contract rejects an empty
SHARD_LISTand aCLUSTER_IDoutsideCLUSTER_COUNT.
- A cluster whose process cannot be forked no longer stops the clusters after it:
-
Reliability audit. These fixes came from an audit of every area, with a reproduction for each finding, now kept as regression tests:
rest.hardeningvoice.hardeningsharding.recoverycache.racesinteractions.lifecyclegateway.hardening
-
REST:
- Aborting a queued request no longer lets the next one run beside the head of its bucket.
- A worker that waited on another’s probe uses the bucket that probe revealed, instead of sending again under the route.
- With a store that has no
reserve, the global slot is taken after the bucket wait. degraded-localcounts the units this process reserved in Redis.
-
Voice:
- The resume loop is bounded (it could open sockets in a busy loop).
join()for the current channel keeps the session.- DAVE encrypt failures are reported once per failure streak.
- No late “IP discovery timed out” error after a leave.
endpoint: nulltimes out.- The Opus codec is freed when a resource is destroyed while it loads, and frames are never encoded after that.
record()’s silence fill respectshighWaterMark.
-
Sharding:
- A late exit of a killed child no longer unregisters the cluster that replaced it.
reshard(n)usesn, so auto-scaling no longer collapses to one shard.- A reshard or destroy during
connect()no longer drives or destroys the new shard set. - Re-IDENTIFYs after a lost session take a slot from the cross-cluster IDENTIFY gate.
- A leader-lock renewal that never settles costs at most one term.
- A worker’s failed send rejects only its own wait.
- An auto-scale respawn keeps
max_concurrency.
-
Cache:
- A REST fetch in flight no longer overwrites a newer Gateway update (members, roles, guilds, channels, users).
- A message deleted during a fetch is not cached again.
members.*androles.*REST results merge into the cached instance.- With the
Guildsintent, member and ban events of a guild the bot left create no per-guild state. - New opt-in
cache.maxUsersboundsclient.users(LRU).
-
Interactions:
editReply(),deleteReply()andfollowUp()use the interaction’s application ID, not the bot user’s. -
Packaging:
lunibeeand its subpaths (lunibee/rest, …) share one copy of each class, and one declaration of each type, soinstanceofand assignments work across them. -
setSpeakingsends the negotiated SSRC instead of0. -
A paused player no longer polls every 25 ms.
-
The
assertUsableindirection is removed. -
The optional peers (
@snazzah/davey,opusscript) are loaded at run time, so a bundle of an app that useslunibeedoes not inline their native or WebAssembly binaries.
📚 Documentation
Section titled “📚 Documentation”- New Voice guide and Voice reference.
🧪 Testing
Section titled “🧪 Testing”- A scripted fake voice server (WebSocket v8 and UDP, with its own rtpsize encryption) covers:
- the handshake, resume, region change and close codes;
- IP discovery, encrypted playback and receive end to end.
- DAVE is tested with a scripted module and real
@snazzah/daveykey packages. - Encryption test vectors and sequence/timestamp wraparound are tested.
- Opus round trip, Ogg demux, FFmpeg and player timing are tested.
- 100 join/leave cycles leave no sockets, timers or listeners behind.
- The fake server is scripted, not a capture of Discord; playing in a real guild is the release smoke test (
bun run smoke:voice, or the manual “Voice smoke test” workflow). - CI also runs the tests on ARM64 and on the minimum Bun (1.4.0).
Earlier releases: see the Git history.