Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(fleet): publish browser and Node SDK with Computer lifecycle (#3408)

r33drichardsf7f5bbb41277
diff --git a/.github/workflows/ci-ts-fleet.yml b/.github/workflows/ci-ts-fleet.yml
new file mode 100644
index 0000000000..b885bc9535
--- /dev/null
+++ b/.github/workflows/ci-ts-fleet.yml
@@ -0,0 +1,18 @@
+name: "CI: @trycua/fleet"
+
+on:
+ pull_request:
+ paths:
+ - "libs/typescript/fleet/**"
+ - "libs/typescript/pnpm-lock.yaml"
+ - "libs/typescript/pnpm-workspace.yaml"
+ - ".github/workflows/ci-ts-fleet.yml"
+ - ".github/workflows/ts-reusable-build.yml"
+
+jobs:
+ build:
+ uses: ./.github/workflows/ts-reusable-build.yml
+ with:
+ package_name: "fleet"
+ package_dir: "libs/typescript/fleet"
+ package_manager: "pnpm"
diff --git a/docs/content/docs/how-to-guides/sandbox/create-pool-with-typescript.mdx b/docs/content/docs/how-to-guides/sandbox/create-pool-with-typescript.mdx
new file mode 100644
index 0000000000..f0c0557a45
--- /dev/null
+++ b/docs/content/docs/how-to-guides/sandbox/create-pool-with-typescript.mdx
@@ -0,0 +1,389 @@
+---
+title: Create a sandbox pool with TypeScript
+description: Create a reusable Fleet pool and capture a sandbox screenshot from browser or Node.js TypeScript.
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+Use `@trycua/fleet` to create a reusable sandbox pool from TypeScript. This
+guide creates a one-replica Linux pool, claims a sandbox, captures a screenshot,
+and releases the claim while leaving the pool warm.
+
+The package provides separate runtime entry points:
+
+- `@trycua/fleet/browser` loads the Fleet WebAssembly module in a browser.
+- `@trycua/fleet/node` loads the same WebAssembly module from disk and provides
+ a fetch-based HTTP transport.
+
+## Prerequisites
+
+- Node.js 20 or newer.
+- A run.cua.ai access token with permission to manage sandbox pools.
+- A globally unique, lowercase DNS-label pool name.
+
+This guide uses the public Linux computer-server image:
+
+```text
+public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04@sha256:82702ebdd32d1f8fc05f2ea409a7c67d0ba9f8f8e4e9f1a89ce40989d5f4475d
+```
+
+<Callout type="warn">
+ Browser code can read every `VITE_*` value bundled into the application. Use the browser example
+ only in a trusted local or internal application with a short-lived, narrowly scoped token. Keep
+ long-lived credentials in Node.js or exchange them for a short-lived token on your backend.
+</Callout>
+
+## Choose a runtime
+
+<Tabs groupId="fleet-typescript-runtime" persist items={['Node.js', 'Browser']}>
+ <Tab value="Node.js">
+
+Install the Fleet lifecycle SDK and a TypeScript runner:
+
+```bash
+npm install @trycua/fleet
+npm install --save-dev tsx typescript
+```
+
+Set the token and a unique pool name:
+
+```bash
+export CUA_FLEET_ACCESS_TOKEN="<your-access-token>"
+export CUA_POOL_NAME="my-team-js-pool"
+```
+
+Save this script as `create-pool.ts`:
+
+```ts title="create-pool.ts"
+import { writeFile } from 'node:fs/promises';
+import {
+ CreateClaimRequestBuilder,
+ CreatePoolRequestBuilder,
+ CreateTemplateRequestBuilder,
+ CyclopsTokenProviderConfigurationBuilder,
+ OsGymSandboxTemplateSpecBuilder,
+ OsGymSandboxWarmPoolSpecBuilder,
+ SandboxServiceBuilder,
+ SandboxTemplateRefBuilder,
+ VmTemplateBuilder,
+ createFleetClient,
+ type Claim,
+} from '@trycua/fleet/node';
+
+const IMAGE =
+ 'public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04' +
+ '@sha256:82702ebdd32d1f8fc05f2ea409a7c67d0ba9f8f8e4e9f1a89ce40989d5f4475d';
+const BASE_URL = process.env.CUA_FLEET_BASE_URL ?? 'https://run.cua.ai';
+const ACCESS_TOKEN = requiredEnv('CUA_FLEET_ACCESS_TOKEN');
+const POOL_NAME = requiredEnv('CUA_POOL_NAME');
+const TEMPLATE_NAME = `${POOL_NAME}-template`;
+
+function requiredEnv(name: string): string {
+ const value = process.env[name];
+ if (!value) throw new Error(`Missing environment variable: ${name}`);
+ return value;
+}
+
+function screenshotBase64(responseBody: ArrayBuffer): string {
+ const text = new TextDecoder().decode(responseBody);
+ const dataLine = text.split('\n').find((line) => line.startsWith('data: '));
+ if (!dataLine) throw new Error(`No screenshot data frame: ${text.slice(0, 200)}`);
+
+ const payload = JSON.parse(dataLine.slice(6));
+ if (!payload.success) throw new Error(payload.error ?? 'Screenshot failed');
+
+ const encoded = payload.image_data ?? payload.result?.image_data;
+ if (typeof encoded !== 'string') throw new Error('Screenshot response has no image data');
+ return encoded;
+}
+
+const configuration = new CyclopsTokenProviderConfigurationBuilder()
+ .baseUrl(BASE_URL)
+ .poolPollIntervalMs(5_000n)
+ .poolPollLimit(120)
+ .claimPollIntervalMs(5_000n)
+ .claimPollLimit(120)
+ .build();
+const client = await createFleetClient(configuration, ACCESS_TOKEN);
+
+let claim: Claim | undefined;
+try {
+ const service = new SandboxServiceBuilder().name('server').targetPort(8000).build();
+ const vm = new VmTemplateBuilder()
+ .containerDiskImage(IMAGE)
+ .cpuCores(4)
+ .memory('4Gi')
+ .services([service])
+ .build();
+ const templateSpec = new OsGymSandboxTemplateSpecBuilder().vmTemplate(vm).build();
+ const templateRef = new SandboxTemplateRefBuilder().name(TEMPLATE_NAME).build();
+ const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()
+ .replicas(1)
+ .sandboxTemplateRef(templateRef)
+ .build();
+
+ const pool = await client.createPool(
+ new CreatePoolRequestBuilder().namespace(POOL_NAME).spec(poolSpec).build(),
+ );
+ const template = await client.createTemplate(
+ new CreateTemplateRequestBuilder()
+ .namespace(POOL_NAME)
+ .name(TEMPLATE_NAME)
+ .spec(templateSpec)
+ .build(),
+ );
+
+ console.log(`Created pool ${pool.metadata.name}`);
+ console.log(`Created template ${template.metadata.name}`);
+
+ claim = await client.createClaim(
+ new CreateClaimRequestBuilder().pool(pool).build(),
+ );
+ const sandbox = await client.waitClaim(claim);
+
+ const requestBody = await new Blob([
+ JSON.stringify({ command: 'screenshot' }),
+ ]).arrayBuffer();
+ const response = await client.serviceRequest(sandbox, 'server', '/cmd', {
+ method: 'POST',
+ url: 'https://service.invalid/cmd',
+ headers: [{ name: 'content-type', value: 'application/json' }],
+ body: requestBody,
+ timeoutSecs: 60n,
+ });
+ if (response.status < 200 || response.status >= 300) {
+ throw new Error(`Screenshot request failed with HTTP ${response.status}`);
+ }
+
+ await writeFile('sandbox.png', Buffer.from(screenshotBase64(response.body), 'base64'));
+ console.log('Wrote sandbox.png');
+} finally {
+ try {
+ // Release the claim but leave the reusable pool warm.
+ if (claim) await client.deleteClaim(claim);
+ } finally {
+ client.uniffiDestroy();
+ }
+}
+```
+
+Run it:
+
+```bash
+npx tsx create-pool.ts
+```
+
+The script writes `sandbox.png` in the current directory. The Fleet client
+creates and waits for the claim, routes `POST /cmd` through the authenticated
+`server` service proxy, and deletes the claim before closing.
+
+ </Tab>
+ <Tab value="Browser">
+
+Create a Vite TypeScript project and install the browser SDK:
+
+```bash
+npm create vite@latest fleet-browser -- --template vanilla-ts
+cd fleet-browser
+npm install
+npm install @trycua/fleet
+```
+
+Create `.env.local` with a short-lived access token and a unique pool name:
+
+```bash title=".env.local"
+VITE_CUA_FLEET_ACCESS_TOKEN=<your-short-lived-access-token>
+VITE_CUA_POOL_NAME=my-team-browser-pool
+```
+
+Replace `src/main.ts` with the following code:
+
+```ts title="src/main.ts"
+import {
+ CreateClaimRequestBuilder,
+ CreatePoolRequestBuilder,
+ CreateTemplateRequestBuilder,
+ CyclopsClient,
+ CyclopsTokenProviderConfigurationBuilder,
+ OsGymSandboxTemplateSpecBuilder,
+ OsGymSandboxWarmPoolSpecBuilder,
+ SandboxServiceBuilder,
+ SandboxTemplateRefBuilder,
+ VmTemplateBuilder,
+ uniffiInitAsync,
+ type Claim,
+} from '@trycua/fleet/browser';
+
+const IMAGE =
+ 'public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04' +
+ '@sha256:82702ebdd32d1f8fc05f2ea409a7c67d0ba9f8f8e4e9f1a89ce40989d5f4475d';
+const BASE_URL = import.meta.env.VITE_CUA_FLEET_BASE_URL ?? 'https://run.cua.ai';
+const ACCESS_TOKEN = requiredEnv('VITE_CUA_FLEET_ACCESS_TOKEN');
+const POOL_NAME = requiredEnv('VITE_CUA_POOL_NAME');
+const TEMPLATE_NAME = `${POOL_NAME}-template`;
+
+function requiredEnv(name: string): string {
+ const value = import.meta.env[name];
+ if (!value) throw new Error(`Missing environment variable: ${name}`);
+ return value;
+}
+
+function screenshotBase64(responseBody: ArrayBuffer): string {
+ const text = new TextDecoder().decode(responseBody);
+ const dataLine = text.split('\n').find((line) => line.startsWith('data: '));
+ if (!dataLine) throw new Error(`No screenshot data frame: ${text.slice(0, 200)}`);
+
+ const payload = JSON.parse(dataLine.slice(6));
+ if (!payload.success) throw new Error(payload.error ?? 'Screenshot failed');
+
+ const encoded = payload.image_data ?? payload.result?.image_data;
+ if (typeof encoded !== 'string') throw new Error('Screenshot response has no image data');
+ return encoded;
+}
+
+function pngBlob(encoded: string): Blob {
+ const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
+ return new Blob([bytes], { type: 'image/png' });
+}
+
+await uniffiInitAsync();
+
+const configuration = new CyclopsTokenProviderConfigurationBuilder()
+ .baseUrl(BASE_URL)
+ .poolPollIntervalMs(5_000n)
+ .poolPollLimit(120)
+ .claimPollIntervalMs(5_000n)
+ .claimPollLimit(120)
+ .build();
+const client = CyclopsClient.connectBrowserWithAccessToken(configuration, ACCESS_TOKEN);
+
+let claim: Claim | undefined;
+try {
+ const service = new SandboxServiceBuilder().name('server').targetPort(8000).build();
+ const vm = new VmTemplateBuilder()
+ .containerDiskImage(IMAGE)
+ .cpuCores(4)
+ .memory('4Gi')
+ .services([service])
+ .build();
+ const templateSpec = new OsGymSandboxTemplateSpecBuilder().vmTemplate(vm).build();
+ const templateRef = new SandboxTemplateRefBuilder().name(TEMPLATE_NAME).build();
+ const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()
+ .replicas(1)
+ .sandboxTemplateRef(templateRef)
+ .build();
+
+ const pool = await client.createPool(
+ new CreatePoolRequestBuilder().namespace(POOL_NAME).spec(poolSpec).build()
+ );
+ const template = await client.createTemplate(
+ new CreateTemplateRequestBuilder()
+ .namespace(POOL_NAME)
+ .name(TEMPLATE_NAME)
+ .spec(templateSpec)
+ .build()
+ );
+
+ console.log(`Created pool ${pool.metadata.name} with template ${template.metadata.name}`);
+
+ claim = await client.createClaim(new CreateClaimRequestBuilder().pool(pool).build());
+ const sandbox = await client.waitClaim(claim);
+
+ const requestBody = await new Blob([JSON.stringify({ command: 'screenshot' })]).arrayBuffer();
+ const response = await client.serviceRequest(sandbox, 'server', '/cmd', {
+ method: 'POST',
+ url: 'https://service.invalid/cmd',
+ headers: [{ name: 'content-type', value: 'application/json' }],
+ body: requestBody,
+ timeoutSecs: 60n,
+ });
+ if (response.status < 200 || response.status >= 300) {
+ throw new Error(`Screenshot request failed with HTTP ${response.status}`);
+ }
+
+ const image = document.querySelector<HTMLImageElement>('#screenshot');
+ if (!image) throw new Error('Missing #screenshot image element');
+ image.src = URL.createObjectURL(pngBlob(screenshotBase64(response.body)));
+} finally {
+ // Release the claim but leave the reusable pool warm.
+ if (claim) await client.deleteClaim(claim);
+}
+```
+
+Replace `index.html` with a minimal screenshot page:
+
+```html title="index.html"
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Fleet screenshot</title>
+ </head>
+ <body>
+ <h1>Fleet sandbox screenshot</h1>
+ <img id="screenshot" alt="Fleet sandbox desktop" />
+ <script type="module" src="/src/main.ts"></script>
+ </body>
+</html>
+```
+
+Start the development server and open the printed URL:
+
+```bash
+npm run dev
+```
+
+The browser SDK authenticates the Fleet API request, routes `POST /cmd` through
+the named `server` service, decodes the computer-server event-stream response,
+and displays the PNG.
+
+ </Tab>
+</Tabs>
+
+## Keep or delete the pool
+
+Both examples release only the claim, so the one-replica pool remains warm for
+the next task. This is the normal reusable-pool lifecycle.
+
+The low-level Fleet SDK creates resources rather than reconciling them. Reusing
+the same pool name in the creation script returns an already-exists error. To
+reuse the pool, skip the creation calls and load it with:
+
+```ts
+const pool = await client.getPool(POOL_NAME);
+```
+
+To remove the pool permanently, retain the `pool` and `template` values and run
+the following after every claim has been released:
+
+```ts
+await client.deletePool(pool);
+await client.deleteTemplate(template);
+```
+
+Pool names are globally unique across Cua accounts. If creation returns HTTP
+403, choose another pool name; changing the claim name does not resolve a pool
+namespace conflict.
+
+## Use autoscaling instead of one replica
+
+Replace `.replicas(1)` with an autoscaling policy and omit `replicas`:
+
+```ts
+import { WarmPoolAutoscalingBuilder } from '@trycua/fleet/node';
+
+const autoscaling = new WarmPoolAutoscalingBuilder()
+ .minPoolSize(0)
+ .initialPoolSize(2)
+ .maxPoolSize(10)
+ .build();
+
+const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()
+ .autoscaling(autoscaling)
+ .sandboxTemplateRef(templateRef)
+ .build();
+```
+
+Use the matching `@trycua/fleet/browser` import in browser code. With a minimum
+size of zero, the first claim after an idle period cold-starts a sandbox.
diff --git a/docs/content/docs/how-to-guides/sandbox/meta.json b/docs/content/docs/how-to-guides/sandbox/meta.json
index 2d28abfb7d..736da86c58 100644
--- a/docs/content/docs/how-to-guides/sandbox/meta.json
+++ b/docs/content/docs/how-to-guides/sandbox/meta.json
@@ -4,6 +4,7 @@
"lifecycle",
"configure-pool-with-terraform",
"create-pool-with-python",
+ "create-pool-with-typescript",
"expire-pools-and-claims",
"secrets",
"scale-out",
diff --git a/libs/typescript/README.md b/libs/typescript/README.md
index e5f17bafa1..bf37fc2eaf 100644
--- a/libs/typescript/README.md
+++ b/libs/typescript/README.md
@@ -3,21 +3,23 @@
This repository contains TypeScript implementations of the Cua libraries:
- `@trycua/core`: Core functionality including telemetry and logging
-- `@trycua/computer`: Computer interaction SDK for VM management and control
+- `@trycua/fleet`: Browser and Node.js SDK for sandbox templates, pools, claims, and services
+- `@trycua/computer`: Legacy computer interaction and control compatibility SDK
## Project Structure
```text
libs/typescript/
-├── computer/ # Computer SDK package
+├── computer/ # Computer-control compatibility package
├── core/ # Core functionality package
+├── fleet/ # Fleet sandbox lifecycle package
├── package.json # Root package configuration
└── pnpm-workspace.yaml # Workspace configuration
```
## Prerequisites
-- [Node.js](https://nodejs.org/) (v18 or later)
+- [Node.js](https://nodejs.org/) (v20 or later)
- [pnpm](https://pnpm.io/) (v10 or later)
## Setup and Installation
@@ -50,7 +52,10 @@ Build specific packages:
# Build core package
pnpm --filter @trycua/core build
-# Build computer package
+# Build Fleet package
+pnpm --filter @trycua/fleet build
+
+# Build computer compatibility package
pnpm --filter @trycua/computer build
```
@@ -97,9 +102,10 @@ Core functionality for Cua libraries including:
### @trycua/computer
-Computer interaction SDK for managing and controlling virtual machines:
+Compatibility SDK for existing computer-control integrations. Use `@trycua/fleet`
+for new sandbox lifecycle code instead of managing Fleet resources here.
-- VM provider system (Cloud)
+- Legacy VM provider system (Cloud)
- Interface system for OS-specific interactions
- Screenshot, keyboard, and mouse control
- Command execution
diff --git a/libs/typescript/computer/README.md b/libs/typescript/computer/README.md
index 79b03ba828..c30c107fe5 100644
--- a/libs/typescript/computer/README.md
+++ b/libs/typescript/computer/README.md
@@ -1,5 +1,31 @@
# @trycua/computer
-Computer-Use Interface (CUI) framework for interacting with local macOS and Linux sandboxes.
+Computer-use interface for controlling local and legacy Cloud macOS, Linux, and
+Windows sandboxes.
+
+## Use Fleet for sandbox lifecycle
+
+New applications should use `@trycua/fleet` to create templates, pools, and
+claims and to send authenticated requests to services inside Fleet sandboxes:
+
+```bash
+npm install @trycua/fleet
+```
+
+Use the runtime-specific entry point in application code:
+
+```ts
+import { createFleetClient } from '@trycua/fleet/node';
+// Browser applications use @trycua/fleet/browser.
+```
+
+Do not call the legacy VM API or implement a second copy of Fleet lifecycle
+logic through `@trycua/computer`. See
+[Create a sandbox pool with TypeScript](https://cua.ai/docs/how-to-guides/sandbox/create-pool-with-typescript)
+for complete Node.js and browser examples, including screenshots.
+
+`@trycua/computer` remains available for existing computer-control integrations.
+Its Fleet compatibility provider delegates lifecycle operations to
+`@trycua/fleet`; new Fleet integrations should use the Fleet package directly.
**[Documentation](https://cua.ai/docs/cua/reference/computer-sdk)** - Installation, guides, and configuration.
diff --git a/libs/typescript/computer/package.json b/libs/typescript/computer/package.json
index 888bf761e1..8743ca11ae 100644
--- a/libs/typescript/computer/package.json
+++ b/libs/typescript/computer/package.json
@@ -5,13 +5,14 @@
"description": "Typescript SDK for Cua computer interaction",
"type": "module",
"license": "MIT",
- "homepage": "https://github.com/trycua/cua/tree/feature/computer/typescript/libs/typescript/computer",
+ "homepage": "https://github.com/trycua/cua/tree/main/libs/typescript/computer",
"bugs": {
"url": "https://github.com/trycua/cua/issues"
},
"repository": {
"type": "git",
- "url": "git+https://github.com/trycua/cua.git"
+ "url": "git+https://github.com/trycua/cua.git",
+ "directory": "libs/typescript/computer"
},
"author": "cua",
"files": [
@@ -35,13 +36,17 @@
"test": "vitest",
"typecheck": "tsc --noEmit",
"release": "bumpp && pnpm publish",
- "prepublishOnly": "pnpm run build"
+ "prepublishOnly": "pnpm run build",
+ "prebuild": "pnpm --filter @trycua/core build && pnpm --filter @trycua/fleet build",
+ "pretest": "pnpm --filter @trycua/core build && pnpm --filter @trycua/fleet build",
+ "pretypecheck": "pnpm --filter @trycua/core build && pnpm --filter @trycua/fleet build"
},
"dependencies": {
"@trycua/core": "workspace:^",
"pino": "^9.7.0",
"uuid": "^11.1.1",
- "ws": "^8.21.0"
+ "ws": "^8.21.0",
+ "@trycua/fleet": "workspace:^"
},
"devDependencies": {
"@types/node": "^22.15.17",
diff --git a/libs/typescript/computer/src/computer/index.ts b/libs/typescript/computer/src/computer/index.ts
index d7411b6366..66121321ee 100644
--- a/libs/typescript/computer/src/computer/index.ts
+++ b/libs/typescript/computer/src/computer/index.ts
@@ -1 +1,2 @@
-export { BaseComputer, CloudComputer } from './providers';
+export { BaseComputer, CloudComputer, FleetComputer } from './providers';
+export type { CloudComputerConfig, FleetComputerConfig } from './types';
diff --git a/libs/typescript/computer/src/computer/providers/fleet.ts b/libs/typescript/computer/src/computer/providers/fleet.ts
new file mode 100644
index 0000000000..cbabb5e621
--- /dev/null
+++ b/libs/typescript/computer/src/computer/providers/fleet.ts
@@ -0,0 +1,163 @@
+import { createHash } from 'node:crypto';
+import {
+ CreateClaimRequestBuilder,
+ CyclopsTokenProviderConfigurationBuilder,
+ createFleetClient,
+ type Claim,
+ type CyclopsClient,
+} from '@trycua/fleet/node';
+import pino from 'pino';
+import { v4 as uuidv4 } from 'uuid';
+import { type BaseComputerInterface, InterfaceFactory } from '../../interface/index';
+import type { FleetComputerConfig } from '../types';
+import { VMProviderType } from '../types';
+import { BaseComputer } from './base';
+
+const DEFAULT_FLEET_BASE_URL = process.env.CUA_FLEET_BASE_URL || 'https://run.cua.ai';
+const DEFAULT_SERVICE_NAME = 'server';
+
+function hashAccessToken(accessToken: string): string {
+ return createHash('sha256').update(accessToken).digest('hex');
+}
+
+function websocketProxyUrl(
+ baseUrl: string,
+ namespace: string,
+ sandboxName: string,
+ serviceName: string
+): string {
+ const url = new URL(
+ `/api/svc/${encodeURIComponent(namespace)}/${encodeURIComponent(`${sandboxName}-${serviceName}`)}/ws`,
+ baseUrl
+ );
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
+ return url.toString();
+}
+
+/** Computer implementation backed by a claim from an existing Fleet pool. */
+export class FleetComputer extends BaseComputer {
+ private readonly config: FleetComputerConfig;
+ private readonly sessionId = uuidv4();
+ private readonly accessTokenHash: string;
+ private iface?: BaseComputerInterface;
+ private client?: CyclopsClient;
+ private claim?: Claim;
+ private proxyUrl?: string;
+ private initialized = false;
+ private sessionStartTime?: number;
+
+ protected logger = pino({ name: 'computer.provider_fleet' });
+
+ constructor(config: FleetComputerConfig) {
+ super({ ...config, vmProvider: VMProviderType.FLEET });
+ this.config = config;
+ this.accessTokenHash = hashAccessToken(config.accessToken);
+ }
+
+ get ip(): string {
+ return this.proxyUrl ?? this.config.fleetBaseUrl ?? DEFAULT_FLEET_BASE_URL;
+ }
+
+ async run(): Promise<void> {
+ if (this.initialized) return;
+
+ try {
+ const configuration = new CyclopsTokenProviderConfigurationBuilder()
+ .baseUrl(this.config.fleetBaseUrl ?? DEFAULT_FLEET_BASE_URL)
+ .poolPollIntervalMs(this.config.poolPollIntervalMs ?? 5_000n)
+ .poolPollLimit(this.config.poolPollLimit ?? 120)
+ .claimPollIntervalMs(this.config.claimPollIntervalMs ?? 5_000n)
+ .claimPollLimit(this.config.claimPollLimit ?? 120)
+ .build();
+ this.client = await createFleetClient(configuration, this.config.accessToken);
+
+ const pool = await this.client.getPool(this.config.poolName);
+ if (this.config.namespace && pool.metadata.namespace !== this.config.namespace) {
+ throw new Error(
+ `Pool ${this.config.poolName} belongs to namespace ${pool.metadata.namespace}`
+ );
+ }
+
+ this.claim = await this.client.createClaim(
+ new CreateClaimRequestBuilder().pool(pool).build()
+ );
+ const sandbox = await this.client.waitClaim(this.claim);
+ this.proxyUrl = websocketProxyUrl(
+ this.config.fleetBaseUrl ?? DEFAULT_FLEET_BASE_URL,
+ sandbox.namespace,
+ sandbox.name,
+ this.config.serviceName ?? DEFAULT_SERVICE_NAME
+ );
+ this.iface = InterfaceFactory.createInterfaceForOS(
+ this.osType,
+ sandbox.name,
+ undefined,
+ undefined,
+ {
+ wsUrl: this.proxyUrl,
+ headers: { Authorization: `Bearer ${this.config.accessToken}` },
+ }
+ );
+ await this.iface.waitForReady();
+
+ this.initialized = true;
+ this.sessionStartTime = Date.now();
+ this.telemetry.recordEvent('ts_session_start', {
+ session_id: this.sessionId,
+ os_type: this.osType,
+ connection_type: 'fleet',
+ access_token_hash: this.accessTokenHash,
+ pool_name: this.config.poolName,
+ });
+ } catch (error) {
+ try {
+ await this.release();
+ } catch (releaseError) {
+ this.logger.warn(
+ `Failed to release Fleet claim after initialization error: ${releaseError}`
+ );
+ }
+ throw new Error(`Failed to initialize Fleet computer: ${error}`);
+ }
+ }
+
+ async stop(): Promise<void> {
+ if (this.sessionStartTime) {
+ this.telemetry.recordEvent('ts_session_end', {
+ session_id: this.sessionId,
+ duration_seconds: (Date.now() - this.sessionStartTime) / 1000,
+ access_token_hash: this.accessTokenHash,
+ pool_name: this.config.poolName,
+ });
+ }
+ await this.release();
+ }
+
+ get interface(): BaseComputerInterface {
+ if (!this.iface) throw new Error('Computer not initialized. Call run() first.');
+ return this.iface;
+ }
+
+ async disconnect(): Promise<void> {
+ await this.stop();
+ }
+
+ private async release(): Promise<void> {
+ this.iface?.disconnect();
+ this.iface = undefined;
+
+ const client = this.client;
+ const claim = this.claim;
+ this.client = undefined;
+ this.claim = undefined;
+ this.initialized = false;
+ this.sessionStartTime = undefined;
+ this.proxyUrl = undefined;
+
+ try {
+ if (client && claim) await client.deleteClaim(claim);
+ } finally {
+ client?.uniffiDestroy();
+ }
+ }
+}
diff --git a/libs/typescript/computer/src/computer/providers/index.ts b/libs/typescript/computer/src/computer/providers/index.ts
index 27faf7d6db..8d1b48bbc9 100644
--- a/libs/typescript/computer/src/computer/providers/index.ts
+++ b/libs/typescript/computer/src/computer/providers/index.ts
@@ -1,2 +1,3 @@
export * from './base';
export * from './cloud';
+export * from './fleet';
diff --git a/libs/typescript/computer/src/computer/types.ts b/libs/typescript/computer/src/computer/types.ts
index 42b48c78cd..267b2b6e5f 100644
--- a/libs/typescript/computer/src/computer/types.ts
+++ b/libs/typescript/computer/src/computer/types.ts
@@ -1,45 +1,37 @@
import type { OSType, ScreenSize } from '../types';
-/**
- * Display configuration for the computer.
- */
+/** Display configuration for the computer. */
export interface Display extends ScreenSize {
scale_factor?: number;
}
-/**
- * Computer configuration model.
- */
export interface BaseComputerConfig {
- /**
- * The VM name
- * @default ""
- */
name: string;
-
- /**
- * The operating system type ('macos', 'windows', or 'linux')
- * @default "macos"
- */
osType: OSType;
-
- /**
- * The VM provider type
- */
vmProvider?: VMProviderType;
}
export interface CloudComputerConfig extends BaseComputerConfig {
- /**
- * Optional API key for cloud providers
- */
apiKey: string;
}
+export interface FleetComputerConfig extends BaseComputerConfig {
+ accessToken: string;
+ poolName: string;
+ namespace?: string;
+ fleetBaseUrl?: string;
+ serviceName?: string;
+ poolPollIntervalMs?: bigint;
+ poolPollLimit?: number;
+ claimPollIntervalMs?: bigint;
+ claimPollLimit?: number;
+}
+
export enum VMProviderType {
DOCKER = 'docker',
LUME = 'lume',
CLOUD = 'cloud',
+ FLEET = 'fleet',
QEMU = 'qemu',
WINDOWS_SANDBOX = 'windows-sandbox',
HOST = 'host',
diff --git a/libs/typescript/computer/src/index.ts b/libs/typescript/computer/src/index.ts
index 7077d8a3cc..e920010ebc 100644
--- a/libs/typescript/computer/src/index.ts
+++ b/libs/typescript/computer/src/index.ts
@@ -1,5 +1,4 @@
-// Export classes
-export { CloudComputer as Computer } from './computer';
-
+export { CloudComputer as Computer, CloudComputer, FleetComputer } from './computer';
+export type { CloudComputerConfig, FleetComputerConfig } from './computer/types';
export { OSType } from './types';
export { VMProviderType as ProviderType } from './computer/types';
diff --git a/libs/typescript/computer/src/interface/base.ts b/libs/typescript/computer/src/interface/base.ts
index af445c0bc8..b8faf7f6b4 100644
--- a/libs/typescript/computer/src/interface/base.ts
+++ b/libs/typescript/computer/src/interface/base.ts
@@ -10,6 +10,11 @@ import type { ScreenSize } from '../types';
export type MouseButton = 'left' | 'middle' | 'right';
+export interface ComputerInterfaceConnection {
+ wsUrl?: string;
+ headers?: Record<string, string>;
+}
+
export interface CursorPosition {
x: number;
y: number;
@@ -41,6 +46,7 @@ export abstract class BaseComputerInterface {
protected ws: WebSocket;
protected apiKey?: string;
protected vmName?: string;
+ protected connection: ComputerInterfaceConnection;
protected logger = pino({ name: 'computer.interface-base' });
@@ -53,30 +59,29 @@ export abstract class BaseComputerInterface {
username = 'lume',
password = 'lume',
apiKey?: string,
- vmName?: string
+ vmName?: string,
+ connection: ComputerInterfaceConnection = {}
) {
this.ipAddress = ipAddress;
this.username = username;
this.password = password;
this.apiKey = apiKey;
this.vmName = vmName;
+ this.connection = connection;
// Initialize telemetry
this.telemetry = new Telemetry();
this.sessionId = uuidv4();
- // Initialize WebSocket with headers if needed
- const headers: { [key: string]: string } = {};
+ this.ws = this.createWebSocket();
+ }
+
+ private createWebSocket(): WebSocket {
+ const headers: Record<string, string> = { ...this.connection.headers };
if (this.apiKey && this.vmName) {
headers['X-API-Key'] = this.apiKey;
headers['X-VM-Name'] = this.vmName;
}
-
- // Create the WebSocket instance
- this.ws = this.createWebSocket(headers);
- }
-
- private createWebSocket(headers: { [key: string]: string }): WebSocket {
const ws = new WebSocket(this.wsUri, { headers });
// Constructors open immediately, and some tests only verify inheritance
// without ever calling connect(). Keep those failed background attempts
@@ -93,6 +98,8 @@ export abstract class BaseComputerInterface {
* Subclasses can override this to customize the URI.
*/
protected get wsUri(): string {
+ if (this.connection.wsUrl) return this.connection.wsUrl;
+
const protocol = this.apiKey ? 'wss' : 'ws';
// Check if ipAddress already includes a port
@@ -186,12 +193,7 @@ export abstract class BaseComputerInterface {
// If the WebSocket is closed or closing, reinitialize it
if (this.ws.readyState === WebSocket.CLOSED || this.ws.readyState === WebSocket.CLOSING) {
this.logger.info('Websocket is closed. Reinitializing connection.');
- const headers: { [key: string]: string } = {};
- if (this.apiKey && this.vmName) {
- headers['X-API-Key'] = this.apiKey;
- headers['X-VM-Name'] = this.vmName;
- }
- this.ws = this.createWebSocket(headers);
+ this.ws = this.createWebSocket();
}
// Connect and authenticate
diff --git a/libs/typescript/computer/src/interface/factory.ts b/libs/typescript/computer/src/interface/factory.ts
index 24dc72ad3b..84a191581e 100644
--- a/libs/typescript/computer/src/interface/factory.ts
+++ b/libs/typescript/computer/src/interface/factory.ts
@@ -3,35 +3,27 @@
*/
import type { OSType } from '../types';
-import type { BaseComputerInterface } from './base';
+import type { BaseComputerInterface, ComputerInterfaceConnection } from './base';
import { LinuxComputerInterface } from './linux';
import { MacOSComputerInterface } from './macos';
import { WindowsComputerInterface } from './windows';
export const InterfaceFactory = {
- /**
- * Create an interface for the specified OS.
- *
- * @param os Operating system type ('macos', 'linux', or 'windows')
- * @param ipAddress IP address of the computer to control
- * @param apiKey Optional API key for cloud authentication
- * @param vmName Optional VM name for cloud authentication
- * @returns The appropriate interface for the OS
- * @throws Error if the OS type is not supported
- */
+ /** Create an interface for the specified operating system and connection. */
createInterfaceForOS(
os: OSType,
ipAddress: string,
apiKey?: string,
- vmName?: string
+ vmName?: string,
+ connection?: ComputerInterfaceConnection
): BaseComputerInterface {
switch (os) {
case 'macos':
- return new MacOSComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName);
+ return new MacOSComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName, connection);
case 'linux':
- return new LinuxComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName);
+ return new LinuxComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName, connection);
case 'windows':
- return new WindowsComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName);
+ return new WindowsComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName, connection);
default:
throw new Error(`Unsupported OS type: ${os}`);
}
diff --git a/libs/typescript/computer/tests/computer/fleet.test.ts b/libs/typescript/computer/tests/computer/fleet.test.ts
new file mode 100644
index 0000000000..6f35dd2f91
--- /dev/null
+++ b/libs/typescript/computer/tests/computer/fleet.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FleetComputer, OSType, ProviderType } from '../../src';
+import { InterfaceFactory } from '../../src/interface/factory';
+
+const fleetMocks = vi.hoisted(() => ({
+ createFleetClient: vi.fn(),
+}));
+
+vi.mock('@trycua/fleet/node', () => ({
+ createFleetClient: fleetMocks.createFleetClient,
+ CyclopsTokenProviderConfigurationBuilder: class {
+ private configuration: Record<string, unknown> = {};
+
+ baseUrl(value: string) {
+ this.configuration.baseUrl = value;
+ return this;
+ }
+
+ poolPollIntervalMs(value: bigint) {
+ this.configuration.poolPollIntervalMs = value;
+ return this;
+ }
+
+ poolPollLimit(value: number) {
+ this.configuration.poolPollLimit = value;
+ return this;
+ }
+
+ claimPollIntervalMs(value: bigint) {
+ this.configuration.claimPollIntervalMs = value;
+ return this;
+ }
+
+ claimPollLimit(value: number) {
+ this.configuration.claimPollLimit = value;
+ return this;
+ }
+
+ build() {
+ return this.configuration;
+ }
+ },
+ CreateClaimRequestBuilder: class {
+ private request: Record<string, unknown> = {};
+
+ pool(value: unknown) {
+ this.request.pool = value;
+ return this;
+ }
+
+ build() {
+ return this.request;
+ }
+ },
+}));
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ fleetMocks.createFleetClient.mockReset();
+});
+
+describe('FleetComputer', () => {
+ it('claims a sandbox, connects through the Fleet proxy, and releases it', async () => {
+ const pool = { metadata: { namespace: 'keiki' } };
+ const claim = { metadata: { name: 'claim-1' } };
+ const sandbox = { namespace: 'keiki', name: 'sandbox-1', services: ['server'] };
+ const client = {
+ getPool: vi.fn().mockResolvedValue(pool),
+ createClaim: vi.fn().mockResolvedValue(claim),
+ waitClaim: vi.fn().mockResolvedValue(sandbox),
+ deleteClaim: vi.fn().mockResolvedValue(undefined),
+ uniffiDestroy: vi.fn(),
+ };
+ fleetMocks.createFleetClient.mockResolvedValue(client);
+
+ const iface = {
+ waitForReady: vi.fn().mockResolvedValue(undefined),
+ disconnect: vi.fn(),
+ };
+ const interfaceSpy = vi
+ .spyOn(InterfaceFactory, 'createInterfaceForOS')
+ .mockReturnValue(iface as never);
+
+ const computer = new FleetComputer({
+ name: 'keiki-task',
+ osType: OSType.LINUX,
+ vmProvider: ProviderType.FLEET,
+ accessToken: 'secret-token',
+ poolName: 'keiki-pool',
+ namespace: 'keiki',
+ serviceName: 'server',
+ });
+
+ await computer.run();
+
+ expect(computer.getVMProviderType()).toBe(ProviderType.FLEET);
+ expect(client.getPool).toHaveBeenCalledWith('keiki-pool');
+ expect(client.createClaim).toHaveBeenCalledWith({ pool });
+ expect(interfaceSpy).toHaveBeenCalledWith(OSType.LINUX, 'sandbox-1', undefined, undefined, {
+ wsUrl: 'wss://run.cua.ai/api/svc/keiki/sandbox-1-server/ws',
+ headers: { Authorization: 'Bearer secret-token' },
+ });
+ expect(computer.ip).toBe('wss://run.cua.ai/api/svc/keiki/sandbox-1-server/ws');
+
+ await computer.stop();
+
+ expect(iface.disconnect).toHaveBeenCalledOnce();
+ expect(client.deleteClaim).toHaveBeenCalledWith(claim);
+ expect(client.uniffiDestroy).toHaveBeenCalledOnce();
+ });
+
+ it('releases a claim when interface initialization fails', async () => {
+ const claim = { metadata: { name: 'claim-1' } };
+ const client = {
+ getPool: vi.fn().mockResolvedValue({ metadata: { namespace: 'keiki' } }),
+ createClaim: vi.fn().mockResolvedValue(claim),
+ waitClaim: vi
+ .fn()
+ .mockResolvedValue({ namespace: 'keiki', name: 'sandbox-1', services: ['server'] }),
+ deleteClaim: vi.fn().mockResolvedValue(undefined),
+ uniffiDestroy: vi.fn(),
+ };
+ fleetMocks.createFleetClient.mockResolvedValue(client);
+ vi.spyOn(InterfaceFactory, 'createInterfaceForOS').mockReturnValue({
+ waitForReady: vi.fn().mockRejectedValue(new Error('not ready')),
+ disconnect: vi.fn(),
+ } as never);
+
+ const computer = new FleetComputer({
+ name: 'keiki-task',
+ osType: OSType.LINUX,
+ accessToken: 'secret-token',
+ poolName: 'keiki-pool',
+ });
+
+ await expect(computer.run()).rejects.toThrow('Failed to initialize Fleet computer');
+ expect(client.deleteClaim).toHaveBeenCalledWith(claim);
+ expect(client.uniffiDestroy).toHaveBeenCalledOnce();
+ });
+});
diff --git a/libs/typescript/computer/tsdown.config.ts b/libs/typescript/computer/tsdown.config.ts
index ef25c723b3..139dcd4794 100644
--- a/libs/typescript/computer/tsdown.config.ts
+++ b/libs/typescript/computer/tsdown.config.ts
@@ -8,7 +8,7 @@ export default defineConfig([
entry: ['./src/index.ts'],
platform: 'node',
dts: true,
- external: ['child_process', 'util'],
+ external: ['child_process', 'util', '@trycua/fleet/node'],
define: {
__CUA_VERSION__: JSON.stringify(pkg.version),
},
diff --git a/libs/typescript/fleet/README.md b/libs/typescript/fleet/README.md
index 6b25c5a919..6c040d57db 100644
--- a/libs/typescript/fleet/README.md
+++ b/libs/typescript/fleet/README.md
@@ -1,18 +1,74 @@
# @trycua/fleet
-> **Name reservation** — this package name is reserved for **Cua Fleet**, an upcoming
-> component of the [Cua](https://github.com/trycua/cua) project for orchestrating fleets
-> of computer-use agents and sandboxes.
+Browser and Node.js WebAssembly bindings for the Cua Fleet control plane. Both
+entry points expose the generated lifecycle client used to create templates,
+pools, claims, and authenticated requests to sandbox services.
-This is a placeholder release: it installs an empty module and has no functionality yet.
-Watch [trycua/cua](https://github.com/trycua/cua) for the first real release.
+The package is built from the public Fleet mirror in
+[`libs/fleet`](../../fleet). That mirror is synchronized from the canonical
+Fleet repository, so the npm release and public SDK source share one repository
+and release history.
-In the meantime, check out the Cua TypeScript SDK:
+## Install
```bash
-npm install @trycua/computer @trycua/agent
+npm install @trycua/fleet
```
+## Browser
+
+```ts
+import {
+ CyclopsClient,
+ CyclopsTokenProviderConfigurationBuilder,
+ uniffiInitAsync,
+} from '@trycua/fleet/browser';
+
+await uniffiInitAsync();
+const configuration = new CyclopsTokenProviderConfigurationBuilder()
+ .baseUrl('https://run.cua.ai')
+ .poolPollIntervalMs(5_000n)
+ .poolPollLimit(120)
+ .claimPollIntervalMs(5_000n)
+ .claimPollLimit(120)
+ .build();
+const client = CyclopsClient.connectBrowserWithAccessToken(configuration, accessToken);
+```
+
+## Node.js
+
+The Node entry loads the same WASM artifact from disk and supplies a fetch-based
+UniFFI HTTP transport, so it does not require a platform-specific native
+`libcyclops_sdk`.
+
+```ts
+import { CyclopsTokenProviderConfigurationBuilder, createFleetClient } from '@trycua/fleet/node';
+
+const configuration = new CyclopsTokenProviderConfigurationBuilder()
+ .baseUrl('https://run.cua.ai')
+ .poolPollIntervalMs(5_000n)
+ .poolPollLimit(120)
+ .claimPollIntervalMs(5_000n)
+ .claimPollLimit(120)
+ .build();
+const client = await createFleetClient(configuration, accessToken);
+```
+
+The package root uses conditional exports: browser-aware bundlers receive the
+browser entry and Node.js receives the Node entry. Explicit subpath imports are
+recommended for application code and tests.
+
+## Development
+
+```bash
+pnpm --dir libs/typescript/fleet build
+pnpm --dir libs/typescript/fleet pack:check
+```
+
+The build regenerates the browser UniFFI binding from `libs/fleet`, compiles the
+pinned Rust SDK to WebAssembly, and emits both ESM entry points plus TypeScript
+declarations.
+
## Links
- Website: [cua.ai](https://cua.ai)
diff --git a/libs/typescript/fleet/index.d.ts b/libs/typescript/fleet/index.d.ts
deleted file mode 100644
index baaee2fd0c..0000000000
--- a/libs/typescript/fleet/index.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export declare const version: string;
diff --git a/libs/typescript/fleet/index.js b/libs/typescript/fleet/index.js
deleted file mode 100644
index f36d716749..0000000000
--- a/libs/typescript/fleet/index.js
+++ /dev/null
@@ -1,5 +0,0 @@
-// @trycua/fleet is reserved for Cua Fleet, an upcoming component of the Cua
-// project (https://github.com/trycua/cua) for orchestrating fleets of
-// computer-use agents and sandboxes. This is a placeholder release with no
-// functionality yet.
-export const version = '0.0.1';
diff --git a/libs/typescript/fleet/package.json b/libs/typescript/fleet/package.json
index d627049969..08e094da54 100644
--- a/libs/typescript/fleet/package.json
+++ b/libs/typescript/fleet/package.json
@@ -2,16 +2,17 @@
"name": "@trycua/fleet",
"version": "0.0.3",
"packageManager": "[email protected]",
- "description": "Reserved for Cua Fleet — fleet orchestration for computer-use agents and sandboxes. Placeholder release.",
+ "description": "Browser and WebAssembly SDK for Cua Fleet sandbox lifecycle management",
"type": "module",
"license": "MIT",
- "homepage": "https://github.com/trycua/cua",
+ "homepage": "https://github.com/trycua/cua/tree/main/libs/typescript/fleet",
"bugs": {
"url": "https://github.com/trycua/cua/issues"
},
"repository": {
"type": "git",
- "url": "git+https://github.com/trycua/cua.git"
+ "url": "git+https://github.com/trycua/cua.git",
+ "directory": "libs/typescript/fleet"
},
"author": "cua",
"keywords": [
@@ -23,17 +24,42 @@
"automation"
],
"files": [
- "index.js",
- "index.d.ts"
+ "dist"
],
- "main": "./index.js",
- "module": "./index.js",
- "types": "./index.d.ts",
+ "main": "./dist/node.js",
+ "module": "./dist/node.js",
+ "types": "./dist/node.d.ts",
"exports": {
- ".": "./index.js",
+ ".": {
+ "types": "./dist/node.d.ts",
+ "browser": "./dist/browser.js",
+ "node": "./dist/node.js",
+ "import": "./dist/node.js"
+ },
+ "./browser": {
+ "types": "./dist/browser.d.ts",
+ "import": "./dist/browser.js"
+ },
+ "./node": {
+ "types": "./dist/node.d.ts",
+ "import": "./dist/node.js"
+ },
"./package.json": "./package.json"
},
"publishConfig": {
"access": "public"
- }
+ },
+ "scripts": {
+ "build": "node ./scripts/build.mjs",
+ "pack:check": "pnpm run build && npm pack --dry-run"
+ },
+ "dependencies": {
+ "@ubjs/core": "0.31.0-3"
+ },
+ "devDependencies": {
+ "esbuild": "^0.27.0",
+ "typescript": "^5.9.0",
+ "@types/node": "^22.15.17"
+ },
+ "browser": "./dist/browser.js"
}
diff --git a/libs/typescript/fleet/scripts/build.mjs b/libs/typescript/fleet/scripts/build.mjs
new file mode 100644
index 0000000000..e196193ec3
--- /dev/null
+++ b/libs/typescript/fleet/scripts/build.mjs
@@ -0,0 +1,227 @@
+import { execFileSync, spawnSync } from 'node:child_process';
+import { cpSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build } from 'esbuild';
+
+const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const repositoryRoot = resolve(packageDirectory, '../../..');
+const bindingDirectory = join(repositoryRoot, 'libs/fleet/sdk-bindings/ts-uniffi-browser');
+const generatedDirectory = join(bindingDirectory, 'ts');
+const browserEntry = join(generatedDirectory, 'package.browser.ts');
+const nodeEntry = join(generatedDirectory, 'package.node.ts');
+const distributionDirectory = join(packageDirectory, 'dist');
+const declarationsDirectory = join(distributionDirectory, '.declarations');
+const rustToolchainFile = join(repositoryRoot, 'libs/fleet/rust-toolchain.toml');
+const rustToolchainMatch = readFileSync(rustToolchainFile, 'utf8').match(
+ /^channel\s*=\s*"([^"]+)"/m
+);
+if (!rustToolchainMatch) {
+ throw new Error(`Could not read the Rust channel from ${rustToolchainFile}`);
+}
+const rustToolchain = rustToolchainMatch[1];
+const wasmBindgenVersion = '0.2.126';
+
+const sharedExports = `
+export * from './cyclops_sdk_schema'
+export * from './fleet_sdk'
+
+import * as cyclops_sdk_schema from './cyclops_sdk_schema'
+import * as fleet_sdk from './fleet_sdk'
+import initAsync from './wasm-bindgen/index.js'
+import wasmPath from './wasm-bindgen/index_bg.wasm'
+
+let initialization: Promise<void> | undefined
+
+function initializeBindings(): void {
+ cyclops_sdk_schema.default.initialize()
+ fleet_sdk.default.initialize()
+}
+
+export default {
+ cyclops_sdk_schema,
+ fleet_sdk,
+}
+`;
+
+const browserSource = `${sharedExports}
+export function uniffiInitAsync(): Promise<void> {
+ initialization ??= (async () => {
+ await initAsync({ module_or_path: new URL(wasmPath as unknown as string, import.meta.url) })
+ initializeBindings()
+ })()
+ return initialization
+}
+`;
+
+const nodeSource = `
+import { readFile } from 'node:fs/promises'
+import type { HttpClient, HttpRequest, HttpResponse } from './fleet_sdk'
+${sharedExports}
+
+export class FetchHttpClient implements HttpClient {
+ async execute(
+ request: HttpRequest,
+ asyncOpts_?: { signal: AbortSignal },
+ ): Promise<HttpResponse> {
+ const timeoutSignal = request.timeoutSecs
+ ? AbortSignal.timeout(Number(request.timeoutSecs) * 1_000)
+ : undefined
+ const response = await fetch(request.url, {
+ method: request.method,
+ headers: request.headers.map(({ name, value }) => [name, value] as [string, string]),
+ body: request.body,
+ signal: asyncOpts_?.signal ?? timeoutSignal,
+ redirect: 'manual',
+ })
+ return {
+ status: response.status,
+ headers: [...response.headers].map(([name, value]) => ({ name, value })),
+ body: await response.arrayBuffer(),
+ }
+ }
+}
+
+export function uniffiInitAsync(): Promise<void> {
+ initialization ??= (async () => {
+ const wasm = await readFile(new URL(wasmPath as unknown as string, import.meta.url))
+ await initAsync({ module_or_path: wasm })
+ initializeBindings()
+ })()
+ return initialization
+}
+
+export async function createFleetClient(
+ configuration: fleet_sdk.CyclopsTokenProviderConfiguration,
+ accessToken: string,
+): Promise<fleet_sdk.CyclopsClient> {
+ await uniffiInitAsync()
+ return fleet_sdk.CyclopsClient.connectWithAccessToken(
+ configuration,
+ accessToken,
+ new FetchHttpClient(),
+ ) as fleet_sdk.CyclopsClient
+}
+`;
+
+function run(command, args, workingDirectory = packageDirectory) {
+ execFileSync(command, args, {
+ cwd: workingDirectory,
+ stdio: 'inherit',
+ });
+}
+
+function hasWasmBindgenVersion() {
+ const result = spawnSync('wasm-bindgen', ['--version'], {
+ encoding: 'utf8',
+ });
+ return result.status === 0 && result.stdout.trim() === `wasm-bindgen ${wasmBindgenVersion}`;
+}
+
+function normalizeDeclarationImports(source) {
+ return source
+ .replaceAll('.//', './')
+ .replace(/(from\s+['"])(\.\/[^'"]+?)(['"])/g, (_match, prefix, specifier, suffix) => {
+ return `${prefix}${specifier.endsWith('.js') ? specifier : `${specifier}.js`}${suffix}`;
+ });
+}
+
+rmSync(distributionDirectory, { force: true, recursive: true });
+mkdirSync(distributionDirectory, { recursive: true });
+
+run('rustup', ['toolchain', 'install', rustToolchain, '--profile', 'minimal']);
+run('rustup', ['target', 'add', 'wasm32-unknown-unknown', '--toolchain', rustToolchain]);
+if (!hasWasmBindgenVersion()) {
+ run('cargo', [
+ `+${rustToolchain}`,
+ 'install',
+ 'wasm-bindgen-cli',
+ '--version',
+ wasmBindgenVersion,
+ '--locked',
+ ]);
+}
+
+run('npm', ['ci'], bindingDirectory);
+run('npm', ['run', 'build:wasm'], bindingDirectory);
+writeFileSync(browserEntry, browserSource);
+writeFileSync(nodeEntry, nodeSource);
+
+try {
+ await build({
+ entryPoints: { browser: browserEntry },
+ bundle: true,
+ format: 'esm',
+ platform: 'browser',
+ target: ['es2022'],
+ outdir: distributionDirectory,
+ assetNames: 'fleet',
+ loader: {
+ '.wasm': 'file',
+ },
+ });
+
+ await build({
+ entryPoints: { node: nodeEntry },
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ target: ['node20'],
+ outdir: distributionDirectory,
+ assetNames: 'fleet',
+ loader: {
+ '.wasm': 'file',
+ },
+ });
+
+ const typescript = join(packageDirectory, 'node_modules/.bin/tsc');
+ run(typescript, [
+ '--declaration',
+ '--emitDeclarationOnly',
+ '--outDir',
+ declarationsDirectory,
+ '--module',
+ 'esnext',
+ '--moduleResolution',
+ 'bundler',
+ '--target',
+ 'es2022',
+ '--types',
+ 'node',
+ '--skipLibCheck',
+ '--allowArbitraryExtensions',
+ 'true',
+ browserEntry,
+ nodeEntry,
+ ]);
+
+ const declarationFiles = [
+ 'cyclops_sdk_schema-ffi.d.ts',
+ 'cyclops_sdk_schema.d.ts',
+ 'fleet_sdk-ffi.d.ts',
+ 'fleet_sdk.d.ts',
+ ];
+ for (const file of declarationFiles) {
+ cpSync(join(declarationsDirectory, file), join(distributionDirectory, file));
+ }
+ renameSync(
+ join(declarationsDirectory, 'package.browser.d.ts'),
+ join(distributionDirectory, 'browser.d.ts')
+ );
+ renameSync(
+ join(declarationsDirectory, 'package.node.d.ts'),
+ join(distributionDirectory, 'node.d.ts')
+ );
+ for (const file of [...declarationFiles, 'browser.d.ts', 'node.d.ts']) {
+ const declarationPath = join(distributionDirectory, file);
+ writeFileSync(
+ declarationPath,
+ normalizeDeclarationImports(readFileSync(declarationPath, 'utf8'))
+ );
+ }
+} finally {
+ rmSync(browserEntry, { force: true });
+ rmSync(nodeEntry, { force: true });
+ rmSync(declarationsDirectory, { force: true, recursive: true });
+}
diff --git a/libs/typescript/package.json b/libs/typescript/package.json
index 86cd628fff..22e49de507 100644
--- a/libs/typescript/package.json
+++ b/libs/typescript/package.json
@@ -16,7 +16,8 @@
"test": "pnpm -r test",
"typecheck": "pnpm build:core && pnpm -r typecheck",
"format": "prettier --write .",
- "format:check": "prettier --check ."
+ "format:check": "prettier --check .",
+ "build:fleet": "pnpm --filter @trycua/fleet build"
},
"packageManager": "[email protected]",
"devDependencies": {
diff --git a/libs/typescript/pnpm-lock.yaml b/libs/typescript/pnpm-lock.yaml
index 89b31417bd..f5221a2a14 100644
--- a/libs/typescript/pnpm-lock.yaml
+++ b/libs/typescript/pnpm-lock.yaml
@@ -62,6 +62,9 @@ importers:
"@trycua/core":
specifier: workspace:^
version: link:../core
+ "@trycua/fleet":
+ specifier: workspace:^
+ version: link:../fleet
pino:
specifier: ^9.7.0
version: 9.14.0
@@ -146,6 +149,22 @@ importers:
specifier: 4.1.0
+ fleet:
+ dependencies:
+ "@ubjs/core":
+ specifier: 0.31.0-3
+ version: 0.31.0-3
+ devDependencies:
+ "@types/node":
+ specifier: ^22.15.17
+ version: 22.19.8
+ esbuild:
+ specifier: ^0.27.0
+ version: 0.27.2
+ typescript:
+ specifier: ^5.9.0
+ version: 5.9.3
+
playground:
dependencies:
"@radix-ui/react-dialog":
@@ -1635,6 +1654,12 @@ packages:
integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==,
}
+ resolution:
+ {
+ integrity: sha512-39XrJgUZ2VVb561sSnkXPhczNoeBsNiSRArecsV0JE7CJq69ajFkcn9/tBAUS2NpgHkLIDU+z6Ks2+1wXnboxg==,
+ }
+
resolution:
{
@@ -4151,6 +4176,8 @@ snapshots:
dependencies:
"@types/node": 22.19.8
+ "@ubjs/[email protected]": {}
+
"@ungap/[email protected]": {}
"@vitest/[email protected]":
diff --git a/libs/typescript/pnpm-workspace.yaml b/libs/typescript/pnpm-workspace.yaml
index 3d90fa6bec..39a0bbd05d 100644
--- a/libs/typescript/pnpm-workspace.yaml
+++ b/libs/typescript/pnpm-workspace.yaml
@@ -2,6 +2,7 @@ packages:
- "computer"
- "core"
- "agent"
+ - "fleet"
- "playground"
minimumReleaseAge: 46080