Interfaces
ConnectBridgeOptions
Properties
| Property | Type | Description |
|---|---|---|
dispatcher? | SandboxToolDispatcher | Custom tool dispatcher. Defaults to the built-in sandbox tool dispatcher (see ./dispatch.ts). Hosts can replace this to extend the tool surface. |
fetchImpl? | typeof fetch | Injectable fetch for the standby health poll (tests). Default: global. |
initialReconnectDelayMs? | number | Initial reconnect delay in ms (default 500). |
maxReconnectDelayMs? | number | Max reconnect delay in ms (default 30_000). |
noReconnect? | boolean | Disable the auto-reconnect loop (useful in tests where the test harness explicitly controls connection lifecycle). |
onStateChange? | (state: ConnectedBridgeState) => void | Called whenever the client transitions connection state. |
sandboxId? | string | Stable identifier for this sandbox session — surfaces in the bridge’s audit log entries. Default: a random UUID per page load. |
standbyPollMs? | number | Standby poll interval in ms (default 2_000). When the bridge closes this connection with the REPLACED code (another tab took the peer slot), the client polls the health endpoint at this cadence — plus per-poll jitter, so two standby tabs don’t stampede a freshly vacant slot — and only reconnects when sandboxConnected is false. |
toolNames? | string[] | Tool names to advertise to the bridge in the hello message. Defaults to SANDBOX_TOOL_NAMES. Override when supplying a custom dispatcher. |
url? | string | Bridge WebSocket URL. Overrides the discovery chain. Example: ws://localhost:3473/__pyric/sandbox, the socket pyric sandbox --bridge serves. |
workerRelay? | WorkerRelay | Generic worker relay (remote sandbox, slice 1). When supplied, the client advertises the worker-relay capability in its hello and routes worker-op / worker-sub / worker-unsub frames through it — on the worker path this forwards them into the SharedWorker port (relayWorkerOp / relayWorkerSub in serve/worker/client.ts). |
ConnectedBridge
Methods
disconnect()
disconnect(): void;
Close the bridge connection. Does NOT close the underlying sandbox.
Returns
void
state()
state(): ConnectedBridgeState;
Current connection state.
Returns
ConsumerPresenceFrame
Bridge → browser peer / Studio: broadcast connected remote consumer presence.
Properties
| Property | Type |
|---|---|
consumers | RemoteConsumerRecord[] |
type | "consumer-presence" |
HelloFromBridge
Bridge → browser: acknowledge connection.
Properties
| Property | Type | Description |
|---|---|---|
bridgeVersion | string | Bridge version, for compatibility checks. |
protocol | 1 | - |
type | "hello-ack" | - |
HelloFromClient
Browser → bridge: “I’m here and ready to receive tool calls.”
Properties
RemoteConsumerRecord
Record representing an attached remote consumer in presence snapshots.
Properties
| Property | Type |
|---|---|
activeLens | AuthLens |
clientSessionId | string |
connectedAt | number |
deviceLabel? | string |
lastSeen | number |
platform | string |
RemoteSetLensAckFrame
Bridge → Studio / peer: acknowledgement of a remote lens mutation request.
Properties
| Property | Type |
|---|---|
clientSessionId | string |
error? | { code: string; message: string; } |
error.code | string |
error.message | string |
id? | string |
ok | boolean |
type | "remote-set-lens-ack" |
RemoteSetLensFrame
Studio / peer → bridge: remote request to mutate a consumer’s active AuthLens.
Properties
| Property | Type |
|---|---|
clientSessionId | string |
id? | string |
lens | AuthLens |
type | "remote-set-lens" |
SandboxToolDispatcher()
SandboxToolDispatcher(
sandbox: LocalSandbox,
name: string,
args: Record<string, unknown>,
actAs?: AuthLens,
callerId?: string): Promise<{
data?: unknown;
ok: boolean;
summary: string;
}>;
Dispatch a tool call. Throws if the tool isn’t recognised (the bridge advertises only what this dispatcher reports it can handle, so unknowns indicate wire-level drift).
Parameters
| Parameter | Type | Description |
|---|---|---|
sandbox | LocalSandbox | - |
name | string | - |
args | Record<string, unknown> | - |
actAs? | AuthLens | The identity the bridge holds for the MCP caller, from the tool-call frame. Absent means the caller never impersonated (the bridge omits the default app-session), and the dispatch runs as it always has. |
callerId? | string | Stable MCP execution owner, independent of impersonated identity. |
Returns
Promise<{
data?: unknown;
ok: boolean;
summary: string;
}>
ToolCallRequest
Bridge → browser: please dispatch this tool call into the sandbox.
Properties
| Property | Type | Description |
|---|---|---|
actAs? | AuthLens | The identity the bridge holds for the MCP caller that made this call (auth_impersonate / auth_reset write it; auth_whoami reads it). The peer applies it as the DEFAULT identity for the dispatch: a tool argument that names an identity itself still wins for that call, and a family with no identity seam ignores it. Additive and OMITTED for the default { mode: 'app-session' }, so an un-impersonated call is byte-identical to what the bridge has always sent. |
args | Record<string, unknown> | Tool arguments (JSON-serializable). |
callerId? | string | Server-owned MCP caller identity for execution ordering, separate from its auth lens. |
id | string | Correlation id — browser must echo in ToolCallResponse. |
name | string | Tool name (e.g. firestore_simulator_create). |
type | "tool-call" | - |
ToolCallResponse
Browser → bridge: tool call result.
Properties
WorkerRelay
Host-supplied handlers that forward relay frames into the SharedWorker.
Methods
disconnect()?
optional disconnect(clientSessionId: string): void;
Teardown a remote consumer session’s virtual port and listeners.
Parameters
| Parameter | Type |
|---|---|
clientSessionId | string |
Returns
void
op()
op(op: WorkerOpPayload, clientSessionId?: string): Promise<unknown>;
Dispatch one worker op; resolves with the worker’s res.value.
Parameters
| Parameter | Type |
|---|---|
op | WorkerOpPayload |
clientSessionId? | string |
Returns
Promise<unknown>
subscribe()
subscribe(
sub: WorkerSubPayload,
onValue: (value: unknown) => void,
clientSessionId?: string): () => void;
Register a worker subscription; onValue receives every snap value
(including the { __error } establishment-failure convention).
Returns the unsubscribe function.
Parameters
| Parameter | Type |
|---|---|
sub | WorkerSubPayload |
onValue | (value: unknown) => void |
clientSessionId? | string |
Returns
(): void;
Returns
void
Type Aliases
BridgeMessage
type BridgeMessage =
| HelloFromClient
| HelloFromBridge
| AttachFromConsumer
| AttachAckFromBridge
| ToolCallRequest
| ToolCallResponse
| WorkerOpFrame
| WorkerResFrame
| WorkerSubFrame
| WorkerUnsubFrame
| WorkerSnapFrame
| WorkerClientDisconnectFrame
| WorkerClientInterruptedFrame
| ConsumerPresenceFrame
| RemoteSetLensFrame
| RemoteSetLensAckFrame
| WorkerEventFrame
| WorkerMessageFrame
| WorkerMessageResultFrame
| Ping
| Pong;
@pyric/cli/bridge — browser-side entry.
Resolved by the browser condition in package.json’s exports map.
Exports connectBridge, which the host app calls to register its
in-page sandbox with a running pyric bridge process. After
registration, MCP tool calls reaching the bridge are forwarded over
WebSocket and dispatched into the local sandbox.
The Node-side server entry lives in ./server.ts. Wire format
shared by both lives in ./protocol.ts.
ALSO reachable as @pyric/cli/bridge/client — an explicit, condition-free
subpath for browser apps whose TYPE resolution doesn’t apply the browser
condition (Pyric Studio’s moduleResolution: bundler tsconfig resolves the
./bridge subpath’s top-level types to the SERVER entry). Same file,
same surface.
ConnectedBridgeState
type ConnectedBridgeState =
| {
kind: "connecting";
}
| {
bridgeVersion: string;
kind: "connected";
}
| {
kind: "disconnected";
reason: string;
}
| {
attempt: number;
delayMs: number;
kind: "reconnecting";
}
| {
kind: "standby";
};
Type Declaration
{
kind: "connecting";
}
kind
kind: "connecting";
{
bridgeVersion: string;
kind: "connected";
}
bridgeVersion
bridgeVersion: string;
kind
kind: "connected";
{
kind: "disconnected";
reason: string;
}
kind
kind: "disconnected";
reason
reason: string;
{
attempt: number;
delayMs: number;
kind: "reconnecting";
}
attempt
attempt: number;
delayMs
delayMs: number;
kind
kind: "reconnecting";
{
kind: "standby";
}
kind
kind: "standby";
Another tab holds the peer slot (this connection was closed with the
REPLACED code). The client health-polls until the slot is vacant, then
reconnects. Distinct from reconnecting: the bridge is healthy and
deliberately serving a different tab.
Variables
FORBIDDEN_STORAGE_KEYS
const FORBIDDEN_STORAGE_KEYS: ReadonlySet<string>;
MAX_STORAGE_CUSTOM_METADATA_BYTES
const MAX_STORAGE_CUSTOM_METADATA_BYTES: number;
MAX_STORAGE_CUSTOM_METADATA_KEYS
const MAX_STORAGE_CUSTOM_METADATA_KEYS: 64 = 64;
MAX_STORAGE_LIST_ENTRIES
const MAX_STORAGE_LIST_ENTRIES: 250 = 250;
MAX_STORAGE_METADATA_STRING_CHARS
const MAX_STORAGE_METADATA_STRING_CHARS: 2048 = 2048;
MAX_STORAGE_OBJECT_PATH_CHARS
const MAX_STORAGE_OBJECT_PATH_CHARS: 1024 = 1024;
STORAGE_IMMUTABLE_STRING_FIELDS
const STORAGE_IMMUTABLE_STRING_FIELDS: readonly ["md5Hash", "generation", "metageneration", "timeCreated", "updated"];
STORAGE_NULLABLE_STRING_FIELDS
const STORAGE_NULLABLE_STRING_FIELDS: readonly ["contentType", "cacheControl", "contentDisposition", "contentEncoding", "contentLanguage"];
Functions
connectBridge()
function connectBridge(sandbox: LocalSandbox, opts?: ConnectBridgeOptions): ConnectedBridge;
Parameters
| Parameter | Type |
|---|---|
sandbox | LocalSandbox |
opts? | ConnectBridgeOptions |
Returns
copyStorageCustomMetadataRecord()
function copyStorageCustomMetadataRecord(raw: Readonly<Record<string, string>>): Record<string, string>;
Copies a customMetadata string map verbatim onto a fresh plain object while
omitting prototype-pollution keys (__proto__, constructor, prototype).
Parameters
| Parameter | Type |
|---|---|
raw | Readonly<Record<string, string>> |
Returns
Record<string, string>
isValidStorageBucketName()
function isValidStorageBucketName(bucket: string): boolean;
Parameters
| Parameter | Type |
|---|---|
bucket | string |
Returns
boolean
selectPreferredStorageBucket()
function selectPreferredStorageBucket(bucketNames: Iterable<string>, projectId: string): string;
Parameters
| Parameter | Type |
|---|---|
bucketNames | Iterable<string> |
projectId | string |
Returns
string
toPageOriginWsUrl()
function toPageOriginWsUrl(
raw: string,
loc: {
host: string;
href: string;
protocol: string;
},
routing?: "page-origin" | "bridge-port"): string;
Re-anchor a bridge WebSocket URL to the page’s own origin.
pyric sandbox / the vite plugin bake their OWN host into the bridge URL it
sends the page (e.g. ws://localhost:5173/__pyric/sandbox). But the page may
have been loaded over a different host (Tailscale, a LAN IP) or scheme
(https via tailscale serve, which then requires wss). Connecting to the
baked localhost from a remote tab dials the WRONG machine (the client’s own
localhost), so the WS fails.
Hosted callers select page-origin: retain the path and use the page’s full
public origin, including a reverse proxy’s port. The default bridge-port
preserves an explicit server port for existing two-server development setups. This also sidesteps the localhost / 127.0.0.1 /
::1 family ambiguity, because the browser dials the exact host it loaded from.
Pure (location is injected) so it is unit-testable. Returns raw unchanged if
it cannot be parsed.
Parameters
| Parameter | Type |
|---|---|
raw | string |
loc | { host: string; href: string; protocol: string; } |
loc.host | string |
loc.href? | string |
loc.protocol? | string |
routing? | "page-origin" | "bridge-port" |
Returns
string
validateObservedStorageDownloadUrl()
function validateObservedStorageDownloadUrl(raw: unknown): string;
Validates a Storage download URL against the Firebase/GCS/loopback origin
allowlist and length cap, returning the URL verbatim (including token=,
signed query parameters, and fragments).
Parameters
| Parameter | Type |
|---|---|
raw | unknown |
Returns
string
References
AuthLens
Re-exports AuthLens
DEFAULT_BRIDGE_PORT
Re-exports DEFAULT_BRIDGE_PORT
DEFAULT_SANDBOX_PATH
Re-exports DEFAULT_SANDBOX_PATH