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.

Added typescript agent client SDK

Dillon DuPont7953de3ba4a5
diff --git a/libs/typescript/agent/README.md b/libs/typescript/agent/README.md
new file mode 100644
index 0000000000..36dc89c952
--- /dev/null
+++ b/libs/typescript/agent/README.md
@@ -0,0 +1,193 @@
+# @trycua/agent
+
+TypeScript SDK for CUA agent interaction. Connect to CUA agent proxies via HTTP/HTTPS or peer-to-peer (WebRTC) connections.
+
+## Installation
+
+```bash
+npm install @trycua/agent
+# or
+pnpm add @trycua/agent
+# or
+yarn add @trycua/agent
+```
+
+## Usage
+
+### Basic Usage
+
+```typescript
+import AgentClient from "@trycua/agent";
+
+// Connect to HTTP server
+const client = new AgentClient("https://localhost:8000");
+
+// Connect to peer
+const peerClient = new AgentClient("peer://my-agent-proxy");
+
+// Send a simple text request
+const response = await client.responses.create({
+ model: "anthropic/claude-3-5-sonnet-20241022",
+ input: "Write a one-sentence bedtime story about a unicorn."
+});
+
+console.log(response.result);
+```
+
+### Multi-modal Requests
+
+```typescript
+const response = await client.responses.create({
+ model: "anthropic/claude-3-5-sonnet-20241022",
+ input: [
+ {
+ role: "user",
+ content: [
+ { type: "input_text", text: "What is in this image?" },
+ {
+ type: "input_image",
+ image_url: "https://example.com/image.jpg"
+ }
+ ]
+ }
+ ]
+});
+```
+
+### Advanced Configuration
+
+```typescript
+const client = new AgentClient("https://localhost:8000", {
+ timeout: 60000, // 60 second timeout
+ retries: 5 // 5 retry attempts
+});
+
+const response = await client.responses.create({
+ model: "anthropic/claude-3-5-sonnet-20241022",
+ input: "Hello, world!",
+ agent_kwargs: {
+ save_trajectory: true,
+ verbosity: 20
+ },
+ computer_kwargs: {
+ os_type: "linux",
+ provider_type: "cloud"
+ }
+});
+```
+
+### Health Check
+
+```typescript
+const health = await client.health();
+console.log(health.status); // 'healthy', 'unhealthy', 'unreachable', 'connected', 'disconnected'
+```
+
+### Cleanup
+
+```typescript
+// Clean up peer connections when done
+await client.disconnect();
+```
+
+## API Reference
+
+### AgentClient
+
+#### Constructor
+
+```typescript
+new AgentClient(url: string, options?: AgentClientOptions)
+```
+
+- `url`: Connection URL. Supports `http://`, `https://`, or `peer://` protocols
+- `options`: Optional configuration object
+
+#### Methods
+
+##### responses.create(request: AgentRequest): Promise<AgentResponse>
+
+Send a request to the agent and get a response.
+
+##### health(): Promise<{status: string}>
+
+Check the health/connection status of the agent.
+
+##### disconnect(): Promise<void>
+
+Clean up resources and close connections.
+
+### Types
+
+#### AgentRequest
+
+```typescript
+interface AgentRequest {
+ model: string;
+ input: string | AgentMessage[];
+ agent_kwargs?: {
+ save_trajectory?: boolean;
+ verbosity?: number;
+ [key: string]: any;
+ };
+ computer_kwargs?: {
+ os_type?: string;
+ provider_type?: string;
+ [key: string]: any;
+ };
+}
+```
+
+#### AgentResponse
+
+```typescript
+interface AgentResponse {
+ success: boolean;
+ result?: any;
+ model: string;
+ error?: string;
+}
+```
+
+## Connection Types
+
+### HTTP/HTTPS
+
+Connect to a CUA agent proxy server:
+
+```typescript
+const client = new AgentClient("https://my-agent-server.com:8000");
+```
+
+### Peer-to-Peer (WebRTC)
+
+Connect directly to another peer using WebRTC:
+
+```typescript
+const client = new AgentClient("peer://agent-proxy-peer-id");
+```
+
+The client uses PeerJS with default configuration for peer connections.
+
+## Error Handling
+
+```typescript
+try {
+ const response = await client.responses.create({
+ model: "anthropic/claude-3-5-sonnet-20241022",
+ input: "Hello!"
+ });
+
+ if (response.success) {
+ console.log(response.result);
+ } else {
+ console.error("Agent error:", response.error);
+ }
+} catch (error) {
+ console.error("Connection error:", error.message);
+}
+```
+
+## License
+
+MIT
diff --git a/libs/typescript/agent/examples/README.md b/libs/typescript/agent/examples/README.md
new file mode 100644
index 0000000000..8e3148fbbf
--- /dev/null
+++ b/libs/typescript/agent/examples/README.md
@@ -0,0 +1,70 @@
+# CUA Agent Client Examples
+
+This directory contains examples demonstrating how to use the `@trycua/agent` client library.
+
+## Browser Example
+
+### `browser-example.html`
+
+A simple HTML page that demonstrates using the CUA Agent Client in a browser environment.
+
+**Features:**
+- Connect to HTTP/HTTPS or P2P (peer://) agent proxies
+- Send text messages to any supported model
+- View responses in real-time
+- Health check functionality
+- Clear, simple interface with no external dependencies
+
+**Usage:**
+
+1. **Build the library first:**
+ ```bash
+ cd ../
+ pnpm build
+ ```
+
+2. **Start a local web server** (required for ES modules):
+ ```bash
+ # Option 1: Using Python
+ python -m http.server 8080
+
+ # Option 2: Using Node.js (if you have http-server installed)
+ npx http-server -p 8080
+
+ # Option 3: Using any other local server
+ ```
+
+3. **Open in browser:**
+ Navigate to `http://localhost:8080/examples/browser-example.html`
+
+4. **Configure and test:**
+ - Enter an agent URL (e.g., `https://localhost:8000` or `peer://some-peer-id`)
+ - Enter a model name (e.g., `anthropic/claude-3-5-sonnet-20241022`)
+ - Type a message and click "Send Message" or press Enter
+ - View the response in the output textarea
+
+**Supported URLs:**
+- **HTTP/HTTPS**: `https://localhost:8000`, `http://my-agent-server.com:8080`
+- **Peer-to-Peer**: `peer://computer-agent-proxy`, `peer://any-peer-id`
+
+**Example Models:**
+- `anthropic/claude-3-5-sonnet-20241022`
+- `openai/gpt-4`
+- `huggingface-local/microsoft/UI-TARS-7B`
+
+**Note:** Make sure you have a CUA agent proxy server running at the specified URL before testing.
+
+## Running Agent Proxy Server
+
+To test the examples, you'll need a CUA agent proxy server running:
+
+```bash
+# HTTP server (default port 8000)
+python -m agent.proxy.cli
+
+# P2P server
+python -m agent.proxy.cli --mode p2p
+
+# Both HTTP and P2P
+python -m agent.proxy.cli --mode both
+```
diff --git a/libs/typescript/agent/examples/playground-example.html b/libs/typescript/agent/examples/playground-example.html
new file mode 100644
index 0000000000..e1d51d7198
--- /dev/null
+++ b/libs/typescript/agent/examples/playground-example.html
@@ -0,0 +1,146 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>CUA Agent Client Browser Example</title>
+</head>
+<body>
+ <h1>CUA Agent Client Browser Example</h1>
+
+ <div>
+ <h2>Configuration</h2>
+ <label for="url">Agent URL:</label><br>
+ <input type="text" id="url" placeholder="https://localhost:8000 or peer://peer-id" value="https://localhost:8000" style="width: 400px;"><br><br>
+
+ <label for="model">Model:</label><br>
+ <input type="text" id="model" placeholder="anthropic/claude-opus-4-1-20250805" value="anthropic/claude-opus-4-1-20250805" style="width: 400px;"><br><br>
+ </div>
+
+ <div>
+ <h2>Chat</h2>
+ <label for="message">Message:</label><br>
+ <input type="text" id="message" placeholder="Enter your message here..." style="width: 400px;"><br><br>
+
+ <button onclick="sendMessage()">Send Message</button>
+ <button onclick="checkHealth()">Check Health</button>
+ <button onclick="clearOutput()">Clear Output</button><br><br>
+
+ <label for="output">Output:</label><br>
+ <textarea id="output" rows="20" cols="80" readonly></textarea>
+ </div>
+
+ <script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
+ <script type="module">
+ // Import the AgentClient from the built library
+ import AgentClient from '/dist/index.js';
+
+ let client = null;
+
+ // Make functions available globally
+ window.sendMessage = sendMessage;
+ window.checkHealth = checkHealth;
+ window.clearOutput = clearOutput;
+
+ function log(message) {
+ const output = document.getElementById('output');
+ const timestamp = new Date().toLocaleTimeString();
+ output.value += `[${timestamp}] ${message}\n`;
+ output.scrollTop = output.scrollHeight;
+ }
+
+ function getClient() {
+ const url = document.getElementById('url').value.trim();
+ if (!url) {
+ log('ERROR: Please enter a URL');
+ return null;
+ }
+
+ // Create new client if URL changed or client doesn't exist
+ if (!client || client.url !== url) {
+ try {
+ client = new AgentClient(url);
+ client.url = url; // Store URL for comparison
+ log(`Created new client for: ${url}`);
+ } catch (error) {
+ log(`ERROR creating client: ${error.message}`);
+ return null;
+ }
+ }
+
+ return client;
+ }
+
+ async function sendMessage() {
+ const messageInput = document.getElementById('message');
+ const modelInput = document.getElementById('model');
+
+ const message = messageInput.value.trim();
+ const model = modelInput.value.trim();
+
+ if (!message) {
+ log('ERROR: Please enter a message');
+ return;
+ }
+
+ if (!model) {
+ log('ERROR: Please enter a model');
+ return;
+ }
+
+ const agentClient = getClient();
+ if (!agentClient) return;
+
+ try {
+ log(`Sending message: "${message}"`);
+ log(`Using model: ${model}`);
+
+ const request = {
+ model: model,
+ input: message
+ };
+
+ log('Sending request...');
+ const response = await agentClient.responses.create(request);
+
+ log('Response received:');
+ log(JSON.stringify(response, null, 2));
+
+ // Clear the message input
+ messageInput.value = '';
+
+ } catch (error) {
+ log(`ERROR: ${error.message}`);
+ }
+ }
+
+ async function checkHealth() {
+ const agentClient = getClient();
+ if (!agentClient) return;
+
+ try {
+ log('Checking health...');
+ const health = await agentClient.health();
+ log(`Health status: ${health.status}`);
+ } catch (error) {
+ log(`ERROR checking health: ${error.message}`);
+ }
+ }
+
+ function clearOutput() {
+ document.getElementById('output').value = '';
+ }
+
+ // Allow sending message with Enter key
+ document.getElementById('message').addEventListener('keypress', function(e) {
+ if (e.key === 'Enter') {
+ sendMessage();
+ }
+ });
+
+ // Log initial message
+ log('CUA Agent Client Browser Example loaded');
+ log('Enter a URL (HTTP/HTTPS or peer://) and model, then send a message');
+ </script>
+</body>
+</html>
diff --git a/libs/typescript/agent/package.json b/libs/typescript/agent/package.json
new file mode 100644
index 0000000000..a1585db26f
--- /dev/null
+++ b/libs/typescript/agent/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "@trycua/agent",
+ "version": "0.1.0",
+ "packageManager": "[email protected]",
+ "description": "TypeScript SDK for CUA agent interaction",
+ "type": "module",
+ "license": "MIT",
+ "homepage": "https://github.com/trycua/cua/tree/main/libs/typescript/agent",
+ "bugs": {
+ "url": "https://github.com/trycua/cua/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/trycua/cua.git"
+ },
+ "author": "cua",
+ "files": [
+ "dist"
+ ],
+ "main": "./dist/index.js",
+ "module": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": "./dist/index.js",
+ "./package.json": "./package.json"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "scripts": {
+ "lint": "biome lint .",
+ "lint:fix": "biome lint --fix .",
+ "build": "tsdown",
+ "dev": "tsdown --watch",
+ "test": "vitest",
+ "typecheck": "tsc --noEmit",
+ "release": "bumpp && pnpm publish",
+ "prepublishOnly": "pnpm run build"
+ },
+ "dependencies": {
+ "@trycua/core": "^0.1.2",
+ "pino": "^9.7.0",
+ "peerjs": "^1.5.4"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "^1.9.4",
+ "@types/node": "^22.15.17",
+ "bumpp": "^10.1.0",
+ "happy-dom": "^17.4.7",
+ "tsdown": "^0.3.0",
+ "typescript": "^5.7.2",
+ "vitest": "^2.1.8"
+ }
+}
diff --git a/libs/typescript/agent/src/client.ts b/libs/typescript/agent/src/client.ts
new file mode 100644
index 0000000000..6a2ec0a277
--- /dev/null
+++ b/libs/typescript/agent/src/client.ts
@@ -0,0 +1,181 @@
+import pkg from 'peerjs';
+const { Peer, DataConnection } = pkg;
+import type { AgentRequest, AgentResponse, ConnectionType, AgentClientOptions } from './types.js';
+
+export class AgentClient {
+ private url: string;
+ private connectionType: ConnectionType;
+ private options: AgentClientOptions;
+ private peer?: Peer;
+ private connection?: DataConnection;
+
+ constructor(url: string, options: AgentClientOptions = {}) {
+ this.url = url;
+ this.options = {
+ timeout: 30000,
+ retries: 3,
+ ...options,
+ };
+
+ // Determine connection type from URL
+ if (url.startsWith('http://') || url.startsWith('https://')) {
+ this.connectionType = url.startsWith('https://') ? 'https' : 'http';
+ } else if (url.startsWith('peer://')) {
+ this.connectionType = 'peer';
+ } else {
+ throw new Error('Invalid URL format. Must start with http://, https://, or peer://');
+ }
+ }
+
+ // Main responses API matching the desired usage pattern
+ public responses = {
+ create: async (request: AgentRequest): Promise<AgentResponse> => {
+ return this.sendRequest(request);
+ }
+ };
+
+ private async sendRequest(request: AgentRequest): Promise<AgentResponse> {
+ switch (this.connectionType) {
+ case 'http':
+ case 'https':
+ return this.sendHttpRequest(request);
+ case 'peer':
+ return this.sendPeerRequest(request);
+ default:
+ throw new Error(`Unsupported connection type: ${this.connectionType}`);
+ }
+ }
+
+ private async sendHttpRequest(request: AgentRequest): Promise<AgentResponse> {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.options.timeout);
+
+ try {
+ const response = await fetch(`${this.url}/responses`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(request),
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeoutId);
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ return data as AgentResponse;
+ } catch (error) {
+ clearTimeout(timeoutId);
+ if (error instanceof Error) {
+ throw new Error(`Failed to send HTTP request: ${error.message}`);
+ }
+ throw error;
+ }
+ }
+
+ private async sendPeerRequest(request: AgentRequest): Promise<AgentResponse> {
+ // Extract peer ID from peer:// URL
+ const peerId = this.url.replace('peer://', '');
+
+ if (!this.peer) {
+ // Initialize peer connection with default options as requested
+ this.peer = new Peer();
+
+ return new Promise<AgentResponse>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ reject(new Error('Peer connection timeout'));
+ }, this.options.timeout);
+
+ this.peer!.on('open', () => {
+ // Connect to the target peer
+ this.connection = this.peer!.connect(peerId);
+
+ this.connection.on('open', () => {
+ // Send the request
+ this.connection!.send(JSON.stringify(request));
+ });
+
+ this.connection.on('data', (data: any) => {
+ clearTimeout(timeout);
+ try {
+ const response = typeof data === 'string' ? JSON.parse(data) : data;
+ resolve(response as AgentResponse);
+ } catch (error) {
+ reject(new Error('Failed to parse peer response'));
+ }
+ });
+
+ this.connection.on('error', (error: any) => {
+ clearTimeout(timeout);
+ reject(new Error(`Peer connection error: ${error}`));
+ });
+ });
+
+ this.peer!.on('error', (error: any) => {
+ clearTimeout(timeout);
+ reject(new Error(`Peer error: ${error}`));
+ });
+ });
+ } else {
+ // Reuse existing connection
+ return new Promise<AgentResponse>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ reject(new Error('Peer request timeout'));
+ }, this.options.timeout);
+
+ if (this.connection && this.connection.open) {
+ this.connection.send(JSON.stringify(request));
+
+ const handleData = (data: any) => {
+ clearTimeout(timeout);
+ this.connection!.off('data', handleData);
+ try {
+ const response = typeof data === 'string' ? JSON.parse(data) : data;
+ resolve(response as AgentResponse);
+ } catch (error) {
+ reject(new Error('Failed to parse peer response'));
+ }
+ };
+
+ this.connection.on('data', handleData);
+ } else {
+ clearTimeout(timeout);
+ reject(new Error('Peer connection not available'));
+ }
+ });
+ }
+ }
+
+ // Health check method
+ async health(): Promise<{ status: string }> {
+ if (this.connectionType === 'peer') {
+ return { status: this.peer?.open ? 'connected' : 'disconnected' };
+ }
+
+ try {
+ const response = await fetch(`${this.url}/health`);
+ if (response.ok) {
+ return { status: 'healthy' };
+ }
+ return { status: 'unhealthy' };
+ } catch {
+ return { status: 'unreachable' };
+ }
+ }
+
+ // Clean up resources
+ async disconnect(): Promise<void> {
+ if (this.connection) {
+ this.connection.close();
+ this.connection = undefined;
+ }
+ if (this.peer) {
+ this.peer.destroy();
+ this.peer = undefined;
+ }
+ }
+}
diff --git a/libs/typescript/agent/src/index.ts b/libs/typescript/agent/src/index.ts
new file mode 100644
index 0000000000..225fa0b364
--- /dev/null
+++ b/libs/typescript/agent/src/index.ts
@@ -0,0 +1,15 @@
+// Export the main AgentClient class as default
+export { AgentClient as default } from './client.js';
+
+// Also export as named export for flexibility
+export { AgentClient } from './client.js';
+
+// Export types for TypeScript users
+export type {
+ AgentRequest,
+ AgentResponse,
+ AgentMessage,
+ AgentContent,
+ ConnectionType,
+ AgentClientOptions,
+} from './types.js';
diff --git a/libs/typescript/agent/src/types.ts b/libs/typescript/agent/src/types.ts
new file mode 100644
index 0000000000..ea32915f6e
--- /dev/null
+++ b/libs/typescript/agent/src/types.ts
@@ -0,0 +1,43 @@
+// Request types matching the Python proxy API
+export interface AgentRequest {
+ model: string;
+ input: string | AgentMessage[];
+ agent_kwargs?: {
+ save_trajectory?: boolean;
+ verbosity?: number;
+ [key: string]: any;
+ };
+ computer_kwargs?: {
+ os_type?: string;
+ provider_type?: string;
+ [key: string]: any;
+ };
+}
+
+// Multi-modal message types
+export interface AgentMessage {
+ role: 'user' | 'assistant';
+ content: AgentContent[];
+}
+
+export interface AgentContent {
+ type: 'input_text' | 'input_image';
+ text?: string;
+ image_url?: string;
+}
+
+// Response types
+export interface AgentResponse {
+ success: boolean;
+ result?: any;
+ model: string;
+ error?: string;
+}
+
+// Connection types
+export type ConnectionType = 'http' | 'https' | 'peer';
+
+export interface AgentClientOptions {
+ timeout?: number;
+ retries?: number;
+}
diff --git a/libs/typescript/agent/tests/client.test.ts b/libs/typescript/agent/tests/client.test.ts
new file mode 100644
index 0000000000..b267b12282
--- /dev/null
+++ b/libs/typescript/agent/tests/client.test.ts
@@ -0,0 +1,34 @@
+import { describe, it, expect } from 'vitest';
+import AgentClient from '../src/index.js';
+
+describe('AgentClient', () => {
+ it('should create client with HTTP URL', () => {
+ const client = new AgentClient('https://localhost:8000');
+ expect(client).toBeDefined();
+ expect(client.responses).toBeDefined();
+ expect(typeof client.responses.create).toBe('function');
+ });
+
+ it('should create client with peer URL', () => {
+ const client = new AgentClient('peer://test-peer-id');
+ expect(client).toBeDefined();
+ expect(client.responses).toBeDefined();
+ expect(typeof client.responses.create).toBe('function');
+ });
+
+ it('should throw error for invalid URL', () => {
+ expect(() => {
+ new AgentClient('invalid://url');
+ }).toThrow('Invalid URL format');
+ });
+
+ it('should have health method', async () => {
+ const client = new AgentClient('https://localhost:8000');
+ expect(typeof client.health).toBe('function');
+ });
+
+ it('should have disconnect method', async () => {
+ const client = new AgentClient('https://localhost:8000');
+ expect(typeof client.disconnect).toBe('function');
+ });
+});
diff --git a/libs/typescript/agent/tsconfig.json b/libs/typescript/agent/tsconfig.json
new file mode 100644
index 0000000000..8d56b691fb
--- /dev/null
+++ b/libs/typescript/agent/tsconfig.json
@@ -0,0 +1,28 @@
+{
+ "compilerOptions": {
+ "target": "esnext",
+ "lib": [
+ "es2023"
+ ],
+ "moduleDetection": "force",
+ "module": "preserve",
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "types": [
+ "node"
+ ],
+ "allowSyntheticDefaultImports": true,
+ "strict": true,
+ "noUnusedLocals": true,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "esModuleInterop": true,
+ "isolatedModules": true,
+ "verbatimModuleSyntax": true,
+ "skipLibCheck": true
+ },
+ "include": [
+ "src"
+ ]
+}
\ No newline at end of file
diff --git a/libs/typescript/agent/tsdown.config.ts b/libs/typescript/agent/tsdown.config.ts
new file mode 100644
index 0000000000..408990c1ec
--- /dev/null
+++ b/libs/typescript/agent/tsdown.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'tsdown'
+
+export default defineConfig({
+ entry: ['src/index.ts'],
+ format: ['esm'],
+ dts: true,
+ clean: true,
+})
diff --git a/libs/typescript/agent/vitest.config.ts b/libs/typescript/agent/vitest.config.ts
new file mode 100644
index 0000000000..56feb5b7e0
--- /dev/null
+++ b/libs/typescript/agent/vitest.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ environment: 'happy-dom',
+ },
+})