SDK guide
Direct messages
Start 1:1 and group DMs with the SDK, compute dm: IDs and hosting servers, keep the DM index current, handle message requests, settings and blocks, and act on a DM's security.
Specification: 12 Direct messages and group DMs, 02 Discovery, server metadata and server keys, 06 Federation, 11 Messages, attachments, read state and presence, 13 MLS profile
A DM is a context like a channel: it lives on one hosting server, and you read and post in it with the normal messaging APIs and its dm: or gdm: reference. What is specific to DMs is where that context lives, how it gets into each participant's DM list, and which security it has. The protocol side is explained on Direct messages and group DMs; this page shows how the SDK covers it.
The SDK splits DMs into two parts:
- DmsApi, on every ServerClient as
dms, wraps the endpoints. Its own methods (create,get,update,rename,addParticipants,removeParticipant,leave) go to the hosting server. Its membersindex,requests,settingsandblocksgo to your home server. - Pure functions evaluate the client-side rules of document 12: the hosting rule, the
dm:reference, the computed security, which warnings to show, and what to do after an error. They do no I/O, so you feed them the metadata and IdentityStates you fetched and verified.
Two servers
Every DM call goes to one of two servers, and calling the wrong one fails:
| What | Where | SDK |
|---|---|---|
| The DM itself: create, read, rename, add, remove, leave | The hosting server, with a home or remote session (12 §7.2) | (await sv.server(host)).dms |
| Messages, timeline, read state, typing in the DM | The hosting server (12 §3) | (await sv.server(host)).messages and the other messaging APIs |
| The DM index | Your home server, with a home session or a bot token (12 §9.3) | (await sv.home()).dms.index |
| Message requests | Your home server, with a home session (12 §10.3) | (await sv.home()).dms.requests |
| DmSettings and blocks | Your home server (12 §9.4, §9.5) | (await sv.home()).dms.settings, .dms.blocks |
SloppyVoiceClient.server gives you the home client when the host is your home server, and otherwise a client that opens a remote session the first time a request needs one (Federation). The home-only members exist on every server client; a remote server answers them with auth.home_session_required (05 §3.2), so call them on sv.home().
DM IDs
A 1:1 DM's reference is computed from the two canonical addresses: "dm:" and the unpadded base64url of the first 16 bytes of SHA-256(UTF8("sv1 dm") || 0x00 || UTF8(P1) || 0x0A || UTF8(P2)), where P1 sorts before P2 byte-wise (12 §5.2). Anyone can compute it, and the same pair has the same reference on every server. dmContextId does it, with the addresses in either order. It lives in the @sloppyvoice/sdk/crypto entry point.
import { dmContextId, isStrictDmRef, verifyDmContextId } from '@sloppyvoice/sdk/crypto'
// Test vector V-1 (12 §5.5), in either order.
const ctx = await dmContextId('dan@d.com', 'alice@a.com')
console.log(ctx) // dm:KBXfagPoLlQyKu3QOiLfgw
// Check a reference from an index entry or a request against the pair it claims.
console.log(await verifyDmContextId(ctx, 'alice@a.com', 'dan@d.com')) // true
// V-7: the last character has non-zero unused bits, so the reference is malformed.
console.log(isStrictDmRef('dm:KBXfagPoLlQyKu3QOiLfgx')) // falseThe addresses must be canonical before you hash them. Hashing Alice@A.com instead of alice@a.com gives a different reference and is non-conforming (test vector V-6, 12 §5.5). dmContextId doesn't canonicalize for you, because full canonicalization needs discovery (an alias domain looks canonical). It only runs the syntactic checks, so it rejects obviously non-canonical input such as Alice@A.com with sdk.invalid_argument (data.reason non_canonical), and equal addresses with data.reason self. Run canonicalize from @sloppyvoice/sdk/address on every address first (Addresses).
Related helpers:
- compareAddresses and sortAddresses order addresses as unsigned UTF-8 bytes, a proper prefix first (12 §2.2). This isn't JavaScript's default string order, which compares UTF-16 code units.
- parseDmRef returns the 16 ID bytes of a
dm:reference and throws for anything that doesn't matchdm-ref(12 §5.1). - isGroupDmRef checks a
gdm:reference. A group reference is a UUIDv7 that the hosting server assigns at creation (12 §5.4), so you can't compute it.
Which server hosts the DM
The hosting rule picks the server from the participants' canonical addresses and the secure flag of each participant's home (12 §4). hostFor1to1 evaluates it for a 1:1 DM, hostForGroup for a new group DM. Both take an IsSecureServer function, (domain) => boolean, which you build from ServerMetadata with two rules from 12 §4.1:
- Use metadata no older than 1 h (DM_LIMITS
.hostingMetadataMaxAgeMs). - Once you have seen
secure: truefor a domain, never usefalsefor it again, because the flag only ever goes fromfalsetotrue.
Creating a DM is rare, so the simplest way to meet the age bound is to recheck /meta for every input domain before you evaluate the rule. With a DiscoveryResolver shared with your client (the discovery option), recheck: 'metadata' does that (02 §13.4). If the refetch fails with a temporary error, the resolver falls back to its cached copy and sets stale: true (02 §13.2), which may be older than 1 h, so check stale:
import { DiscoveryResolver, type IsSecureServer } from '@sloppyvoice/sdk'
// Domains this client has ever seen with secure: true. Keep this in durable storage:
// a client that has seen true for a domain never uses false for it (12 §4.1 item 2).
const seenSecure = new Set<string>()
/** secure(d) for every participant's home, from fresh ServerMetadata (12 §4.1). */
export async function secureFlags(resolver: DiscoveryResolver, addresses: string[]): Promise<IsSecureServer> {
const domains = new Set(addresses.map((a) => a.slice(a.lastIndexOf('@') + 1)))
for (const domain of domains) {
const { metadata, stale } = await resolver.resolve(domain, { recheck: 'metadata' })
if (metadata.secure) seenSecure.add(domain)
// A failed refetch returns the old copy with stale: true. Its false may be out of date.
else if (stale && !seenSecure.has(domain)) throw new Error(`No fresh ServerMetadata for ${domain} (12 §4.1)`)
}
return (domain) => seenSecure.has(domain)
}With the flags in hand, the rule is a pure function. These are test vectors H-1, H-3 and H-7 of 12 §4.6:
import { hostFor1to1 } from '@sloppyvoice/sdk'
const none = () => false
const onlyA = (d: string) => d === 'a.com'
console.log(hostFor1to1('alice@a.com', 'dan@d.com', none)) // a.com: alice@a.com sorts first
console.log(hostFor1to1('dan@d.com', 'alice@a.com', onlyA)) // d.com: exactly one home is secure, so the other one
console.log(hostFor1to1('bob@b.com', 'bob@b.co', none)) // b.co: a proper prefix sorts firsthostForGroup also needs each participant's sec from a verified IdentityState (Secure accounts), passed as a DmPartySecurity { addr, sec }. An upgrade_required account counts as insecure (12 §2.2). When every home is a secure server and the group would be insecure, it throws dm.encryption_pending with data.waitingFor listing the insecure people (12 §4.3).
Existing DMs: use the index
The rule picks a host only when a DM is created. After that the DM stays where it is, even when a server upgrade makes the rule pick another server (12 §4.5). To send to an existing DM, use the host in your DM index entry, never a freshly computed rule host. currentDmHost returns it from your index entries, or null when you have no entry for that context that isn't closed; only then compute the rule.
import { currentDmHost, type DmCtx, type DmIndexEntry } from '@sloppyvoice/sdk'
declare const entries: DmIndexEntry[] // from home.dms.index.list(), kept current from events
declare const ctx: DmCtx
const host = currentDmHost(entries, ctx)
if (host === null) {
// No open DM for this context: start one (or its successor) at the rule host.
}dm.wrong_host
If the server you sent POST /v1/dms to computes a different host, it answers 409 dm.wrong_host with data.host (12 §4.4). Refetch every input metadata document, recompute, and pass both results to nextWrongHostStep. It returns one of three steps:
retry_at: your result now matchesdata.host; retry there.retry_original: you still disagree; retry the original server once, afterdelayMs(5,000 ms).give_up: you already did; show "Couldn't start this conversation right now" (core.unavailable) and keep the draft in the outbox.
Starting a 1:1 DM
The client procedure of 12 §7.1 has seven steps. planDirectDm computes what steps 2, 3 and 6 send: the rule host, the dm: reference, the computed security, the body of the registration at your home, and the body of POST /v1/dms. You do the I/O around it.
import {
isSloppyVoiceError,
planDirectDm,
shouldDeleteRegistrationAfter,
type Dm,
type DmPartySecurity,
type IsSecureServer,
type SloppyVoiceClient,
} from '@sloppyvoice/sdk'
/**
* Start an insecure 1:1 DM (12 §7.1). `self` and `peer` carry the `sec` of IdentityStates
* you verified; `isSecureServer` holds the homes' secure flags (12 §4.1).
*/
export async function startDirectDm(sv: SloppyVoiceClient, self: DmPartySecurity, peer: DmPartySecurity, isSecureServer: IsSecureServer, text: string) {
const plan = await planDirectDm({ self, peer, isSecureServer })
if (plan.security === 'secure') throw new Error('A secure DM needs an MLS bootstrap in plan.create (12 §7.1 step 5)')
// Step 3: register at your own home first, so the DM shows up on your other devices at once.
const home = await sv.home()
const { entry } = await home.dms.index.register(plan.register)
// Steps 4 and 6: the hosting server, with a remote session when it isn't your home.
const hosting = await sv.server(plan.host)
let dm: Dm
try {
;({ dm } = await hosting.dms.create(plan.create))
} catch (e) {
// A non-retryable failure of POST /v1/dms deletes the registration; dm.encryption_pending keeps it (12 §7.1).
if (isSloppyVoiceError(e) && shouldDeleteRegistrationAfter(e)) await home.dms.index.delete(entry.id)
throw e
}
// Step 7: the first message. The hosting server sends the dm.request when it sequences it.
// The DM exists now, so a failure here leaves the registration alone; the outbox retries the message.
await hosting.messages.send(dm.ctx, text)
return dm
}Notes on the steps:
- Security.
plan.securitycomes from computeDmSecurity: a 1:1 DM issecureonly when both people are (12 §11.1). The plan puts it inexpectSecurity. If the hosting server computes something else it answers 409 dm.security_mismatch, whosedatalists each participant'ssec, so you can refetch exactly the IdentityStates you disagree about. - Secure 1:1 DMs. Before step 6 you claim KeyPackages, build the MLS group with your MlsProvider, and set
plan.create.bootstrapandplan.create.commitfrom groupBootstrapFor and commitSubmissionFor (12 §7.1 step 5; MLS and sealed messages). An unenrolled device can't create a secure DM: the server answers 403 security.device_not_enrolled. - 201 or 200. DmsApi.create returns
{ dm, created, status }.createdis false (200) when the 1:1 DM already existed, for example because the peer started it at the same moment, or when a closed 1:1 DM was reopened. A bootstrap you sent is then ignored, and you join the existing group instead (12 §5.3, §13.4). - Retries. A 1:1 creation is idempotent on
ctx, but the SDK doesn't resend it on its own: a resend after a lost 201 would get 200 and ignore its bootstrap, so your outbox decides.dm.*problems are never retried blindly, because 12 defines its own recovery for them. - Validation.
createchecks the shape of the body with validateCreateDmRequest before sending and throwssdk.invalid_argumentfor a malformed one, such as a missingpeer, fewer than 2 other participants or abootstrapon a group (12 §7.2). It doesn't know your own address or the server'smaxGroupDmParticipants, so a body naming you, or too many people, still reaches the server;planDirectDmandplanGroupDmpass your address and catch the first. - Community hints. Pass
communityHintstoplanDirectDm: up to 10 community domains on your community list where you saw the peer. They only order the recipient home's auto-accept checks (12 §10.2).
The other errors to expect from create are listed in its reference entry. The most common are dm.recipient_not_found (no such account), federation.blocked and dm.encryption_pending.
Starting a group DM
A group's reference comes from the hosting server, so a group registers in your index after creation, not before (12 §7.1 step 6). planGroupDm computes the host with hostForGroup, the security, and the body.
import { planGroupDm, type DmPartySecurity, type IsSecureServer, type SloppyVoiceClient } from '@sloppyvoice/sdk'
/**
* Start a group DM with at least two other people (12 §7.1, §7.2). Create `idempotencyKey` once
* per creation (for example with uuidv7()), keep it in your outbox and pass the same value on every
* retry, so that a retry returns the group the first attempt created instead of a second group.
*/
export async function startGroupDm(
sv: SloppyVoiceClient,
self: DmPartySecurity,
others: DmPartySecurity[],
isSecureServer: IsSecureServer,
name: string,
idempotencyKey: string,
) {
const plan = planGroupDm({ self, participants: others, isSecureServer, name })
const hosting = await sv.server(plan.host)
const { dm } = await hosting.dms.create(plan.create, { idempotencyKey })
// Now that the server assigned the gdm: reference, register it at your home.
const home = await sv.home()
await home.dms.index.register({ host: plan.host, ctx: dm.ctx, kind: 'group' })
return dm
}Without idempotencyKey, create sends a fresh Idempotency-Key for a group, which protects only the SDK's own resend of a request whose outcome it doesn't know.
For a secure group, your device holds the bootstrap grant for 60 s after the 201 (DM_LIMITS.creatorBootstrapGrantMs). Build the group with group_id sv1:<host>:<ctx>:1, every participant listed, and upload the bootstrap with the first commit in one request (12 §7.1 step 6, 12 §11.4). Until then a SealedMessage fails with mls.group_not_found.
"Add people" in a 1:1 DM starts a new group DM with both participants plus the new people; the 1:1 DM is unchanged and its history isn't copied (12 §7.1).
Managing a group
| Method | Endpoint | Notes |
|---|---|---|
rename(ctx, name) |
PATCH /v1/dms/{ctx} | Any active participant may set or clear (null) the name (12 §7.5). The SDK checks the name with groupNameProblem first: 1 to 100 characters, at most 400 bytes, NFC, no control characters, no leading or trailing white space (12 §6.1). |
addParticipants(ctx, { participants }) |
POST /v1/dms/{ctx}/participants | 1 to 10 addresses. Returns { dm, reserved, status }. In an insecure group the new people are pending at once (200). In a secure group reserved is true (202): you have 60 s to submit one commit that adds them and lists them in sv_participants, or the reservation lapses and a late commit fails with dm.reservation_expired (12 §12.2). |
removeParticipant(ctx, addr) |
DELETE /v1/dms/{ctx}/participants/{addr} | While the group has an owner, only the owner may remove others (403 dm.not_owner) (12 §12.3). |
leave(ctx, self) |
The same, with your own address | A 1:1 DM can't be left (409 dm.not_group): hide it or block the peer instead. |
get(ctx) |
GET /v1/dms/{ctx} | The Dm, filtered for you. In a 1:1 DM the peer's pending or declined state is reported as active (12 §6.5). |
Adding an insecure person to a secure group fails with 409 security.would_downgrade, data.insecure listing them; offer to start a new group without encryption instead (12 §11.3).
The DM index
Your home server keeps one DmIndexEntry per DM you take part in, on any hosting server (12 §9.1). It is your client's source of truth for which DMs exist and where they live. DmIndexApi, at home.dms.index, wraps it:
| Method | Endpoint | Purpose |
|---|---|---|
list(params) |
GET /v1/me/dms | A pager over entries, newest activity first. Default states active,requested; state, kind, includeHidden and limit (1 to 100) filter. |
get(id) |
GET /v1/me/dms/{id} | One entry, with pendingEvents. |
register({ host, ctx, kind }) |
POST /v1/me/dms | Register an outgoing DM. Idempotent; created tells 201 from 200. If a request for that DM is waiting, this accepts it. |
hide(id, hidden?) |
PATCH /v1/me/dms/{id} | Hide or unhide. A hidden entry reappears when new activity arrives. |
delete(id) |
DELETE /v1/me/dms/{id} | Only for a declined, left or closed entry, or an outgoing entry whose lastSeq is 0. Others fail with 409 dm.entry_active. |
Load the list once, then keep it current from dm.index_updated and dm.index_removed on the me stream of your home server's event socket, which every socket follows (12 §16.2):
import { normalizeIndexEntryState, type DmIndexEntry, type SloppyVoiceClient } from '@sloppyvoice/sdk'
export async function followDmList(sv: SloppyVoiceClient, onChange: (entries: DmIndexEntry[]) => void) {
const home = await sv.home()
const byId = new Map<string, DmIndexEntry>()
const events = home.events()
events.on('dm.index_updated', (e) => {
byId.set(e.d.entry.id, e.d.entry)
onChange([...byId.values()])
})
events.on('dm.index_removed', (e) => {
byId.delete(e.d.id)
onChange([...byId.values()])
})
await events.connect()
for await (const entry of home.dms.index.list({ state: ['active', 'requested'] })) byId.set(entry.id, entry)
onChange([...byId.values()])
}
/** Accepted conversations. Show `requested` entries in a separate tab, never among these (12 §10.4). */
export function conversations(entries: DmIndexEntry[]): DmIndexEntry[] {
return entries.filter((e) => normalizeIndexEntryState(e.state) === 'active')
}Treat an unknown entry state as left; normalizeIndexEntryState does that (12 §9.1). The SDK has more normalizers for DM values whose unknown values the spec gives a meaning, for example normalizeDmSecurity, which treats an unknown security as secure so that plaintext is refused (12 §6.1).
An entry exists only because you registered it or a request passed your home's filter. A hosting server can't put a conversation in your list (12 §9.3).
Message requests
When an invitation matches none of the auto-accept rules (for example, you have no accepted DM with the inviter and share no community of at most 200 members with them), your home server files a DmRequest instead of accepting it (12 §10.2). DmRequestsApi, at home.dms.requests, wraps the endpoints of 12 §10.3:
| Method | Effect |
|---|---|
list(params) |
A pager over requests, newest first, default state pending. List items carry preview instead of events and welcome. |
get(id) |
The full DmRequest: events, Welcome, IdentityStates and the relayed serverKeys. |
accept(id) |
The request becomes accepted and the entry active. Returns the DmIndexEntry. |
decline(id) |
Declines quietly; the sender isn't told. In a 1:1 DM no new request comes for 30 days; in a group DM the decline removes you (12 §8.5). |
block(id) |
Declines and blocks the inviter. |
Acting on a request that isn't pending fails with 409 dm.request_not_pending. New requests arrive as dm.request_received on the me stream, and every change emits dm.request_resolved.
Before Accept
Until the user accepts, your client MUST NOT contact the hosting server, the inviter's home server or any other server the sender chose, so a stranger can't learn the user's IP address or that they read the message (12 §10.4). Many of those contacts would also accept the request implicitly (12 §8.7). Render the request card from requests.get(id) alone: no avatars, attachments, link previews, IdentityState or profile fetches.
assertMayContactBeforeAccept is a guard you put in front of any I/O a request card could trigger. It throws sdk.invalid_argument when the target isn't your home server and the state isn't one in which the user took part:
import { assertMayContactBeforeAccept, type DmRequest, type SloppyVoiceClient } from '@sloppyvoice/sdk'
/** Accept a request, then open the DM at its hosting server (12 §10.5). */
export async function acceptAndOpen(sv: SloppyVoiceClient, request: DmRequest) {
const home = await sv.home()
// Throws: the request is still pending and the hosting server isn't the home server.
// assertMayContactBeforeAccept({ state: request.state, target: request.host, home: home.domain, action: 'session' })
const entry = await home.dms.requests.accept(request.id)
assertMayContactBeforeAccept({ state: entry.state, target: entry.host, home: home.domain, action: 'session' })
// Only now: a remote session at the hosting server, and the timeline from the highest seq you hold.
const hosting = await sv.server(entry.host)
const events = hosting.events({ subscribe: [entry.ctx] })
await events.connect()
return { entry, hosting, events }
}After Accept, refresh the participants' IdentityStates from their home servers, fetch the Welcome and any events the request didn't carry, and in a secure DM join the group (12 §10.5).
Settings and blocks
DmSettingsApi, at home.dms.settings, reads and replaces the account's DmSettings (12 §9.4):
autoAccept:contacts_and_communities(the default),contacts_onlyoreveryone. It decides which auto-accept rules of 12 §10.2 apply. Treat an unknown value as the default (normalizeAutoAcceptSetting).requestNotifications: whether a new message request creates a notification.
DmBlocksApi, at home.dms.blocks, manages blocks, at most 10,000 per account (12 §9.5). Blocking an address drops its new requests silently, moves every 1:1 entry with it and any pending request from it to blocked, and your home tells each hosting server; group DMs you share with that person don't change at the protocol level.
import type { SloppyVoiceClient } from '@sloppyvoice/sdk'
export async function tightenDms(sv: SloppyVoiceClient, spammer: string) {
const home = await sv.home()
// "Who can message you directly: only people you know."
const settings = await home.dms.settings.get()
await home.dms.settings.put({ ...settings, autoAccept: 'contacts_only' })
// spammer must be a canonical address. Blocking is idempotent.
await home.dms.blocks.block(spammer)
for await (const block of home.dms.blocks.list()) console.log(block.addr, block.createdAt)
}blocks.unblock(addr) sets the blocked 1:1 entries back to declined without a quiet period. Every change emits dm.settings_updated or dm.block_updated on the me stream, so your other devices follow.
Security
A DM's security is computed from its participants, never chosen (12 §11.1). A 1:1 DM is secure when both people are, and follows them both ways. A group DM is secure when every current participant is, and once secure it never goes back. computeDmSecurity evaluates this; for a group, pass wasSecure: true when you hold a secure-state pin for it.
Your client computes the security itself, from IdentityStates it verified, and acts on its own result, because a hosting server could otherwise present a secure DM as insecure and collect plaintext (12 §11.1). plaintextDecision combines those rules before you post plaintext into a DM:
import {
normalizeDmKind,
normalizeDmSecurity,
plaintextDecision,
securityDisagrees,
type Dm,
type SloppyVoiceClient,
} from '@sloppyvoice/sdk'
/**
* Post plaintext into an insecure DM. `computed` is the security you computed from verified
* IdentityStates; `securePinned` says whether you hold a secure-state pin for this group.
*/
export async function sendPlaintext(sv: SloppyVoiceClient, dm: Dm, computed: 'secure' | 'insecure', securePinned: boolean, text: string) {
// W9: a group you pinned as secure, presented as insecure. A hard error with "Leave" offered, not a retry (12 §11.1).
if (securePinned && normalizeDmKind(dm.kind) === 'group' && normalizeDmSecurity(dm.security) === 'insecure') {
throw new Error('W9: this group was secure and is now presented as insecure')
}
if (securityDisagrees(computed, dm.security)) {
// Refetch the IdentityStates concerned (at most once per 30 s per DM) and keep the message queued.
return { queued: true as const }
}
const decision = plaintextDecision({ kind: dm.kind, computedSecurity: computed, reportedSecurity: dm.security, state: dm.state, securePinned })
if (!decision.allowed) throw new Error(`Not sending plaintext: ${decision.reason}`)
const hosting = await sv.server(dm.host)
return { queued: false as const, ack: await hosting.messages.send(dm.ctx, text) }
}The refusal reasons are:
| Reason | Meaning |
|---|---|
computed_secure |
You compute the DM as secure. Send a SealedMessage instead (MLS and sealed messages). |
secure_pin |
A group you hold a secure-state pin for, with computedSecurity insecure. If you computed it with wasSecure from the same pin, the result is secure and the reason is computed_secure instead, so detect W9 (a hard error with "Leave" offered) yourself, as the sample does, or with dmWarnings. |
unverified_downgrade |
A 1:1 DM you last knew as secure, until you have verified the peer's downgrade yourself. Pass lastKnownSecure and peerDowngradeVerified. |
reported_secure |
The hosting server reports the DM as secure, or with an unknown security value. |
state |
The DM isn't active, so it accepts no content (12 §6.2). |
Secure contexts only
For a group you have ever seen as secure, record a secure-state pin for (host, ctx) and use it as wasSecure and securePinned, never the value the hosting server reports. Take a secure group's participant set from its sv_participants extension, not from the hosting server's list (12 §11.1, 12 §20).
Related functions:
- dmWarnings returns the persistent warnings that depend on a DM's security: W3 (insecure group, naming the insecure participants), W7 (insecure 1:1 DM with an insecure peer) and W9 (12 §11.6). It returns neither W3 nor W7 to an insecure viewer, nor for an
upgradingDM, which shows the status line "Setting up encryption…" instead (12 §11.7). - dmCallPolicy says whether a DM can have calls (
calls), whether it takes new joins (newJoins) and whether its video may move to the SFU (sfu) (12 §14).sfuis true for group DMs only, because a 1:1 DM call never uses the SFU (15 §7.2 item 1). Every DM call's media goes through the hosting server's relay or SFU, so a call never reveals one participant's IP address to another (12 §14). - secureHostOutcome says what happens to a DM on a hosting server that is or has become a secure server: unchanged,
encryption_pending, or closed, with the rule host for a 1:1 successor (12 §13.1). - needsSuccessor tells you that a DM closed with reason
host_secure, so you create a successor without asking the user before you send. PassreplacestoplanDirectDmorplanGroupDm; a 1:1 successor keeps the samedm:reference on the new host, and for a group you first use the closed entry'ssuccessorif another participant already made one (12 §13.3).
dm.upgrade_in_progress is retryable with userAction none: it means the DM is becoming secure, not that sending failed. Keep the message in the outbox; it goes out as a SealedMessage, with the same mid, after the switch. An enrolled device that gets this error, or sees dm.security_eligible, takes part in the upgrade without asking the user: it asks for the group, bootstraps it if it receives the grant, and otherwise waits for its Welcome (12 §11.4).
Errors from the rules
The pure functions throw a SloppyVoiceError either way. Malformed input, such as a non-canonical address or a group with fewer than two other people, is sdk.invalid_argument. When the rule itself fails, the SDK builds the dm.* error the hosting server would send, with status 0 and the retryable and userAction of the registry in 12 §17, so you handle it exactly like the server's: hostFor1to1 with the same address twice throws dm.invalid_participants, and hostForGroup throws dm.encryption_pending. localDmError builds one, and DM_ERRORS is the registry.