---
url: https://jetpack-desktop.github.io/sdk/frontend/api-reference.md
description: >-
  Complete TypeScript API reference for @jetpack-desktop/client
  (JetPackAppClient, JetPackOpcodeMap typed contracts, ControlBar, LogTerminal)
  and low-level jetpack-wasm bindings.
---

# Frontend API Reference

This page documents both the high-level TypeScript SDK (`@jetpack-desktop/client`) and the bundled `wasm-bindgen` bindings (`jetpack-wasm`, re-exported via `@jetpack-desktop/client/wasm`).

```bash
npm install @jetpack-desktop/client
```

## High-Level SDK: `JetPackAppClient<TOpcodes>` (`@jetpack-desktop/client`)

Source: `web/packages/jetpack-client/src/client.ts` and `types.ts`. By default, `JetPackAppClient` loads the bundled `@jetpack-desktop/client/wasm` module with zero configuration (`wasmModule`, `wasmModulePath`, and `wasmBinaryOrUrl` remain available as optional overrides).

Pass a `JetPackOpcodeMap` interface generated by [`jetpack codegen`](/publishing/cli-tools#jetpack-codegen---worker-path---out-path---strict) (`new JetPackAppClient<JetPackOpcodeMap>()`) for compile-time validation of opcodes, metadata shapes, required `Uint8Array` payloads, response types, and `onStream()` listeners. Omitting the generic (`new JetPackAppClient()`) falls back to `DefaultOpcodeMap` and stays 100% backwards-compatible.

### Methods

| Method | Signature | Description |
| :--- | :--- | :--- |
| `connectAndEnsureApp` | `(options: ConnectAndEnsureAppOptions) => Promise<this>` | Initializes WASM, connects & pairs if needed, pulls from `SignedAppCatalog` if absent, launches or attaches to the worker, mounts `JetPackControlBar`, and mounts/subscribes `JetPackLogTerminal` when `developer_mode === true`. |
| `ensureWorkerRunning` | `() => Promise<void>` | Ensures the sandboxed worker is running, relaunching it via `launch_app` if it was stopped externally (for example via Control Center or manual Stop). Concurrent callers share a single launch operation. |
| `stopApp` | `() => Promise<unknown>` | Terminates the active worker via `terminate_app(appId)`, rejects in-flight requests with `NOT_CONNECTED`, and sets `JetPackControlBar` status to `'Stopped'`. |
| `request` | `<K extends keyof TOpcodes & string>(opcode: K, ...args: OpcodeRequestArgs<TOpcodes, K>) => Promise<WorkerResponse<OpcodeResponseFor<TOpcodes, K>>>` | Sends a correlated `HybridFrame` (`target_worker = appId`) with zero-copy `Uint8Array` transfer and resolves with `{ opcode, payload, correlationId }`. Automatically wakes a stopped worker via `ensureWorkerRunning()` (and retries once on a no-active-worker `system.error` race) while respecting `timeoutMs`. |
| `onStream` | `<K extends (keyof TOpcodes & string) \| '*'>(opcode: K, callback: StreamCallback<K extends '*' ? string : K, OpcodeStreamPayloadFor<TOpcodes, K>>) => () => void` | Subscribes to unsolicited or streaming worker frames matching `opcode` (or `'*'`). Returns an idempotent unsubscribe function. |
| `onWorkerStopped` | `(callback: (event: AppWorkerStoppedEvent) => void) => () => void` | Subscribes to daemon `"app.worker.stopped"` events (`'idle_timeout'`, `'terminated'`, `'process_exited'`). Returns an idempotent unsubscribe function. |
| `onWorkerStarted` | `(callback: (event: { app_id: string }) => void) => () => void` | Subscribes to worker wake/relaunch events emitted after `ensureWorkerRunning()` succeeds. Returns an idempotent unsubscribe function. |
| `subscribeLogs` | `(onEntry: (entry: LogEntry) => void) => Promise<LogsSubscribeOkResponse>` | Subscribes to live sanitized daemon & worker `logs.entry` frames (`logs.subscribe`). Rejects with `DEV_MODE_REQUIRED` when Developer Mode is off. |
| `unsubscribeLogs` | `() => Promise<void>` | Unsubscribes from live log streaming (`logs.unsubscribe`). Safe to call repeatedly. |
| `isConnected` | `() => boolean` | Returns `true` when an authenticated session is active and bound to an ensured `appId`. |
| `isWorkerRunning` | `() => boolean` | Returns `true` when the session is connected and the app worker is currently active. |
| `getLastStopReason` | `() => WorkerStopReason \| null` | Returns the most recent `WorkerStopReason` (`'idle_timeout'`, `'terminated'`, `'process_exited'`) if stopped, or `null` while running. |
| `getAppId` | `() => string \| null` | Returns the currently ensured `appId`, or `null` if disconnected. |
| `getEnvironment` | `() => JetPackEnvironmentName \| null` | Returns the resolved environment (`'dev'` or `'prod'`) while connected, or `null` before connect / after `close()`. |
| `getLanguage` | `() => string` | Returns the resolved lowercase primary BCP-47 UI language tag (`'en'` by default). |
| `onLanguageChanged` | `(callback: (language: string) => void) => () => void` | Registers a callback invoked when the resolved language updates during `connectAndEnsureApp()` (`?lang=` or `DaemonSettings.language`). Returns an unsubscribe function. |
| `getIdentity` | `() => WasmIdentityLike \| null` | Returns the active `WasmClientIdentity`, if initialized. |
| `getLastPairingUri` | `() => string \| null` | Returns the last generated `jetpack://pair?...` URI if auto-pairing ran. |
| `getRawClient` | `() => WasmClientLike \| null` | Exposes the underlying `JetPackWasmClient` for control-plane calls (`get_hardware_profile`, `reset_app_volumes`, `set_language`, etc.). |
| `getControlBar` | `() => JetPackControlBar \| null` | Returns the auto-mounted `JetPackControlBar` instance, or `null` when disabled (`controlBar: false`) or running headless. |
| `getLogTerminal` | `() => JetPackLogTerminal \| null` | Returns the auto-mounted Developer Mode `JetPackLogTerminal` instance, or `null` when Developer Mode is off, disabled (`logTerminal: false`), or running headless. |
| `close` | `() => void` | Closes the WebSocket, unsubscribes live log streams, clears stream/lifecycle listeners, rejects pending `request()` calls with `CLIENT_CLOSED`, hides `JetPackLogTerminal`, and marks `JetPackControlBar` as `'Stopped'`. |
| `destroy` | `() => void` | Calls `close()` and unmounts any auto-mounted `JetPackControlBar` and `JetPackLogTerminal`. |

### Environment Helpers & `ConnectAndEnsureAppOptions`

* **`deriveDevAppId(prodAppId: string): string`**: Derives a safe `com.dev.<slug>` development ID from a production reverse-DNS identifier (preserving identifiers already starting with `com.dev.`).
* **`resolveEnvironmentOptions(options: ConnectAndEnsureAppOptions): ResolvedEnvironmentOptions`**: Resolves `env` (`'dev' | 'prod' | 'auto'`) and `environments` overrides, deriving `com.dev.<slug>` when `env === 'dev'` and `dev.appId` is omitted. Legacy single-`appId` calls without `env` or `environments` resolve unchanged to `'prod'`.

```typescript
export type JetPackEnvironmentName = 'dev' | 'prod';
export type JetPackEnvironmentMode = JetPackEnvironmentName | 'auto';

export interface JetPackEnvironmentOptions {
  appId?: string;
  daemonPort?: number;
  wsUrl?: string;
  origin?: string;
  ociReference?: string;
  autoPair?: boolean;
  resetVolumes?: boolean;
  downloadUrl?: string;
  posterUrl?: string;
  installBanner?: boolean | JetPackInstallBannerOptions;
  controlBar?: boolean | JetPackControlBarOptions;
  logTerminal?: boolean | JetPackLogTerminalOptions;
}

export interface JetPackEnvironmentsConfig {
  dev?: JetPackEnvironmentOptions;
  prod?: JetPackEnvironmentOptions;
}

export interface ConnectAndEnsureAppOptions {
  appId?: string;                     // Required unless provided by environments[resolvedEnv]
  env?: JetPackEnvironmentMode;       // 'dev' | 'prod' | 'auto' (legacy { appId } defaults to 'prod')
  environments?: JetPackEnvironmentsConfig;
  daemonPort?: number;                // Default: 9470
  wsUrl?: string;                     // Overrides ws://127.0.0.1:<daemonPort>
  origin?: string;                    // Overrides window.location.origin
  ociReference?: string;              // Explicit OCI ref (for local/custom testing)
  autoPair?: boolean;                 // Default: true
  resetVolumes?: boolean;             // Default: false
  pairingPollIntervalMs?: number;     // Default: 1500
  pairingTimeoutMs?: number;          // Default: 60000
  disableAutoDeepLink?: boolean;      // Default: false
  downloadUrl?: string;               // Deprecated, ignored: the SDK always uses DEFAULT_JETPACK_DOWNLOAD_URL
  posterUrl?: string;                 // Safe poster URL shown in the blocking install-gate overlay
  installBanner?: boolean | JetPackInstallBannerOptions; // Default: enabled on DAEMON_NOT_RUNNING
  autoReconnectOnDaemonStart?: boolean; // Background /health polling in DOM (default: true)
  daemonPollIntervalMs?: number;      // Interval in ms between /health polls (default: 2000)
  onDaemonReconnect?: (client: JetPackAppClient<any>) => void | Promise<void>;
  healthProbeTimeoutMs?: number;      // /health pre-flight timeout in ms (default: 2000; 0 skips probe)
  fetchFn?: typeof fetch;             // Custom fetch implementation for /health probe (testing/SSR)
  onProgress?: (progress: AppPullProgress) => void;
  onPairingUri?: (uri: string) => void;
  wasmModule?: WasmBindingsAdapter;
  wasmModulePath?: string;
  wasmBinaryOrUrl?: unknown;
  controlBar?: boolean | JetPackControlBarOptions; // Default: auto-mounted in DOM
  logTerminal?: boolean | JetPackLogTerminalOptions; // Auto-mounted only if developer_mode === true
}
```

### `JetPackControlBar`, `JetPackInstallBannerOptions` & `JetPackControlBarOptions`

Source: `web/packages/jetpack-client/src/control-bar.ts`. Uses `attachShadow({ mode: 'open' })` for CSS isolation, enforces a **single active instance per `document`** (unmounting any prior bar via `Symbol.for('jetpack.controlBar.activeByDocument')` and firing `onSuperseded`), displays a **`DEV`** badge beside `appName` when `env === 'dev'`, lazily mounts the blocking install-gate overlay (`#jetpack-install-banner-host`, `z-index: 2147483645`) strictly on `'Error'` with a sanitized `https://` `downloadUrl`, and safely no-ops in headless/SSR environments where `document` is undefined.

```typescript
export type ControlBarWorkerStatus = 'Connecting' | 'Running' | 'Stopped' | 'Error';
export type WorkerStopReason = 'idle_timeout' | 'terminated' | 'process_exited';

export interface AppWorkerStoppedEvent {
  app_id: string;
  job_id: string;
  reason: WorkerStopReason;
}

export interface JetPackInstallBannerOptions {
  posterUrl?: string; // Safe https://, loopback http://, or '/'-relative URL
  message?: string;   // Custom prompt shown below the poster
}

export interface JetPackControlBarOptions {
  appId?: string;
  appName?: string;
  env?: JetPackEnvironmentName;        // Shows a visible DEV badge when 'dev'
  controlCenterUrl?: string;           // Default: http://127.0.0.1:<daemonPort>/#apps
  downloadUrl?: string;                // Deprecated, ignored: Error state always links to DEFAULT_JETPACK_DOWNLOAD_URL
  posterUrl?: string;                  // Safe poster URL for blocking install-gate overlay
  installBanner?: boolean | JetPackInstallBannerOptions; // Set false to disable overlay
  logoUrl?: string;                    // Overrides built-in JetPack SVG icon
  mountTarget?: HTMLElement | null;    // Default: document.body; pass null to defer mount()
  initialStatus?: ControlBarWorkerStatus; // Default: 'Connecting'
  onBeforeStop?: () => Promise<boolean> | boolean;
  warnOnUnsavedWork?: boolean | (() => boolean);
  stopConfirmTitle?: string;
  stopConfirmMessage?: string;
  onStop?: () => Promise<unknown>;     // Wired automatically to client.stopApp()
  onLaunch?: () => Promise<unknown>;   // Wired automatically to ensureWorkerRunning() or connectAndEnsureApp() reconnect
  onRelaunch?: () => Promise<unknown>; // Backwards-compatible alias for onLaunch
  onAfterStop?: () => Promise<void> | void;
  onStopError?: (error: Error) => void;
  language?: string;                   // Active UI language tag ('en', 'uk', etc.). Defaults to 'en'.
  onSuperseded?: () => void;           // Invoked when a newer bar replaces this one
}
```

The single context-aware primary action button in `JetPackControlBar` adapts automatically to worker status:

* **`'Running'`**: Renders **`Stop`** (`Зупинити`), opening the optional confirmation modal (`warnOnUnsavedWork` / `onBeforeStop`) and terminating the worker via `onStop()`.
* **`'Stopped'`**: Renders enabled **`Launch`** (`Запустити`), calling `onLaunch()` (which uses `ensureWorkerRunning()` when the WebSocket is still open, or transparently calls `connectAndEnsureApp()` with sanitized stored connection options when disconnected or after `client.close()`).
* **`'Connecting'` / `'Error'`**: Renders disabled **`Launch`** (`Запустити`) until connected or recovered.

| Method | Signature | Description |
| :--- | :--- | :--- |
| `mount` | `(target?: HTMLElement \| null) => boolean` | Inserts `#jetpack-control-bar-host` at the top of `target` (or `document.body`), superseding and removing any previous `JetPackControlBar` or stale control-bar/install-banner hosts in the same `document`. Returns `false` if headless. |
| `unmount` | `() => void` | Removes both `#jetpack-control-bar-host` and `#jetpack-install-banner-host`, detaches layout observers, and clears modal/keyboard listeners. |
| `updateOptions` | `(partial: Partial<JetPackControlBarOptions>) => void` | Updates bar and install-banner options live and refreshes rendered text/links/poster. |
| `setLanguage` | `(language?: string \| null) => void` | Switches Shadow-DOM bar, modal, and install-gate strings live between `'en'` and `'uk'` (falling back to `'en'`). |
| `setInstallBannerOptions` | `(installBanner: boolean \| JetPackInstallBannerOptions) => void` | Enables, disables (`false`), or updates the blocking install-gate overlay (`posterUrl` / `message`). |
| `setStatus` | `(status: ControlBarWorkerStatus, detail?: string, options?: { downloadUrl?: string }) => void` | Updates the live status pill, optional `'Stopped'` status note or `'Error'` detail tooltip, switches the unified action button between **`Launch`** and **`Stop`**, renders the `"Download JetPack"` link (always the official `DEFAULT_JETPACK_DOWNLOAD_URL`; custom `downloadUrl` values are ignored) when in `'Error'` state, and attaches/detaches the blocking install-gate overlay with a curved dashed SVG arrow pointing to `"Download JetPack"`. |
| `getStatus` | `() => ControlBarWorkerStatus` | Returns the current status (`'Connecting'`, `'Running'`, `'Stopped'`, or `'Error'`). |
| `isInstallBannerVisible` | `() => boolean` | Returns `true` when the blocking install-gate overlay is currently visible (`status === 'Error'` and `installBanner !== false`). |
| `setAppName` / `setControlCenterUrl` | `(value: string) => void` | Updates the displayed app name or `"Control Center"` destination URL. |
| `triggerLaunch` | `() => Promise<boolean>` | Invokes `onLaunch()` (or fallback `onRelaunch()`) when `status === 'Stopped'` and transitions the bar back to `'Running'` on success. |
| `triggerRelaunch` | `() => Promise<boolean>` | Backwards-compatible alias forwarding directly to `triggerLaunch()`. |
| `triggerStop` | `() => Promise<boolean>` | Opens the Shadow-DOM confirmation modal when `warnOnUnsavedWork` evaluates to `true` or `onBeforeStop` is set (unless `warnOnUnsavedWork === false`); otherwise stops directly. |
| `confirmStopModal` / `cancelStopModal` | `() => Promise<boolean>` / `() => void` | Confirms (running `onBeforeStop` -> `onStop` -> `onAfterStop`) or dismisses the modal. |
| `isModalOpen` | `() => boolean` | Returns `true` when the stop confirmation modal is currently visible. |
| `getHostElement` / `getShadowRoot` | `() => HTMLElement \| null` / `() => ShadowRoot \| null` | Exposes the top-bar host element and open `ShadowRoot`. |
| `getInstallBannerHostElement` / `getInstallBannerShadowRoot` | `() => HTMLElement \| null` / `() => ShadowRoot \| null` | Exposes the install-gate overlay host element (`#jetpack-install-banner-host`) and its open `ShadowRoot`. |

### `JetPackLogTerminal` & Log Streaming Types

Source: `web/packages/jetpack-client/src/log-terminal.ts` and `types.ts`. Uses `attachShadow({ mode: 'open' })` for CSS isolation, enforces a **single active terminal per `document`** via `Symbol.for('jetpack.logTerminal.activeByDocument')`, and renders strictly when `developerMode` is `true` (collapsing into a thin bottom bar with an unread `WARN`/`ERROR` counter by default).

```typescript
export type LogLevel = 'INFO' | 'WARN' | 'ERROR' | 'DEBUG' | 'TRACE' | string;
export type LogSourceFilter = 'all' | 'daemon' | 'worker';

export interface LogEntry {
  timestamp_ms: number;
  level: LogLevel;
  source: string; // "daemon" or app_id (e.g. "io.jetpack.media-converter")
  message: string;
}

export interface LogsSubscribeOkResponse {
  buffered_count: number;
}

export interface JetPackLogTerminalOptions {
  mountTarget?: HTMLElement | null; // Default: document.body; pass null to defer mount()
  developerMode?: boolean;          // Default: false (hidden unless true)
  maxEntries?: number;              // Default: 1000 buffered rows
  title?: string;                   // Default: 'JetPack Live Logs'
  language?: string;                // Active UI language tag ('en', 'uk', etc.). Defaults to 'en'.
  expanded?: boolean;               // Default: false (thin collapsed header bar)
  sourceFilter?: LogSourceFilter;   // Default: 'all'
  copyToClipboard?: (text: string) => Promise<void>;
  onCopySuccess?: (text: string) => void;
  onCopyError?: (error: Error) => void;
}
```

| Method | Signature | Description |
| :--- | :--- | :--- |
| `mount` / `unmount` | `(target?: HTMLElement \| null) => boolean` / `() => void` | Attaches or removes `#jetpack-log-terminal-host` on `target` (`document.body` by default). |
| `setDeveloperMode` / `isDeveloperMode` | `(enabled: boolean) => void` / `() => boolean` | Shows or hides the bottom drawer strictly according to `developerMode` (collapses when disabled). |
| `setLanguage` | `(language?: string \| null) => void` | Switches Shadow-DOM log terminal buttons, source filters, and empty-state labels live (`'en'` fallback). |
| `setExpanded` / `toggle` / `isExpanded` | `(expanded: boolean) => void` / `() => void` / `() => boolean` | Expands or collapses the drawer body, resetting unread `WARN`/`ERROR` count and auto-scrolling on expand. |
| `setSourceFilter` / `getSourceFilter` | `(filter: LogSourceFilter) => void` / `() => LogSourceFilter` | Filters displayed rows between `'all'`, `'daemon'`, and `'worker'`. |
| `appendEntry` / `clear` | `(entry: LogEntry) => void` / `() => void` | Appends a log row (incrementing unread `WARN`/`ERROR` count while collapsed) or clears buffered logs. |
| `getUnreadWarningErrorCount` / `getEntries` / `getVisibleEntries` | `() => number` / `() => LogEntry[]` / `() => LogEntry[]` | Inspects unread alert count, full buffer, or currently filtered log entries. |
| `formatAllLogsText` / `copyLogs` | `() => string` / `() => Promise<boolean>` | Formats all buffered logs and copies them to clipboard, showing localized `"Copied!"` confirmation. |
| `updateOptions` | `(partial: Partial<JetPackLogTerminalOptions>) => void` | Updates options live without clearing buffered entries. |
| `getHostElement` / `getShadowRoot` | `() => HTMLElement \| null` / `() => ShadowRoot \| null` | Exposes the mounted host element and open `ShadowRoot`. |

### Zero-Dependency i18n Helpers (`createI18n`, `resolveLanguage`, `normalizeLanguageTag`)

Source: `web/packages/jetpack-client/src/i18n.ts`. Provides type-safe, zero-dependency localization with English (`'en'`) as canonical base and automatic per-key / per-locale fallback.

```typescript
export function normalizeLanguageTag(tag?: string | null): string | null;

export function resolveLanguage(options?: {
  url?: string | null;
  search?: string | null;
  daemonLanguage?: string | null;
  preferredLanguage?: string | null;
  supportedLocales?: readonly string[];
  fallbackLocale?: string;
}): string;

export function createI18n<TDict extends Record<string, string>>(options: {
  catalogs: { en: TDict } & Record<string, Partial<TDict> | TDict>;
  defaultLocale?: string;
  initialLocale?: string | null;
}): JetPackI18n<TDict>;
```

* `normalizeLanguageTag(tag)` canonicalizes safe BCP-47 tags (e.g. `'uk-UA'` → `'uk'`) and returns `null` for malformed, overly long, or unsafe inputs.
* `resolveLanguage(options)` evaluates `preferredLanguage` → `?lang=` → `daemonLanguage` → `'en'` and falls back to `'en'` whenever an app does not list the resolved locale in `supportedLocales`.
* `createI18n(options)` returns `{ locale, t(key, params?), getLocale(), setLocale(tag), getSupportedLocales(), onChange(listener) }` with per-key `'en'` fallback and `{placeholder}` interpolation.

### `JetPackOpcodeMap`, `WorkerResponse` & `StreamCallback`

```typescript
export interface JetPackOpcodeEntry<
  TMeta = Record<string, unknown> | null,
  TResponse = unknown,
  TBinary extends boolean = boolean,
  TStream extends boolean = boolean,
> {
  meta: TMeta;
  response: TResponse;
  binary?: TBinary;
  stream?: TStream;
}

export type JetPackOpcodeMap = Record<string, JetPackOpcodeEntry<any, any, boolean, boolean>>;

export interface DefaultOpcodeMap {
  [opcode: string]: JetPackOpcodeEntry<Record<string, unknown> | null, unknown, boolean, boolean>;
}

export interface WorkerResponse<TResponse = unknown> {
  opcode: string;
  payload: Uint8Array;
  correlationId: number;
  readonly __responseType?: TResponse;
}

export interface StreamFrameContext<TOpcode extends string = string, TPayload = unknown> {
  opcode: TOpcode;
  correlationId: number | null;
  readonly __payloadType?: TPayload;
}

export type StreamCallback<TOpcode extends string = string, TPayload = unknown> = (
  payload: Uint8Array,
  context: StreamFrameContext<TOpcode, TPayload>
) => void;
```

### `JetPackClientError` & Codes

`JetPackClientError` exposes `readonly code: JetPackClientErrorCode` and `readonly downloadUrl?: string` (populated on `DAEMON_NOT_RUNNING`, always equal to `DEFAULT_JETPACK_DOWNLOAD_URL = 'https://github.com/jetpack-desktop/releases/releases/latest'`).

| Code | Cause |
| :--- | :--- |
| `DAEMON_NOT_RUNNING` | `GET /health` timed out, failed to connect, or returned non-OK before pairing/WebSocket handshake. `err.downloadUrl` is always the official JetPack releases link. |
| `NOT_CONNECTED` | `request()` or `stopApp()` called before `connectAndEnsureApp()` succeeded. |
| `CLIENT_CLOSED` | `request()` or `stopApp()` called after `close()`, or `close()` invoked while a request was in flight. |
| `PAIRING_TIMEOUT` | User did not approve `jetpack://pair` within `pairingTimeoutMs`. |
| `APP_NOT_IN_CATALOG` | `appId` is neither installed locally nor present in `SignedAppCatalog` (and `ociReference` was omitted). |
| `REQUEST_TIMEOUT` | Worker did not reply within `RequestOptions.timeoutMs`. |
| `WASM_LOAD_FAILED` | Failed to dynamically import `jetpack-wasm` bindings. |
| `INVALID_OPTIONS` | Missing or empty `appId` passed to `connectAndEnsureApp()`. |

***

## Low-Level WASM Bindings (`@jetpack-desktop/client/wasm` / `jetpack-wasm`)

Source: `crates/jetpack-wasm/src/identity.rs` and `client.rs` (bundled inside `@jetpack-desktop/client` under `@jetpack-desktop/client/wasm`).

```typescript
import initWasm, { WasmClientIdentity, JetPackWasmClient } from '@jetpack-desktop/client/wasm';

await initWasm();
```

### `WasmClientIdentity`

* `new WasmClientIdentity()` (`load_or_generate`): Loads or generates `client_id` (`UUIDv4`) + `Ed25519` / `X25519` 32-byte seeds in `localStorage` (`jetpack_client_id`, `jetpack_ed25519_seed`, `jetpack_x25519_seed`), falling back to ephemeral in-memory keys if storage is blocked.
* `WasmClientIdentity.generate_new_ephemeral()`: Creates a fresh in-memory identity without touching `localStorage`.
* `WasmClientIdentity.clear_storage()`: Removes persisted identity keys from `localStorage`.
* `identity.client_id`: Getter returning the `UUIDv4` string.
* `identity.public_key_bundle_base64()`: Returns the URL-safe Base64 64-byte (`Ed25519` + `X25519`) public key bundle.
* `identity.ed25519_pubkey_hex()` / `identity.x25519_pubkey_hex()`: Returns 32-byte hex public keys.
* `identity.generate_pairing_uri(origin)`: Validates and normalizes `origin` and returns `jetpack://pair?client_id=...&pubkey=...&origin=...`.

### Pre-Install Size Estimation Types

```typescript
export interface CatalogAppModelEntry {
  id: string;
  name: string;
  size_bytes: number;
  approximate?: boolean;
  source?: string | null;
  trigger?: string | null;
}

export interface CatalogAppSizeEstimate {
  app_id: string;
  install_download_bytes: number;
  install_known: boolean;
  install_size_approximate: boolean;
  cached_reused_bytes: number;
  models_total_bytes: number;
  models: CatalogAppModelEntry[];
}

export interface CatalogEstimateSizesResponse {
  estimates: CatalogAppSizeEstimate[];
}
```

### `JetPackWasmClient`

| Method | Return Type | Description |
| :--- | :--- | :--- |
| `JetPackWasmClient.connect(wsUrl, identity, origin?)` | `Promise<JetPackWasmClient>` | Opens binary WebSocket (`arraybuffer`) and executes `ClientHello` / `ServerHello` handshake. |
| `is_connected()` | `boolean` | Returns `true` when in `Established` encrypted session state. |
| `get_hardware_profile()` | `Promise<HardwareProfile>` | Sends `hardware.get_profile` and resolves with CPU, RAM/unified memory, and GPU device details. |
| `get_catalog()` | `Promise<CatalogAppEntry[]>` | Fetches verified entries from the active `SignedAppCatalog` (refreshed via `catalog_url` with cached/embedded fallback), including `coming_soon?: boolean`, `launch_url?: string \| null`, `poster_url?: string \| null`, optional `install_size_bytes`, `platform_install_sizes`, `install_size_approximate`, and `models`. |
| `estimate_catalog_sizes(appIds?)` | `Promise<CatalogEstimateSizesResponse>` | Sends `catalog.estimate_sizes` (optionally scoped to `string[]` `appIds`) and returns host-aware pre-install remaining download bytes (`install_download_bytes`, deducting cached CAS blobs, shared runtimes, `uv`, and Python artifacts in `cached_reused_bytes`) separated from lazy runtime AI model totals (`models_total_bytes`, `models[]`). |
| `list_apps()` | `Promise<AppInfo[]>` | Lists installed apps with `status`, `is_verified`, `has_ui`, and sanitized `volumes` (`folder_name`, `is_configured`—never host paths). |
| `pull_app(imageRef, onProgress?, appId?)` | `Promise<AppPullOkResponse>` | Pulls a catalog-verified OCI app and streams `app.pull.progress` events (`percent` may be `number \| null`). |
| `launch_app(appId, resetVolumes?, onProgress?)` | `Promise<AppLaunchOkResponse>` | Starts sandboxed worker (`resetVolumes` forces fresh `rfd` folder prompts). Optional `onProgress` receives `app.launch.progress` events (`runtime_download`, `runtime_extract`, `uv_bootstrap`, `python_standalone`, `uv_sync`, `sandbox_launch`) while remaining compatible with 1- and 2-argument calls. |
| `reset_app_volumes(appId, volumeName?)` | `Promise<AppVolumesResetOkResponse>` | Clears persisted `authorized_volumes` entries in `paired_clients.db`. |
| `clear_app_cache(appId)` | `Promise<AppClearCacheOkResponse>` | Loopback Control-Center-only (`127.0.0.1` / `localhost`, rejecting non-Control-Center origins with `APP_MANAGEMENT_ORIGIN_FORBIDDEN` and active workers with `APP_IS_RUNNING`). Removes `<appdata_root>/<app_id>`, recreates an empty `0o700` directory on Unix, and clears `authorized_volumes` rows without touching mounted host folders or application bundles. |
| `uninstall_app(appId, removeCache?)` | `Promise<AppUninstallOkResponse>` | Loopback Control-Center-only (`APP_MANAGEMENT_ORIGIN_FORBIDDEN` / `APP_IS_RUNNING`). Removes all installed bundle directories for `appId` under `<apps_dir>`, and when `removeCache` is `true`, also removes `<appdata_root>/<app_id>` and clears `authorized_volumes` rows. Never deletes mounted host folders, `.core-apps-seeded`, shared blobs, or shared runtimes. |
| `terminate_app(appIdOrJobId)` | `Promise<AppTerminateOkResponse>` | Terminates a running job and its OS sandbox. |
| `list_paired_clients()` | `Promise<PairedClientSummary[]>` | Lists paired browser clients from `paired_clients.db`. |
| `revoke_client(clientId?, origin?)` | `Promise<ClientRevokeOkResponse>` | Revokes paired client access. |
| `get_settings()` / `set_developer_mode(enabled)` / `set_open_in_app_window(enabled)` / `set_open_dashboard_on_startup(enabled)` / `set_language(language)` | `Promise<DaemonSettings>` | Reads or partially updates daemon UI settings (`developer_mode`, `open_in_app_window`, `open_dashboard_on_startup`, `language`, `daemon_version`, `appdata_dir`). `set_language` validates supported languages (`'en'`, `'uk'`) from loopback origins and triggers live OS tray refresh. |
| `pick_appdata_dir()` / `reset_appdata_dir()` | `Promise<DaemonSettings>` | Loopback-only (`127.0.0.1` / `localhost`). `pick_appdata_dir()` opens the daemon's main-thread OS folder picker (`rfd`) to choose a custom `appdata_dir` root (rejects with `APPDATA_PICKER_CANCELLED` on cancel); `reset_appdata_dir()` restores `<root>/appdata`. |
| `subscribe_logs(onEntryCallback)` | `Promise<LogsSubscribeOkResponse>` | Sends `logs.subscribe` and streams sanitized `logs.entry` (`{ timestamp_ms, level, source, message }`) frames; rejects with `DEV_MODE_REQUIRED` if Developer Mode is off. |
| `unsubscribe_logs()` | `Promise<LogsUnsubscribeOkResponse>` | Sends `logs.unsubscribe` and clears the active log callback. |
| `open_url(url)` | `Promise<UiOpenUrlOkResponse>` | Loopback-only caller (`127.0.0.1` / `localhost`). Opens either a validated loopback HTTP URL or an exact `launch_url` declared in the active Ed25519-verified `SignedAppCatalog` (with origin in `allowed_origins`) in a dedicated OS-native `wry` WebView window (`WKWebView` with `NSAllowsLocalNetworking` / `WebView2` / `WebKitGTK`, persisted under `<root>/webview-data` and intercepting `jetpack://pair` deep links) when `open_in_app_window` is `true` (with headless default-browser fallback) or a browser tab when `false`, resolving to `{ opened_in_app_window }`. |
| `export_diagnostics()` | `Promise<DiagnosticsExportResult>` | Requests `diagnostics.export` and returns `{ filename, generated_at_unix, log_tail_bytes, log_truncated, redactions_applied, zip_bytes }` where `zip_bytes` is a `Uint8Array` sliced from the binary frame. |
| `send_diagnostics()` | `Promise<DiagnosticsSendOkResponse>` | Requests `diagnostics.send` to transmit a sanitized diagnostic JSON report to `[diagnostics].report_url` (rejects with `[DIAGNOSTICS_DISABLED]` when `report_url` is unset). |
| `check_for_updates()` | `Promise<UpdateStatusResponse>` | Sends `update.check` and resolves with `{ current_version, latest_version, update_available, release_url, asset_name, checked_at_secs, error }`. |
| `apply_update(onProgress?, expectedVersion?)` | `Promise<UpdateRestartingResponse>` | Control-Center-only (`127.0.0.1` own origin). Sends `update.apply`, streams `UpdateProgressFrame` (`checking`, `downloading`, `verifying`, `extracting`, `installing`, `restarting`, `percent`, `bytes_downloaded`, `total_bytes`, `message`) to `onProgress`, and resolves with `{ target_version, restart_delay_ms }` before daemon restart. |
| `send_worker_frame(targetWorker, opcode, metaJs, rawPayload)` | `void` | Fire-and-forget encrypted `HybridFrame` dispatch to a worker. |
| `request_worker_frame(targetWorker, opcode, metaJs, rawPayload)` | `Promise<WorkerResponse>` | Correlated worker request matching `correlation_id`. |
| `on_worker_frame(callback)` | `void` | Registers `(opcode, payloadUint8Array, correlationId)` listener for unsolicited/stream frames. |
| `on_worker_stopped(callback)` | `void` | Registers `(event)` listener invoked when the daemon pushes `"app.worker.stopped"` (`{ app_id, job_id, reason }`). |
| `close()` | `void` | Closes WebSocket, clears log/worker listeners, and fails pending promises. |
