omnyshell_client_web library

OmnyShell Client for the browser (dart2js / DDC): authenticate with a Hub, discover nodes, and manage sessions — over the platform WebSocket.

This is the browser-safe counterpart of omnyshell_client.dart. The latter re-exports dart:io-bound helpers (progress bars, local commands, file transfer, OmnyDrive) that cannot compile to JavaScript; this barrel exports only the subset that runs in a browser. Import this, never omnyshell_client.dart, from web code.

final client = ClientRuntime(ClientConfig(
  hubUri: Uri.parse('wss://hub.example.com:8443'),
  credentials: TokenCredentialProvider(principal: 'alice', token: '...'),
));
await client.connect();
final nodes = await client.listNodes();

Classes

ActiveSessionDetachRequest
Client → Hub: detach an active (attached) session on nodeId from another connection — e.g. when a full-screen program owns the original terminal. sessionRef is an id/short-id/prefix, or empty to target the caller's sole active session. Correlated by requestId.
ActiveSessionDetachResponse
Hub → Client: the result of an active-session detach. Correlated by requestId.
ActiveSessionDetachResult
The result of ClientRuntime.detachActiveSession.
AgentAbort
A cooperative cancellation signal for an AgentService run.
AgentCommandRunner
Runs commands the agent decides to execute, decoupling the agent loop from the concrete transport (ClientRuntime) so it stays browser-safe and unit-testable with a fake.
AgentEnvironment
Facts about the target node, woven into the system prompt so the model knows what it is operating.
AgentHandlers
Host-side interaction hooks the agent uses to talk to the user. The CLI and the web client provide their own implementations; tests provide fakes.
AgentPlan
A plan the model presents (in AgentMode.plan) before executing.
AgentPlanStep
A single step in a proposed plan.
AgentService
Drives a provider-agnostic agent loop that investigates a node, plans and executes commands to accomplish a natural-language goal.
AgentStyle
Maps the agent's output categories to display styling.
AiCommand
The :ai $prompt local command: drives a provider-agnostic AI agent that investigates the node, plans and executes commands to accomplish a natural-language goal, with command_shield gating every command.
AiConfig
Immutable AI configuration: which provider/model to use, the API key, the default agent mode and loop bounds.
AiConfigRequest
Client → Hub: ask for the Hub's default AI configuration (provider/model and agent defaults) so a browser embedder can offer "use the Hub default" without ever seeing an API key. Correlated by requestId.
AiConfigResponse
Hub → Client: the Hub's default AI configuration. Never carries an API key — the key stays on the Hub and is injected when proxying. available is false when the Hub has no AI provider configured. Correlated by requestId.
AiMessage
A single message in the conversation.
AiModelCheck
The outcome of validating one model with a live provider request.
AiProvider
A chat provider that supports tool calling.
AiResult
One assistant turn returned by a provider.
AiToolCall
A single tool invocation requested by the model.
AiToolResult
The outcome of executing an AiToolCall, fed back to the model.
AiToolSpec
A tool the model is allowed to call. parameters is a JSON-Schema object.
AiUsage
Token usage and latency for a single provider call.
AnsiAgentStyle
ANSI-colored AgentStyle for terminals.
AnsiTerminalDriver
A TerminalDriver base that turns ScreenBuffer frames into ANSI byte output, leaving the byte sink, size, and input/resize streams to subclasses.
AuthFail
Failed authentication.
AuthOk
Successful authentication, carrying the resolved identity and a session token bound to this connection.
AuthRequest
A login attempt presenting a credential.
Cell
A single terminal cell: one printable character and its Style.
Channel
One logical, bidirectional stream multiplexed over a connection.
ChannelClose
Tear down a channel.
ChannelEof
Half-close a stream (typically stdin) on the channel.
ChannelExit
Node → Client: the process exited.
ChannelId
A logical channel identifier, scoped to a single physical connection.
ChannelMultiplexer
Multiplexes logical Channels over a single OmnyShellConnection.
ChannelResize
Resize the terminal of an interactive session.
ChannelSignal
Deliver a POSIX signal to the session's process.
ChannelWindow
Backpressure credit grant for a stream on a channel.
ClientConfig
Configuration for a ClientRuntime.
ClientRuntime
An embeddable OmnyShell client: authenticates with the Hub, discovers nodes, and opens exec / interactive sessions.
Clock
Time source used throughout OmnyShell so tests can fix now.
CmdShellDialect
Windows cmd.exe — the degraded last resort. cmd /Q disables command echo; initLine shrinks the prompt to >. The marker reports only the working directory (%CD%): git branch/status and privilege are omitted, since cmd cannot compute them inline. The token is written in two set /p pieces so it never appears verbatim in the command text.
Color
An immutable terminal colour: either a named ANSI colour or a 256-palette index. Use Color.ansi for theme-honouring named colours and Color.indexed for a fixed palette entry.
CommandExecution
A single in-flight command launched by the IDE terminal panel: a stream of output output lines (stdout and stderr merged, one event per line), a exitCode future, and a kill to terminate it early.
CommandHistoryBuffer
An ordered, bounded set of history entries with the shell's add rules.
CommandHistoryStore
A persistent command history a LineEditor can record into and navigate.
CommandRun
The result of running a single command on the node.
CommandRunner
Runs a shell command line and exposes its output as a CommandExecution. Abstracted so the IDE can target a local process, a remote node, or a fake in tests.
ControlFrame
A control message frame (carried as a WebSocket text frame).
ControlMessage
Base class for every structured control message.
CredentialProvider
Produces the AuthRequest a node or client sends in response to the Hub's challenge hello.
CwdMarker
Client-side shell integration that learns the remote working directory.
CwdScan
The outcome of feeding one chunk of remote stdout to a CwdMarker.
DataFrame
A binary stream-data frame (carried as a WebSocket binary frame) with a fixed 10-byte header followed by the raw payload bytes.
DetachedSessionInfo
A user-facing view of a detached session living in a node's in-memory registry, as returned by the list API and relayed through the Hub.
DetachedSessionKillRequest
Client → Hub: terminate the caller's detached session sessionRef (an unambiguous id or prefix) on nodeId. Correlated by requestId.
DetachedSessionKillResponse
Hub → Client: the result of a detached-session kill. Correlated by requestId.
DetachedSessionKillResult
The result of ClientRuntime.killDetachedSession.
DetachedSessionsRequest
Client → Hub: list the caller's detached sessions on nodeId. Correlated to the response by requestId (a connection-level request/response RPC).
DetachedSessionsResponse
Hub → Client: the caller's detached sessions. Correlated by requestId.
DetachOutcome
The result of RemoteSession.detach: the detached session's identifiers and optional expiry, used to print the resume hint.
DriveCredentialEntry
One masked git-credential entry returned by a list (secrets never leave the node — description is the credential's masked toString).
DriveCredentialRequest
Client → Hub: manage the caller's own git credentials on nodeId.
DriveCredentialResponse
Hub → Client: the result of a drive-credential operation. Correlated by requestId.
DriveCredentialResult
The result of ClientRuntime.peekSession: the current screen snapshot of a session, captured without attaching to it. The result of a drive credential RPC against a node.
Ed25519PublicKey
An Ed25519 public key, used to identify users and nodes in an authorized_keys-style trust store. Equality is by key bytes.
ErrorCodes
Stable, machine-readable error codes carried in error control messages and surfaced on OmnyShellExceptions.
ExecResult
The result of a one-shot ClientRuntime.execute.
FrameCodec
Encodes and decodes OmnyShellFrames to and from WebSocket events.
Hello
First frame after the WebSocket upgrade. The Hub sends hello with a single-use nonce; the peer replies with its role and capabilities.
HistoryCursor
A reusable Up/Down navigation cursor over a CommandHistoryBuffer.
HttpProxyRequest
Client → Hub: make an outbound HTTPS request to an AI provider on the client's behalf (the browser cannot, due to CORS). The Hub validates the target against an allowlist, optionally injects credentials, and replies with an HttpProxyResponse. Correlated by requestId.
HttpProxyResponse
Hub → Client: the result of a proxied AI request. On a transport-level failure (rejected host, timeout, DNS) error is set and statusCode is 0. Correlated by requestId.
HubAiConfig
The Hub's advertised default AI configuration, returned by ClientRuntime.fetchHubAiConfig. Never carries an API key — the key stays on the Hub. available is false when the Hub has no default provider.
HubHttpClient
An http.Client that tunnels requests through the Hub instead of issuing them from the current process.
IdeApp
The full-screen TUI IDE: a file-tree sidebar, a tab bar of open files, a syntax-highlighted editor with a git-change gutter, and a status bar.
InteractiveShellController
Pure Dart (no dart:io, no DOM), so the orchestration is identical and unit-testable across the CLI, the browser, and any other embedder.
KeyDecoder
Turns raw terminal input bytes (read in raw mode) into KeyEvents.
KeyEvent
An immutable decoded key press.
LineEditor
A raw-mode line editor with command-history navigation.
LocalCommand
A local OmnyShell command, invoked with a leading : and never forwarded to the remote shell.
LocalCommandContext
Runtime context passed to a LocalCommand.
LocalCommandRegistry
An extensible registry of local : commands.
NodeActiveSessionDetach
Hub → Node: detach the principal's active session sessionRef.
NodeActiveSessionDetachResponse
Node → Hub: the result of an active-session detach. Correlated by requestId.
NodeCapabilities
What a node can do, advertised to the Hub after registration and relayed to clients during discovery.
NodeCapabilitiesMessage
Node → Hub: advertises capabilities after registration.
NodeDescriptor
A node's public description as registered with the Hub and returned by discovery (nodes list). Combines identity, platform, operator labels and advertised capabilities.
NodeDetachedSessionKillRequest
Hub → Node: terminate the principal's detached session sessionRef.
NodeDetachedSessionKillResponse
Node → Hub: the result of a detached-session kill. Correlated by requestId.
NodeDetachedSessionsRequest
Hub → Node: list the principal's detached sessions. Correlated by requestId.
NodeDetachedSessionsResponse
Node → Hub: the principal's detached sessions. Correlated by requestId.
NodeDriveCredentialRequest
Hub → Node: manage principal's git credentials. The principal is stamped by the hub from the authenticated peer; the node only ever mutates that principal's scope. Correlated by requestId.
NodeDriveCredentialResponse
Node → Hub: the result of a drive-credential operation. entries carries the masked credential list for list. Correlated by requestId.
NodeHeartbeat
Node → Hub: periodic liveness signal with a monotonic sequence number.
NodeHeartbeatAck
Hub → Node: acknowledges a heartbeat.
NodeId
Stable identity of a node, used by clients to address it (instead of a host:port). Equality is by value.
NodeListRequest
Client → Hub: requests the list of nodes the client may see.
NodeListResponse
Hub → Client: the discovered nodes.
NodeRegister
Node → Hub: registers the node's identity and platform.
NodeRegistered
Hub → Node: confirms registration.
NodeSessionDetach
Hub → Node: detach the session on the node-side channel, on behalf of principal. Mirrors SessionDetachRequest across the relay.
NodeSessionDetached
Node → Hub: the session was detached and now lives in the node registry.
NodeSessionOpen
Hub → Node: instructs the node to start a session on a node-side channel.
NodeSessionOpened
Node → Hub: the node accepted and started the session.
NodeSessionRejected
Node → Hub: the node refused the session.
NodeSessionScreenRequest
Hub → Node: fetch the current screen snapshot of the principal's session sessionRef. Correlated by requestId.
NodeSessionScreenResponse
Node → Hub: the current screen snapshot of a session. The replayable bytes (the same a resume would paint) are base64-encoded in screenBase64. Correlated by requestId.
NodeTunnelConnect
Hub → exposer (node or client): a public connection arrived; adopt channel, dial targetHost:targetPort, and bridge bytes. Reply with NodeTunnelConnected or NodeTunnelConnectFailed.
NodeTunnelConnected
Exposer → Hub: the target was dialed; the Hub may relay bytes on channel.
NodeTunnelConnectFailed
Exposer → Hub: the target dial failed; the Hub closes the public socket.
OmnyShellConnection
A duplex, frame-oriented link between two OmnyShell peers.
OmnyShellFrame
A decoded unit travelling over a connection: either a structured control message (ControlFrame) or a binary stream payload (DataFrame).
OmnyUid
A deterministic, globally-stable identifier for a node or a hub.
Ping
Application-level keepalive request, used to measure round-trip latency and detect half-open connections.
PlatformInfo
Describes the operating system and architecture a node runs on, advertised to clients during discovery and shown by the :info local command.
Pong
Reply to a Ping.
PosixShellDialect
POSIX shells (sh, bash, zsh, Git Bash, WSL): the original protocol, unchanged. Uses trap, eval, stty and a printf/git/id marker.
PowerShellDialect
Windows PowerShell (pwsh/powershell). The shell reads commands from a redirected stdin (so input is never echoed); initLine silences the per-line prompt. The marker computes git status counts and the admin flag in PowerShell and writes one line directly to the console out.
Principal
An authenticated identity, as resolved by an Authenticator.
PrincipalId
Identity of an authenticated principal (a user or a node account) as known to the Hub. Equality is by value.
ProtocolError
A connection- or channel-level error.
PtySpec
Requested pseudo-terminal geometry for an interactive shell.
PublicKeyCredentialProvider
A CredentialProvider that signs the connection nonce with an Ed25519 private key.
RemoteCommandRunner
A CommandRunner that runs commands on a remote node via the connected ClientRuntime (executeStreaming), decoding the byte stream into output lines. dart:io-free, so it works in the web client too.
RemoteSession
A client-side handle to one open session on a node.
RemoteWorkspace
A Workspace backed by a remote node over the connected ClientRuntime.
ScreenBuffer
An off-screen grid of Cells the widgets paint into, plus a diff-based renderDiff that emits the minimal ANSI to turn a previous frame into this one (so only changed cells are rewritten — no flicker, minimal bytes).
Session
A domain view of a brokered session: who opened it, on which node, in what mode, and its current state and exit code.
SessionCommandResult
The captured result of running a command in the host's interactive session (see LocalCommandContext.runInSession).
SessionDetached
Hub → Client: the session was detached; resume it later by shortId.
SessionDetachRequest
Client → Hub: detach the live session on channel, keeping the node-side PTY/shell/processes running. Optional timeoutSeconds schedules automatic cleanup; null keeps the session indefinitely.
SessionId
Unique identity of a brokered session, minted by the Hub when a session is opened. Equality is by value.
SessionOpen
Client → Hub: opens a session on a node over a new client channel.
SessionOpened
Hub → Client: the session is open.
SessionRejected
Hub → Client (or Node → Hub via NodeSessionRejected): the session could not be opened.
SessionScreenRequest
Client → Hub: fetch the current screen snapshot of the caller's session sessionRef (active or detached) on nodeId, without attaching to it. Correlated by requestId.
SessionScreenResponse
Hub → Client: the current screen snapshot of a session. Correlated by requestId.
SessionScreenResult
ShellDialect
Generates the shell-specific text the interactive connect/resume loop sends to a remote shell: a one-time init line, the per-command wrapper, and the prompt-completion markers.
ShellPromptState
The remote shell's prompt context, reported to the host when the shell returns to its (idle) prompt so the host can render a prompt line.
ShellRunResult
Drives a ShellSessionPort as an interactive shell, terminal-agnostically.
ShellSessionPort
The minimal session surface an InteractiveShellController drives.
Style
An immutable bundle of a foreground/background colour and text attributes.
SystemClock
The default Clock, backed by the system wall clock (UTC).
TerminalDriver
The terminal capabilities the IDE engine depends on, kept dart:io-free so the engine compiles to JavaScript. The native Terminal (in terminal.dart) implements it for a real TTY; tests provide a fake; a web app provides its own driver feeding the rendered frames to a browser terminal widget.
TokenCredentialProvider
A CredentialProvider that presents a bearer token.
TunnelCloseRequest
Client → Hub: close the caller's tunnel tunnelRef (a full id or unambiguous prefix). Correlated by requestId.
TunnelCloseResponse
Hub → Client: the result of a tunnel close. Correlated by requestId.
TunnelCloseResult
The result of ClientRuntime.closeTunnel.
TunnelHandle
A handle to an open tunnel returned by ClientRuntime.openTunnel.
TunnelInfo
A user-facing view of an active TCP tunnel held by the Hub, as returned by the list API and relayed to the owning client.
TunnelListRequest
Client → Hub: list the caller's active tunnels. Correlated by requestId.
TunnelListResponse
Hub → Client: the caller's active tunnels. Correlated by requestId.
TunnelOpened
Hub → Client: the tunnel is open and listening. Correlated by requestId.
TunnelOpenRequest
Client → Hub: open a tunnel that exposes targetHost:targetPort (reachable by nodeId, or the requesting client's own machine when nodeId is the @local sentinel) on a public Hub port. When publicPort is set the Hub validates it against its configured range; otherwise the Hub allocates a free port in range. Correlated by requestId.
TunnelRejected
Hub → Client: the tunnel was refused. Correlated by requestId.
Workspace
The filesystem + command operations the IDE runs against.
WsChannelConnection
An OmnyShellConnection over any WebSocketChannel, with no dart:io dependency — the browser-safe counterpart of WebSocketConnection.
WsEntry
A directory entry returned by Workspace.list.
WsExecResult
The result of a one-shot command run via Workspace.exec.

Enums

AgentMode
How much autonomy the AI agent has when it wants to run a command.
AgentPhase
Which phase of the agent loop a model request belongs to, used to pick the model via AiConfig.modelFor.
AiProviderKind
The AI provider an AiConfig talks to.
AiRole
The author of an AiMessage.
AiStopReason
Why the model stopped this turn.
CommandConfirm
The user's answer at a command-confirmation prompt.
DataOpcode
The stream a binary data frame belongs to, encoded as the msgType byte of the data-frame header.
Focus
Which pane currently receives key input.
HttpProxyCredentialMode
How the Hub should authenticate a proxied AI request.
KeyType
The kind of a KeyEvent.
PlanApproval
The user's verdict on a presented plan.
SessionMode
How a session runs on the node.
SessionState
Lifecycle state of a session as tracked by the Hub.
ShellFamily
The command-language family of a node's interactive shell.

Extensions

AiWebCommands on LocalCommandRegistry
Registers the :ai command on a LocalCommandRegistry for a browser embedder.

Constants

kAiProxyElapsedMsHeader → const String
Response header the Hub proxy sets to report the upstream provider request duration in milliseconds.
kMinProtocolVersion → const int
The lowest protocol version this build can interoperate with.
kProtocolVersion → const int
The wire protocol version implemented by this package.
omnyShellVersion → const String
The canonical OmnyShell package version (kept in sync with pubspec.yaml).

Functions

aiRequestMs(Map<String, String> headers, int localMs) int
The request duration to record for a provider call: the Hub-reported upstream time from kAiProxyElapsedMsHeader when present (proxied requests), otherwise the locally measured localMs.
aiTokenCount(Object? value) int
Coerces a JSON value (provider usage counts may arrive as int or num) into a non-negative token count, returning 0 for null/unexpected types.
defaultModelFor(AiProviderKind provider) String
The default model for provider when neither the user, env, nor ai.yaml (CLI) or the Hub (web) specified one.
formatShellPrompt({required String principal, required String node, required String cwd, String? branch, String? gitStatus, String? privilege, bool color = true, int width = 0}) String
Formats the interactive shell prompt — user@node:cwd (git) $ — shared by the native CLI connect loop and web clients so the prompt looks the same everywhere. Pure string assembly with no I/O, so it compiles to JavaScript.
ideCommandSyntaxFor(ShellFamily? family) → CommandSyntax
Maps a shell family to the command_shield CommandSyntax the IDE's AI agent uses to validate the commands it runs. Defaults to bash.
isProtocolCompatible(int remoteVersion, {int? remoteMin}) bool
Whether a peer advertising remoteVersion (with optional remoteMin) is compatible with this build.
launchesForegroundProgram(String line) bool
Whether line launches an interactive foreground program that should take over the terminal (so the client switches to raw passthrough).
mayChangeCwdOrGit(String line) bool
Whether line could change the working directory or git state, and thus warrants a prompt refresh (the marker).
parseStatLines(String stdout) List<StatEntry>
Parses the TYPE|SIZE|PATH lines emitted by the node's find/stat run.
providerFor(AiConfig config, Client client) AiProvider
Builds the AiProvider matching config's provider kind, sharing client for all requests.
renderTree(String root, List<StatEntry> entries, {required int maxDepth}) List<String>
Renders entries (rooted at the start point root) as a tree-style listing: each line carries the aggregated size, directories are listed first, and subtrees deeper than maxDepth are collapsed (their line still reports the full aggregate). maxDepth == 0 means no depth limit.
resolveRemoteIdeRoot(String? arg, String? remoteCwd) String?
Helpers shared by the native :ide command and a web client's :ide, kept dart:io-free so both (CLI and browser) resolve the IDE root and pick the agent's command syntax identically. Resolves the remote IDE root from an optional arg and the current remote working directory remoteCwd:
validateModels(AiProvider provider, List<String> models) Future<List<AiModelCheck>>
Validates models against provider by sending a minimal, tool-free request per model — confirming the API key works and each model id is accepted. Errors are captured per model rather than thrown, so one bad model does not hide the others.

Typedefs

ConnectionFactory = Future<OmnyShellConnection> Function(Uri uri, {Map<String, String>? headers})
Opens a transport connection to uri, returning a connected OmnyShellConnection.
ControlDecoder = ControlMessage Function(int? channelId, Map<String, dynamic> data)
Decodes a control-message payload (the envelope d) for a registered type.
OmnyShellClient = ClientRuntime
Friendly alias for ClientRuntime, the embeddable OmnyShell client.
StatEntry = ({bool isDir, bool isLink, String path, int size})
A single find … -exec stat … entry: its absolute path, byte size and whether it is a directory or a symlink (leaf; never followed).

Exceptions / Errors

AiProviderException
Thrown when a provider request fails (network, auth, malformed response).
AuthException
Authentication failed: credentials missing, malformed or rejected.
AuthorizationException
The authenticated principal is not permitted to perform the action.
ChannelException
A logical channel was closed or referenced after teardown.
NodeUnavailableException
The requested node is unknown or offline.
OmnyShellException
Base type for every expected, classified failure raised by OmnyShell.
OmnyShellTimeoutException
An operation exceeded its deadline.
ProtocolException
A frame could not be decoded, or a message violated the protocol.
SessionRejectedException
A session could not be opened (rejected by the Hub or node).
TransportException
The underlying transport failed or closed unexpectedly.
TunnelRejectedException
A tunnel could not be opened (rejected by the Hub).
WorkspaceException
Thrown by Workspace operations on bad paths or I/O failures.