StudioXid.OmniAdapter
0.1.0
Prefix Reserved
dotnet add package StudioXid.OmniAdapter --version 0.1.0
NuGet\Install-Package StudioXid.OmniAdapter -Version 0.1.0
<PackageReference Include="StudioXid.OmniAdapter" Version="0.1.0" />
<PackageVersion Include="StudioXid.OmniAdapter" Version="0.1.0" />
<PackageReference Include="StudioXid.OmniAdapter" />
paket add StudioXid.OmniAdapter --version 0.1.0
#r "nuget: StudioXid.OmniAdapter, 0.1.0"
#:package StudioXid.OmniAdapter@0.1.0
#addin nuget:?package=StudioXid.OmniAdapter&version=0.1.0
#tool nuget:?package=StudioXid.OmniAdapter&version=0.1.0
StudioXid.OmniAdapter (.NET)
Join a Connect Omni stage from .NET — services, desktop apps, industrial
HMIs, Unity — and exchange messages with prototypes in real time. Mirrors the
TypeScript/Python adapters' wire contract and concepts on a Task-based surface.
After dotnet restore, the package's files sit in the NuGet global packages folder:
~/.nuget/packages/studioxid.omniadapter/<version>/ (Windows:
%USERPROFILE%\.nuget\packages\studioxid.omniadapter\<version>\). Paths below start there.
First time? The step-by-step guide ships in the package: docs/getting-started.md — the
adapter key, the install and the adapter name, from nothing to your first message.
For AI assistants — the full usage guide ships in the package root: llms.txt. For Claude
Code, copy the skill folder skills/using-omni-adapter/ into your project's .claude/skills/.
Must-know rules for C#:
- Credential: only a
cst_…adapter token (Share → Adapter keys → Create key, then Copy) or a bareck_…key withUrl+StageId; read it from an environment variable, never hard-code it. Whitespace around it →ConfigError. - Close on exit:
await client.CloseAsync()on Ctrl+C, SIGTERM and app quit — the client ends at the call, and the task completes once the server confirms the leave (≤1 s);Dispose()sends the leave without waiting. An unclean exit holds the seat a few seconds; the same key coming back keeps its name (on a server with same-key name sharing — older servers renamed a restart that came within a few seconds of an unclean exit). - Lifecycle events are .NET events:
StateChanged,Error,MemberJoined,MemberLeft,Ended,HistoryReplaced,QueueOverflow.client.On("error", …)subscribes to a channel namederrorand never sees a failure. Server events run one at a time on the socket receive thread — never block there (.Result,.Wait(),Dispatcher.Invoke→ a falseAckTimeout); hop to the UI thread withBeginInvoke/Post. Latest()is not a delivery check: it folds your own sends in. To confirm a publish useack: true(a server ack, not a delivery receipt) or watch the channel from a second connection.ExclusiveNamestandby: only instances on the same adapter key; while standby new sends are dropped (or, acked, fail withStandby), and becoming standby drops whatever was queued — nothing stale goes out on promotion. Readclient.Standby.- 60 messages a second per connection: the adapter paces sends to the server's limit; a faster source fills the
queue and loses its oldest values —
Throttle()it.CloseAsync()/Dispose()drop queued fire-and-forget sends. asynclambdas areasync void: an exception escapingclient.On("x", async msg => …)or anasyncevent handler crashes the process — wrap the body intry/catch.
using StudioXid.OmniAdapter;
// One credential is all you need (stage → Share → Adapter keys → Create key):
var client = await Connect.ToStageAsync(new ConnectOptions
{
SecretKey = Environment.GetEnvironmentVariable("CONNECT_TOKEN"), // "cst_…"
DisplayName = "Line Controller",
Receives = new[] { "actuator.cmd" }, // declared → Backstage port chips
Sends = new[] { "sensor.temperature" },
});
client.On("actuator.cmd", msg => Console.WriteLine($"prototype asked for {msg.Value}"));
await client.SendAsync("sensor.temperature", 23.5);
await client.SendAsync("door.open", true, ack: true); // wait for the server ack
await client.CloseAsync(); // when you are done — leaves the stage
Install
dotnet add package StudioXid.OmniAdapter
Targets netstandard2.0 (Unity / .NET Framework) and net8.0. The only
runtime dependency is SocketIOClient (plus System.Text.Json 8.0.6 — on net8.0 it raises the 8.0.4 that
SocketIOClient brings, which is affected by CVE-2024-43485).
License: Apache 2.0 (see LICENSE in the package); connecting to a
stage requires a Connect Omni subscription (an adapter token).
Working from a checkout of the adapter repository instead (contributors with access to it)?
Keep the checkout next to your project, not inside its folder — the
.NET SDK's default **/*.cs glob would compile the checkout's tests and Unity scripts into
your app — and reference the project from your app's directory:
dotnet add reference ../omni-adapter/csharp/src/StudioXid.OmniAdapter.
Connecting
Two forms, same precedence as the other adapters. Both carry an adapter key
(ck_…) issued from Stage → Share → Adapter keys → Create key, then Copy (the Copy
button appears only right after Create key — the plaintext is shown once). Anything else (a
share token, for instance) is rejected with ConfigError before any network call, and so is
a credential with whitespace around it (the newline a token file ends with — trim it).
await Connect.ToStageAsync("cst_…"); // ① self-describing token (recommended)
await Connect.ToStageAsync(new ConnectOptions // ② raw key + explicit coordinates
{
Url = "http://192.168.0.10:9981", StageId = "01HXYZ", SecretKey = "ck_…",
});
Without StrictRouting, Receives may use wildcards (robot.*). StrictRouting = true
requires exact Receives names (no wildcards); the
server then delivers only those channels plus messages targeted at you.
Your name on the stage is DisplayName (1–64 chars, default Omni adapter). Instances on the
same adapter key share the name — a restart is never renamed (this needs a server with same-key name
sharing, the Connect Omni server change shipping with this release; older servers renamed a restart that came
within a few seconds of an unclean exit). You join as name (2) only when the name is held by another
adapter key: another key's adapter is connected under it, or (with ProvidesView = "stream") the
stage's Adapter Stream layer of that name is bound to another key that is still valid. Another program
on a different key uses this name, or you rotated keys without revoking the old one — rename one, or
revoke the old key.
Read client.Me?.DisplayName to see what you got. A person never takes a program's name.
A screen — set ProvidesView = "stream" if this program broadcasts a screen (ScreenBroadcast,
below). The server then creates the Adapter Stream layer for your name on the stage, or binds the
one a designer already placed, as soon as you connect — nothing else to call. ProvidesView = "web"
is for a page shown in a Web View layer; leave it unset otherwise.
Close on exit. A program that exits without leaving holds its seat for a few seconds (the same
key coming back keeps its name). CloseAsync() sends the leave before it
disconnects; Dispose() ends the client the same way but sends the leave in the background
without waiting, so prefer await client.CloseAsync() on the way out — for Ctrl+C and for SIGTERM
(docker stop, systemd):
using System.Runtime.InteropServices; // PosixSignalRegistration (.NET 6+)
var stop = new TaskCompletionSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.TrySetResult(); }; // Ctrl+C
using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM,
ctx => { ctx.Cancel = true; stop.TrySetResult(); }); // SIGTERM
client.Ended += _ => stop.TrySetResult(); // the session ended for good (e.g. the key was revoked)
await stop.Task;
await client.CloseAsync();
API sketch
await client.SendAsync("door.open", true); // fire-and-forget
await client.SendAsync("door.open", true, ack: true); // wait for the server ack
await client.SendToAsync(participantId, "cmd.stop", 1); // unicast
await client.SendJsonAsync("robot.status", new { pose = new[] { 1, 2 } });
client.On("button.tap", msg => { }); // exact channel
client.On("robot.*", msg => { }); // wildcard — 1+ dot segments
client.OnJson<RobotStatus>("robot.status", (status, msg) => { });
using var sub = client.On("chat.message", msg => { }); // Dispose() unsubscribes
client.Latest("temp.reading"); // last value (history-seeded; 1000 most recent channels)
client.LatestJson<RobotStatus>("robot.status");
client.History(); // replay ring (≤1000, not storage)
client.HistoryJson<ChatMessage>("chat.message");
await client.MembersAsync(); // each Member also carries Receives · Sends · ClientType · StrictRouting · ExclusiveName · OsHostname (null on older servers); member.DeclaresChannel("robot.status")
await client.ListenersAsync("robot.status"); // who will receive it: .Declared / .Broadcast (self excluded); records no-listener when nobody declared it
var push = client.Throttle("nav.position", hz: 10); // coalesced sender (trailing flush)
push(37.5665); // a bad value throws ValidationError right here; delivery failures go to Error
await client.EnsureStreamLayerAsync(); // optional — the server already created/bound it on connect (ProvidesView = "stream"); .Renamed
await client.FetchIceServersAsync(); // WebRTC ICE config (/api/stages/:id/ice: STUN+TURN,
// /api/about STUN fallback) — successes cached; on failure it returns
// a still-cached list, else the public STUN list, else [] (fail-open),
// and the next call asks again.
// ScreenBroadcast fetches it for you (SessionFactoryWithIce).
// Lifecycle = .NET events (On("error") would subscribe to a channel named "error"):
client.StateChanged += state => { }; // idle→connecting→connected↔reconnecting→ended
client.Error += err => { }; // server-pushed / transport errors — subscribe in any headless program
client.MemberJoined += member => { };
client.MemberLeft += participantId => { };
client.HistoryReplaced += snapshot => { }; // the (re)join snapshot re-seeded Latest()/History()
client.Ended += reason => { }; // final — build a new client to connect again
client.QueueOverflow += input => { };
Console.WriteLine($"{client.State} queued={client.QueuedCount} standby={client.Standby}"); // readable any time
foreach (var entry in client.Diagnostics()) Console.WriteLine(entry); // last 100 lifecycle points, no credential
await client.CloseAsync(); // or Dispose() — same ending: queued acks reject with SessionEnded, Ended fires once
// (CloseAsync sends the leave first; Dispose sends it without waiting)
Values are primitives only (string/number/bool/null) — use
SendJsonAsync for objects (JSON-string convention that prototypes parse). It serializes with
System.Text.Json (POCOs, records, dictionaries, arrays, lists); a value it cannot encode — a
reference cycle, NaN/Infinity, a Type or a delegate — throws ValidationError
synchronously from the call.
The server never echoes your own publishes; Latest() still folds them locally, so it is no
proof that a send went out. Prototypes and the Console send every value as a string ("42", not 42) — or null when
the message carries none — so convert before comparing; values from other programs keep their type.
Acks. SendAsync(…, ack: true) waits for the server's ack and fails with AckTimeout after
ConnectOptions.AckTimeout (15 s by default). It must be above zero and at most 2^31−1 ms (about
24.8 days) — anything else, Timeout.InfiniteTimeSpan and TimeSpan.MaxValue included, fails with
ConfigError before the client contacts the server — and it is read once when the client connects.
A timeout does not prove the server didn't get the
message, and a server ack is not a delivery receipt — peers never ack. An acked send that is still
waiting when you close the client or the connection drops fails with AckTimeout at once (it is
not re-sent; one still in the offline queue stays queued, or fails with SessionEnded when the
client ends). A plain send is at-most-once, direct or queued: it asks for no ack, so a server
rejection of it (the rate limit included) is never seen, and one lost to a drop right after it
went out is not retried — only acked sends report the server's answer. A queued acked send that already went out once before a drop and is later failed with
QueueOverflow, Standby or SessionEnded may have reached the server too — on a queued
acked send, none of these codes proves non-delivery.
Offline sends queue (default 1000, oldest dropped with a QueueOverflow event)
and flush in order on reconnect, as fast as the rate limit below allows — plain items without
waiting for acks, an acked item only after its server answer; TooManyRequests
(only acked sends see it) pauses sending with exponential backoff (1s → ×2 → 60s) and requeues silently — no send-dropped entry
in Diagnostics(), so "connected, QueuedCount > 0, not standby, no send-dropped" is a
backoff. Every reconnect revalidates the adapter key
for a fresh JWT; a revoked key surfaces as AuthRevoked. When the server drops the
socket itself (a revoked or expired key, with no stage:ended), the client treats it as a
session end: it rejoins through that revalidation (a revoked key ends with
rejoin-abandoned: AuthRevoked), or ends with server-disconnect when AutoRejoin is off.
CloseAsync() (and Dispose()) drop queued fire-and-forget sends (queued acked sends fail with SessionEnded): to be
sure the last values went out, await an acked send or wait until QueuedCount is 0 first.
Rate limit — 60 messages a second. The server accepts at most 60 messages a second per
connection and silently drops fire-and-forget messages above that, so the adapter paces every
send — direct or queued — with a token bucket (60 per second, bursts of up to 30); a send with
no token free waits in the queue. Keep a source above 60/s up and the queue fills: the oldest
items are dropped (a QueueOverflow event for each, one queue-overflow line in the diagnostics
ring per episode) and the newest value still goes out. After a disconnect, a sender at 60/s or
more stays behind by up to QueueLimit ÷ 60 seconds (the queue drains at 60 a
second, so a full default queue of 1000 takes about 17 s) —
throttle it or lower QueueLimit. Acked sends go one per round trip, so never use ack: true
for a high-rate stream.
Errors are AdapterError with .Code and usually .Hint — a one-line next action. Print the
code and e.Hint ?? e.Message in your error paths: several codes carry no hint (AckTimeout,
ValidationError, SessionEnded, some ConfigErrors), and an error without a message of its
own has the code as its message (AckTimeout) — so also say which call failed.
Roster. await client.MembersAsync() returns an IReadOnlyList<Member> (you included) and
await client.ListenersAsync(channel) a Listeners with Channel, Declared and Broadcast
(lists of Member, you excluded). Re-read MembersAsync() after every (re)connect — joins and leaves that happened while you were
disconnected are not replayed as events. MembersAsync() and ListenersAsync() are server round trips:
they fail with NotConnected while the client is not connected.
Do not share one HttpClient between clients. The join keeps the server's guest cookie,
and the server reuses the participant id it names — so two clients built on the same
ConnectOptions.HttpClient (with cookies on, the default) join as the same participant,
and one's CloseAsync()/Dispose() marks the other as left (its publishes then fail with
Unauthorized). Give each client its own HttpClient (or a handler with UseCookies = false).
That includes a retry loop: a ToStageAsync that failed (e.g. JoinTimeout) may still have a
handshake in flight that completes later and leaves — retrying with the same cookie-enabled
HttpClient lets that late leave end the retry's member.
Threading: callbacks and events fire on background threads, never marshalled to a UI
context. Server events — channel messages, HistoryReplaced, presence, remote-input holder
notices — run one at a time, in the order they arrived, on the socket's receive loop (a
thread-pool thread). Lifecycle events can also come from other threads: the reconnect task
(StateChanged, Ended), whichever thread continues after await client.CloseAsync(), and
Dispose(), which raises Ended synchronously on the caller's thread before it returns.
Reading state — Latest(), History(), State, QueuedCount — is thread-safe, so a UI
timer may poll it from its own thread. So marshal every handler that touches UI, and never
block in a callback — a blocked callback
holds back every later event of that client, which fails in two ways:
- Waiting on the adapter from a callback times out.
SendAsync(…, ack: true).GetAwaiter().GetResult()(or.Result/.Wait(),MembersAsync().Result,PingAsync().Result) waits for a server reply that only this blocked thread can read. It fails withAckTimeoutafter the full ack timeout (15 s by default) even though the server accepted the publish — an app that retries then publishes the value twice. - A callback blocked past the server's heartbeat drops the connection. The server
closes a socket that stops answering its pings (Connect's default: a ping every 25 s,
20 s to answer); the adapter reconnects and re-seeds
History()/Latest().
await inside an async handler is fine: the handler gives the thread back to the
receive loop at its first await, so the send below gets its ack. Catch exceptions
inside it yourself — an async lambda passed as an Action (to On() or to an event) is
async void, so the adapter cannot catch what escapes it, and an exception that does
(AckTimeout, SessionEnded, …) crashes the process:
client.On("ask", async msg =>
{
try
{
await client.SendAsync("reply", 1, ack: true);
}
catch (Exception e) // an exception escaping an async void lambda would crash the process
{
if (e is AdapterError a)
{
var why = a.Hint ?? a.Message; // AckTimeout carries neither a hint nor more than its code
Console.Error.WriteLine("reply failed: " + (why == a.Code ? a.Code : a.Code + ": " + why));
}
else Console.Error.WriteLine(e);
}
});
To touch UI objects (WPF/WinForms/Unity), post without waiting —
Dispatcher.BeginInvoke/InvokeAsync, SynchronizationContext.Post, or Unity's
main-thread queue — never Dispatcher.Invoke, which waits for a UI thread that may
itself be waiting on this client. A synchronous handler that throws stops neither the adapter
nor the other handlers: the exception arrives on Error as SubscriberError (an async void
handler's exceptions never reach the adapter — see above).
Error codes
Every failure is an AdapterError (an Exception) with .Code (branch on this — it
is the stable identifier), .Message and usually .Hint — a one-line next
action worth logging. Errors throw from the call that caused them, and lifecycle
failures also arrive on the Error event.
| Code | Meaning | adapter behaviour |
|---|---|---|
AuthRevoked |
Adapter key rejected, revoked, or expired | Terminal — auto-rejoin gives up (ended: "rejoin-abandoned: AuthRevoked"); issue a new key |
ProtocolVersionMismatch / ClientAheadOfServer |
Wire version gate | Terminal — upgrade one side; rejoin gives up rather than retrying forever |
ValidationError |
Bad channel/value locally, or the server rejected the join body (400) | Local checks fail before any network call; a join 400 names the fields the server rejected (see below) |
RoomEnded |
No live session — an Editor/Owner has to open the stage in Connect (people who joined through a share link cannot start one), or use a key created with Let adapters start a session turned on (Share → Adapter keys) so it can start one | ToStageAsync throws it at once; after a successful join, auto-rejoin (on by default) keeps waiting and joins when the session opens |
SessionEnded |
The client has ended (closed, or the session is over for good) | Sends fail; queued acks reject |
StageFull |
Participant cap reached | Surfaced from the join; rejoin keeps waiting — a seat may free up |
StageArchived |
The stage is archived | Surfaced from the join — ask its owner to restore it |
TooManyRequests |
Server rate limit (60 messages a second per connection), seen only on acked sends | Automatic backoff (1s → ×2 → 60s) and retry from the offline queue — not thrown |
TooManyRequests from Connect.ToStageAsync |
The server refused the join (429): too many failed join attempts from this network address — 20 within 5 minutes, usually another program here still using a revoked or mistyped token — or more than 60 joins a minute with one adapter key (a restart loop); servers without the per-key join limit also refuse a sixth join from one address within a minute | Thrown from Connect.ToStageAsync, not retried — wait up to 5 minutes, and fix the program that causes it |
KeyMaterialUnavailable from Connect.ToStageAsync |
The server (503) cannot read the stored material of an older adapter key on this stage — a server-side key change left it behind; after 30 of these from one address within a minute, a correct key gets the same answer until the minute ends | Thrown from Connect.ToStageAsync, not retried (a joined client keeps retrying while it rejoins) — ask whoever runs your Connect to revoke the old keys |
AckTimeout |
No ack within the ack timeout, or the connection closed with the ack pending | Surfaced to the caller of an acked send (at once when the connection closes) — the server may still have it |
Standby |
An acked send while this instance is standby (ExclusiveName), or a queued acked send discarded when it became standby |
Not sent; a plain send is dropped instead |
QueueOverflow |
Queue cap hit (default 1000 — sending faster than 60/s, or a long disconnect) | Oldest item dropped and rejected, plus QueueOverflow event |
NotConnected / JoinTimeout / ConfigError |
Client side: unreachable server (or MembersAsync()/ListenersAsync() while not connected) · connected but never admitted · bad options |
Surfaced to the caller — ConfigError before any connection is attempted |
Unauthorized / NotSupported |
The server refused a roster or publish request (e.g. this connection was already marked as left) · the call is not available on this transport or server (remote-input registration on the Engine profile, EnsureStreamLayerAsync() on a server without the route) |
Thrown from that call |
EnsureStreamLayerAsync() errors |
NotSupported (server without the route) · RoomEnded (no live session) · TooManyRequests · ValidationError (the server's message; a hint when it says no ProvidesView = "stream" or the stage's Adapter Stream layer limit) · NotConnected (network or server error, or no answer within the ack timeout — the timeout covers a 401 re-validation too) · errors from that 401 re-validation pass through as Connect.ToStageAsync would report them (e.g. AuthRevoked), except a server (5xx) or network failure during it, which is NotConnected · SessionEnded (the client has ended — nothing is sent) |
Thrown from that call; cancelling the token throws OperationCanceledException |
SubscriberError |
One of your callbacks or event handlers threw | Surfaced on the Error event; the client — joining, reconnecting and ending included — and the other handlers keep running rather than tearing down over a handler bug |
A 400 from the join carries the server's own issue list instead of a bare (400) —
that failure is almost always a version skew between server and adapter, not a bad
token:
[ValidationError] token/validate rejected the request body (400):
clientType — Invalid literal value, expected "adapter"
Up to three fields are shown, then (+N more).
An AuthRevoked whose message says stage-locked means the stage is closed to guests, and
adapters join as guests; the hint asks you to have the stage owner (or whoever runs your
Connect) reopen it to guests.
ExclusiveName = true — one active instance per name. The server keeps the newest
instance active and marks the others standby; standby keeps receiving and takes over when
the active one leaves. Only instances on the same adapter key are judged together — a copy
with a different key joins as name (2) and the rule does not apply, so a failover pair
shares one key. The judgment arrives as Member.Standby and the client enforces it for you:
While standby, new sends are dropped (fire-and-forget, debug log only) or fail with
Standby (ack: true) — never deferred. When an instance becomes standby — after a reconnect
or when presence changes — everything it had queued is dropped the same way (the standby
entry in Diagnostics() ends with — dropped N queued sends), so a later promotion sends nothing
stale. After each (re)connect the adapter needs one roster round trip to judge standby; sends
made meanwhile are held (sharing QueueLimit), then queued if this instance is active (or the
judgment failed) or treated by the standby rule. There is
no standby-change event: read client.Standby, or look for the standby / active entries in
Diagnostics().
Examples
The package ships three runnable examples — the same three scenarios every language of the
adapter has — as one Program.cs each:
| File | Shows |
|---|---|
examples/Quickstart/Program.cs |
connect · the first acked round trip · receive |
examples/RosterBridge/Program.cs |
both directions and the roster (MembersAsync) |
examples/Resilience/Program.cs |
reconnect · offline queue · auto-rejoin |
To run one, make a console app, add the package and replace its Program.cs with the example's
(the console template already turns on the implicit usings and nullable settings the examples use):
dotnet new console -o Quickstart && cd Quickstart
dotnet add package StudioXid.OmniAdapter
cp ~/.nuget/packages/studioxid.omniadapter/<version>/examples/Quickstart/Program.cs Program.cs
CONNECT_TOKEN=cst_… dotnet run # or: dotnet run -- "cst_…"
In the adapter repository the same three are solution members (dotnet run --project examples/Quickstart from csharp/), so dotnet build keeps them in step with the API. The
Unity example (below) is in the repository only.
Unity
The adapter repository's examples/Unity/ (not in the NuGet package) is a runnable
car-telemetry example (verified on Unity 2021.3 LTS) plus the two glue scripts every Unity integration needs — a main-thread
dispatcher and a MonoBehaviour that owns the connection's lifecycle. Callbacks
arrive on background threads and almost every Unity API throws off the main thread, so
the main-thread dispatcher is required, not optional.
Its fetch-plugins.sh <project> builds the netstandard2.0 target
and copies the whole dependency closure (13 assemblies) into Assets/Plugins/ —
Unity has no NuGet, and it refuses to load a plugin whose assembly references it
cannot resolve, so the .NET Standard 2.0 shims have to ship too.
Limits: WebGL is not supported (the transport needs System.Net.WebSockets), IL2CPP
builds are not verified, and UPM packaging is not done (loose scripts plus copied DLLs) —
see docs/COMPATIBILITY.md in the package.
Diagnostics — doctor as a library call
var results = await Doctor.RunAsync(credential); // IReadOnlyList<CheckResult>
Console.WriteLine(Doctor.FormatReport(results));
Eight checks run in order and stop at the first failure (the point is to name one
cause, not list a cascade): credential · url shape · server reachable · adapter screens ·
remote input · stage session · socket join · screen adapters. Only ✖ lines need fixing
(△ and · are informational). The credential is masked in the report. It diagnoses a cst_…
token; a bare ck_… key carries no server or stage, so the report says so. It checks the
connection, not delivery — a green report with a silent peer points at channel names, routing
or the receiving side.
Print the report when connecting fails:
var token = Environment.GetEnvironmentVariable("CONNECT_TOKEN") ?? "";
ConnectClient client;
try
{
client = await Connect.ToStageAsync(new ConnectOptions { SecretKey = token, DisplayName = "Line Controller" });
}
catch (AdapterError e)
{
Console.Error.WriteLine($"[{e.Code}] {e.Hint ?? e.Message}");
Console.Error.WriteLine(Doctor.FormatReport(await Doctor.RunAsync(token))); // fix the ✖ lines
return 1;
}
HTTP and the connect step are injectable, so you can unit-test the whole thing. The
terminal omni-adapter CLI is TypeScript/Python only — npx --no-install omni-adapter doctor "$CONNECT_TOKEN"
in a Node project that has the TypeScript package installed, or
python -m omni_adapter doctor "$CONNECT_TOKEN" with the Python package.
Engine profile (Blazor WASM) — no credential, no seat
Running inside a stage-canvas layer that hands the page a MessagePort — a Connect Omni
Web View layer (Add → Web View: any page URL; its Stage messages rules list the channels
the page may receive and send) or an Engine Layer iframe — the
adapter borrows the host's authenticated connection: no cst_ token in the page and
no guest seat. There is no automatic detection here (that is TypeScript's credential-less
connect()): you assemble the client yourself — an EngineTransport over the parent-window
bridge you implement (IEngineHostWindow / IEnginePortHandle), wrapped in a ConnectClient.
Blazor's JS interop lives in your app, so this package keeps its netstandard2.0 (Unity) target.
// window: your IEngineHostWindow (window.parent.postMessage + the transferred MessagePort, via JS interop)
var engine = new EngineTransport(window, "Speed Panel", receives: new[] { "car.speed" },
sends: new[] { "panel.ready" }); // announced to the host (engine:message-declare) — information, not permission
var client = new ConnectClient(engine);
await client.OpenAsync(); // the handshake — no credential, no seat
client.On("car.speed", msg => Console.WriteLine(msg.Value));
await client.SendAsync("panel.ready", true);
// Engine-layer control lives on the transport, not on the client:
await engine.AcquireControlAsync(); // presenter lease — writes need it first
await engine.SetStateAsync(new { page = 2 }); // live shared state (≤8KB)
using var off = engine.OnState(frame => Console.WriteLine(frame.Revision));
The adapter owns the protocol: the two-step handshake (identity echo, then the port
that arrives with the second host-init) or the Web View layer's one-step
adapter-view:init handoff (port in the first message; the layer's Receive rules cap
subscribe and its Send rules cap publish — exposed as AllowedReceives and AllowedSends;
AllowedChannels, both together, is obsolete. A subscription outside Receive is dropped without
an error and a send outside Send is refused. Channels the page declares but the rules lack show up
in the layer's Stage messages as ones "This page asked for", for the designer to add with Add.
Saving changed rules closes the port and reloads the page, so your bridge should call
NotifyPortClosedAsync() on the port's close event), explicit subscribe (receives, max 32 — that
declaration is the inbound), request/response correlation, and the presenter lease /
shared state / session snapshot operations.
Honest limits (v1): no ring-buffer history replay — but Latest() is seeded, because
the host replays each subscribed channel's most recent value; MembersAsync() answers
empty (there is no seat); there is no reconnect concept (the host owns the layer's life).
Screen broadcast (Adapter Stream)
Connect with ProvidesView = "stream" and the server puts an Adapter Stream layer for your
DisplayName on the stage (or binds the one already placed under that name) — the layer is how the
stage finds your screen. ScreenBroadcast.Start announces you (ready) and answers each viewer's
offer with your session factory:
var client = await Connect.ToStageAsync(new ConnectOptions { SecretKey = "cst_…", DisplayName = "gauge", ProvidesView = "stream" });
Console.WriteLine($"on the stage as {client.Me?.DisplayName}"); // "gauge (2)" if another adapter key holds "gauge"
using var broadcast = ScreenBroadcast.Start(client, (viewer, sendIce, iceServers) => OpenSession(viewer, sendIce, iceServers));
broadcast.SourceChanged(); // when the capture starts or changes (not per frame) — viewers that got no answer offer again
- If the factory returns
null(nothing to send yet), the viewer gets no answer; callSourceChanged()once the source exists. Call it when the source starts or changes, not per frame — calls are coalesced to at most onereadya second. - Starting a broadcast without
ProvidesView = "stream"writes onestream-undeclaredwarning to the diagnostics ring — the server creates and binds no layer for such an adapter. It is judged from theProvidesViewyou connected with. - The web keeps one receiver per (viewer page × adapter participant), each with its own
receiverId— not one per layer instance; two receivers on one page replace each other — so a person with two tabs gets two sessions: your factory is called once per tab with the same viewer id, andViewerCountcounts sessions. A new offer from the same tab replaces only that tab's session. A PIN or share-link guest's refreshed or closed tab leaves its session behind (the server reports such a guest leaving only when their last tab goes; team members get a new participant id per tab, so theirs is reported), so each person keeps at most 4 sessions — a fifth evicts first a session whose answer has not been sent yet, then their oldest. Report closures (next point) so stale receivers don't use the cap and push out a live tab. When the person leaves, all of their sessions close. Remote input is judged per person. Viewers that send noreceiverId(older web) keep one session per person. - Call
broadcast.SessionClosed(session)when a session's peer connection reachesfailedorclosed: the helper forgets it at once and calls itsCloseAsync()on the thread pool — the call returns immediately, so it is safe inside the peer connection's state callback (keepCloseAsync()idempotent). A newer offer from the same tab that is still being negotiated is left alone. Optional — otherwise a dead session stays until the viewer offers again, leaves, or is evicted. - Viewer ICE that arrives early (before the session exists or has applied the offer, or even before the
offer) is queued and handed over once the offer is applied. ICE that comes before any offer is held for
10 s, for at most 4 receivers per viewer and 64 in total (the oldest is dropped; one
ice-queuediagnostics note). If the ICE-server lookup fails or takes longer than 5 s, the helper answers with the last known servers (oneice-serversdiagnostics note). - If the adapter rejoins as a new participant (a new session after the stage reopened, or a long-lived adapter re-validating its key), the helper closes every viewer session from before — viewers address the adapter by participant id and offer again to the new one.
EnsureStreamLayerAsync()is optional (idempotent).Renamedmeans the server joined you under a different name (gauge (2): another program on a different key usesgauge, or thegaugelayer is bound to a key you rotated without revoking — rename one, or revoke the old key), so a layer placed forgaugewill not show this screen. For two instances of the same program that take over from each other, put both on one key and setExclusiveName = true(one active, the other standby). Errors are in the table above; cancelling the token throwsOperationCanceledException.
Remote input
Lets an Editor drive your broadcast screen with their pointer — no registration code and no
extra code on your side: use the 4-parameter session factory, wrap your WebRTC data channel as
IRemoteInputChannel, and pass onRemoteInput:
using var broadcast = ScreenBroadcast.Start(
client,
(viewer, sendIce, iceServers, wireInput) => OpenSession(viewer, sendIce, iceServers, wireInput),
onRemoteInput: (msg, viewer) => Inject(msg)); // coordinates are 0..1 — injecting them is the app's job
Directions are whitelisted, coordinates clamped to [0,1], and holder loss or channel close
synthesizes cancel for open pointers. The holder gate stays permissive until the server
announces a holder; once a notice arrives, onRemoteInput fires only for that holder (local TTL
expiry included) for the rest of the session. Standalone servers send lease-holder notices: input is accepted only from the Editor holding the
lease (key adapters are registered automatically when they join and are told the holder; the Connect
editor claims the lease on its first pointer-down), and PIN and share-link viewers never control.
Older servers that predate those notices never announce a holder, and the helper then accepts every
viewer's input. The registration API —
SubmitRegistrationCodeAsync(code) (returns a RegistrationId and a DeviceSecret, which is a
secret), ResumeRegistrationAsync(secret) and the RemoteInputHolder event — is for servers that
turn on one-operator-at-a-time control by registration code; you don't need it otherwise. Callbacks
arrive on the socket/WebRTC thread — marshal to your UI thread yourself.
A viewer that leaves takes its whole footprint with it — session closed, hello keepalive
stopped, input-dropped dedupe cleared. That includes viewers that left while the adapter
was reconnecting (the server's peer-left is not replayed): the helper remembers its viewers
when the connection drops and, on the server's peers reply to the next ready, closes the
ones that are no longer connected (no reply from an older server closes nothing). A viewer's
data channel stops delivering input once its session is gone, and a superseded session's ICE
candidates are not relayed. When the client ends, the helper stops itself.
Testing (adapter repository)
cd csharp && dotnet test
ProtocolDriftTests pins the wire constants against the sibling TypeScript adapter
sources in this repo (which in turn drift-check against the server's protocol
package); the check skips itself in a standalone checkout.
Testing without a server — MemoryStage
var stage = new MemoryStage();
var sensor = await stage.JoinAsync(new MemoryJoinOptions { DisplayName = "sensor", Sends = new[] { "sensor.temperature" } });
var panel = await stage.JoinAsync(new MemoryJoinOptions { DisplayName = "panel", Receives = new[] { "sensor.*" } });
panel.On("sensor.*", m => Console.WriteLine(m.Value));
await sensor.SendAsync("sensor.temperature", 23.5, ack: true); // panel receives it; sensor does not (no echo)
stage.Inject("ui.tap", 1); // as if a prototype sent it
stage.Disconnect(panel); stage.Reconnect(panel); // drop + recover: history snapshot, queue flush
stage.End("host closed the stage"); // everyone gets Ended
Emulates the wire rules in-process (no self-echo, strict delivery, history ring,
ExclusiveName standby, ListenersAsync); rejectPublish: injects failures. A harness,
not a server — no doctor, no REST, no media, and no 60-messages-a-second pacing (its
transport implements IRateLimitBypassTransport). EnsureStreamLayerAsync() answers with a stable
fake layer per name (memory-layer:<name>; stage.StreamLayers() lists them).
Testing without hardware — Playback.ReplayAsync · Playback.SimulateAsync
var records = Playback.ParseRecording(File.ReadAllText("run.ndjson")); // written by `omni-adapter record`
await Playback.ReplayAsync(client, records, new ReplayOptions { Speed = 2 });
await Playback.SimulateAsync(client, "sensor.temperature",
new SimulateOptions { Waveform = "sine", Min = 18, Max = 26, Hz = 2, DurationMs = 30_000 });
Both publish through SendAsync (rate limit, queue, standby and backoff unchanged), wait for
the queue to drain (giving up after 15 s without progress) before returning, stop on Ended or a cancelled token (checked
before each send and during a wait), and return the partial count.
Wait/Random are injectable for deterministic tests. They only pace the sends — the 15 s no-progress limit runs on the real clock, so a no-op wait does not make it give up early.
History is state, not triggers
History()/Latest() are re-seeded from the server snapshot on every (re)join whose joined payload carries one (the stage:joined fallback re-seeds nothing) and HistoryReplaced fires — but the snapshot is never replayed into On() callbacks. A command published while this adapter was disconnected is lost as a trigger and survives only as a last value: read Latest() when StateChanged reports connected for state channels; treat trigger channels as at-most-once across a disconnect. Deliberate — replaying into callbacks would re-fire a stale command minutes late.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- SocketIOClient (>= 3.1.2)
- System.Text.Json (>= 8.0.6)
-
net8.0
- SocketIOClient (>= 3.1.2)
- System.Text.Json (>= 8.0.6)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0 | 101 | 11/16/2026 |
| 0.1.0-beta.3 | 85 | 11/2/2026 |
| 0.1.0-beta.2 | 61 | 10/30/2026 |
| 0.1.0-beta.1 | 60 | 10/30/2026 |
| 0.1.0-beta.0 | 67 | 10/29/2026 |