# UiPath TypeScript SDK # Getting Started # Getting Started ## Prerequisites - **Node.js** 20.x or higher - **npm** 8.x or higher (or yarn/pnpm) - **TypeScript** 4.5+ (for TypeScript projects) ## Install the SDK npm install @uipath/uipath-typescript\ found 0 vulnerabilities yarn add @uipath/uipath-typescript✨ Done in 1.85s. pnpm add @uipath/uipath-typescript ## Project Setup mkdir my-uipath-project && cd my-uipath-projectnpm init -yWrote to package.jsonnpm install typescript @types/node ts-node --save-dev\ added x packages in 1snpx tsc --initCreated a new tsconfig.jsonnpm install @uipath/uipath-typescript\ added x packages in 1s mkdir my-uipath-project && cd my-uipath-projectnpm init -yWrote to package.jsonnpm install @uipath/uipath-typescript\ added x packages in 1s ## **Import & Initialize** The SDK supports two import patterns. Choose based on your SDK version. ``` // Import core SDK and only the services you need import { UiPath } from '@uipath/uipath-typescript/core'; import { Entities } from '@uipath/uipath-typescript/entities'; // Configure and initialize the SDK const sdk = new UiPath({ baseUrl: 'https://cloud.uipath.com', orgName: 'your-org', tenantName: 'your-tenant', clientId: 'your-client-id', redirectUri: 'http://localhost:3000/callback', scope: 'OR.Tasks OR.DataService' }); await sdk.initialize(); // Create service instances const entities = new Entities(sdk); // Use the services const allEntities = await entities.getAll(); ``` ``` // Import everything from the main package import { UiPath } from '@uipath/uipath-typescript'; // Configure and initialize the SDK const sdk = new UiPath({ baseUrl: 'https://cloud.uipath.com', orgName: 'your-org', tenantName: 'your-tenant', clientId: 'your-client-id', redirectUri: 'http://localhost:3000/callback', scope: 'OR.Tasks OR.DataService' }); await sdk.initialize(); // Access services directly from sdk instance const allTasks = await sdk.tasks.getAll(); const allEntities = await sdk.entities.getAll(); ``` **Note:** This pattern still works in newer versions but it includes all services in your bundle regardless of usage. ## **Telemetry** To improve the developer experience, the SDK collects basic usage data about method invocations. For details on UiPath’s privacy practices, see our [privacy policy](https://www.uipath.com/legal/privacy-policy). ## **Vibe Coding** The SDK is designed for rapid prototyping and development, making it perfect for vibe coding. Here are three ways to get started: ### **Option 1: AI Agent Skills** Install the agent skill in your AI agent of choice to build, deploy, and create coded apps: # install uipath cli npm install -g @uipath/cli# install all uipath skillsuip skills install This will install all uipath skills including the uipath-coded-apps skill. See [UiPath Skills](https://github.com/uipath/skills) and [UiPath CLI](https://github.com/UiPath/cli) for more details. ### **Option 2: AI IDE Integration** After installing the SDK, supercharge your development with AI IDEs: 1. **Install the SDK**: `npm install @uipath/uipath-typescript` 1. **Drag & Drop**: From your `node_modules/@uipath/uipath-typescript` folder, drag the entire package into your AI IDE 1. **Start Prompting**: Your AI assistant now has full context of the SDK! **Works with:** - **GitHub Copilot** - **Cursor** - **Claude** - **Any AI coding assistant** ### **Option 3: Copy Documentation for LLMs** Give your AI assistant complete context by copying our documentation: **For Maximum Context:** 1. **Download Complete Documentation**: [llms-full-content.txt](/uipath-typescript/llms-full-content.txt) 1. **Copy and Paste**: Copy the entire content and paste it into your AI chat 1. **Start Prompting**: Your AI now has complete SDK knowledge! **For Specific Features:** 1. **Use the copy button** (πŸ“‹) on any documentation page 1. **Paste into your AI chat** 1. **Ask specific questions** about that feature # Authentication The SDK supports multiple authentication methods depending on your use case. ## Coded Apps Once your app is deployed as a [Coded App](../coded-apps/getting-started/), the platform injects all configuration automatically at deploy time. You can construct `UiPath` with no arguments β€” the SDK reads from the injected meta tags: ``` import { UiPath } from '@uipath/uipath-typescript/core'; const sdk = new UiPath(); await sdk.initialize(); ``` See [Coded Apps β€” Getting Started](../coded-apps/getting-started/) for the full setup guide. ## OAuth Authentication (Recommended) For OAuth, first create a non confidential [External App](https://docs.uipath.com/automation-cloud/automation-cloud/latest/admin-guide/managing-external-applications). 1. In UiPath Cloud: **Admin** β†’ **External Applications** 1. Click **Add Application** β†’ **Non Confidential Application** 1. Configure: - **Name**: Your app name - **Redirect URI**: For eg, `http://localhost:3000` (for development) - **Scopes**: Select permissions you need ([see scopes guide](/uipath-typescript/oauth-scopes)) 4. Save and copy the **Client ID** Add the Client ID and other config to your `uipath.json`. The `@uipath/coded-apps-dev` bundler plugin injects these as meta tags during local development; at deploy time the platform injects them automatically. With config in place, initialize the SDK with no arguments β€” it reads everything from the injected meta tags: ``` import { UiPath } from '@uipath/uipath-typescript/core'; const sdk = new UiPath(); await sdk.initialize(); ``` ## Secret-based Authentication ``` import { UiPath } from '@uipath/uipath-typescript/core'; const sdk = new UiPath({ baseUrl: 'https://api.uipath.com', orgName: 'your-organization', tenantName: 'your-tenant', secret: 'your-secret' //PAT Token or Bearer Token }); ``` Using externally obtained tokens If you have backend / external system that handles authentication and token generation, you can pass the token directly to the SDK via the `secret` parameter at initialization. When the token expires, your backend / external system can inject a refreshed token into the same instance via `sdk.updateToken()` to keep it authenticated. In this setup, token lifecycle management stays entirely on your side. To Generate a PAT Token: 1. Log in to [UiPath Cloud](https://cloud.uipath.com) 1. Go to **User Profile** β†’ **Preferences** β†’ **Personal Access Token** 1. Click **Create Token** 1. Give it a name and expiration date 1. Provide relevant scopes ## SDK Initialization - The initialize() Method ### When to Use initialize() The `initialize()` method completes the authentication process for the SDK: - **Secret Authentication**: Auto-initializes when creating the SDK instance - **no need to call initialize()** - **OAuth Authentication**: **MUST call** `await sdk.initialize()` before using any SDK services ### Example: Secret Authentication (Auto-initialized) ``` import { UiPath } from '@uipath/uipath-typescript/core'; import { Tasks } from '@uipath/uipath-typescript/tasks'; const sdk = new UiPath({ baseUrl: 'https://api.uipath.com', orgName: 'your-organization', tenantName: 'your-tenant', secret: 'your-secret' //PAT Token or Bearer Token }); // Ready to use immediately - no initialize() needed const tasks = new Tasks(sdk); const allTasks = await tasks.getAll(); ``` ### Example: OAuth Authentication (Requires initialize) ``` import { UiPath } from '@uipath/uipath-typescript/core'; import { Tasks } from '@uipath/uipath-typescript/tasks'; const sdk = new UiPath({ baseUrl: 'https://api.uipath.com', orgName: 'your-organization', tenantName: 'your-tenant', clientId: 'your-client-id', redirectUri: 'http://localhost:3000', scope: 'your-scopes' }); // Must initialize before using services try { await sdk.initialize(); console.log('SDK initialized successfully'); // Now you can use the SDK const tasks = new Tasks(sdk); const allTasks = await tasks.getAll(); } catch (error) { console.error('Failed to initialize SDK:', error); } ``` ## OAuth Integration Patterns ### Auto-login on App Load ``` import { UiPath } from '@uipath/uipath-typescript/core'; const sdk = new UiPath({...oauthConfig}); useEffect(() => { const initSDK = async () => { await sdk.initialize(); }; initSDK(); }, []); ``` ### User-Triggered Login ``` import { UiPath } from '@uipath/uipath-typescript/core'; const sdk = new UiPath({...oauthConfig}); const onLogin = async () => { await sdk.initialize(); }; // Handle OAuth callback const oauthCompleted = useRef(false); useEffect(() => { if (sdk.isInitialized() && !oauthCompleted.current) { oauthCompleted.current = true; sdk.completeOAuth(); } }, []); ``` ### Available Auth Methods - `sdk.initialize()` - Start OAuth flow (auto completes also based on callback state) - `sdk.isInitialized()` - Check if SDK initialization completed - `sdk.isAuthenticated()` - Check if user has valid token - `sdk.isInOAuthCallback()` - Check if processing OAuth redirect - `sdk.completeOAuth()` - Manually complete OAuth (advanced use) - `sdk.getToken()` - Get the logged-in user's access token - `sdk.logout()` - Logout and clear all authentication state (requires re-initialization to authenticate again) - `sdk.updateToken()` - Inject a refreshed token into the SDK instance (useful for backend services managing token lifecycle) ## Quick Test Script Create `.env` file: ``` # .env UIPATH_BASE_URL=https://api.uipath.com UIPATH_ORG_NAME=your-organization-name UIPATH_TENANT_NAME=your-tenant-name UIPATH_SECRET=your-pat-token ``` Verify your authentication setup: ``` // test-auth.ts import 'dotenv/config'; import { UiPath } from '@uipath/uipath-typescript/core'; import { Assets } from '@uipath/uipath-typescript/assets'; async function testAuthentication() { const sdk = new UiPath({ baseUrl: process.env.UIPATH_BASE_URL!, orgName: process.env.UIPATH_ORG_NAME!, tenantName: process.env.UIPATH_TENANT_NAME!, secret: process.env.UIPATH_SECRET! }); try { // Test with a simple API call const assets = new Assets(sdk); const allAssets = await assets.getAll(); console.log('Authentication successful!'); console.log(`Connected to ${process.env.UIPATH_ORG_NAME}/${process.env.UIPATH_TENANT_NAME}`); console.log(`Found ${allAssets.items.length} assets`); } catch (error) { console.error('Authentication failed:'); console.error(error.message); } } testAuthentication(); ``` Run it: `npx ts-node test-auth.ts` # Pagination ## Overview The SDK supports two pagination approaches: 1. **Cursor-based Navigation**: Use opaque cursors to navigate between pages 1. **Page Jump**: Jump directly to specific page numbers (when supported) [β†— Refer to the Quick Reference Table](#quick-reference-table) You can specify either cursor OR jumpToPage, but **not** both. All paginated methods return a `PaginatedResponse` when pagination parameters are provided, or a `NonPaginatedResponse` when no pagination parameters are specified. ## Types ### [PaginationOptions](/uipath-typescript/api/type-aliases/PaginationOptions) ``` type PaginationOptions = { pageSize?: number; // Size of the page to fetch (items per page) cursor?: string; // Opaque string containing all information needed to fetch next page jumpToPage?: number; // Direct page number navigation } ``` ### [PaginatedResponse](/uipath-typescript/api/interfaces/PaginatedResponse) ``` interface PaginatedResponse { items: T[]; // The items in the current page totalCount?: number; // Total count of items across all pages (if available) hasNextPage: boolean; // Whether more pages are available nextCursor?: PaginationCursor; // Cursor to fetch the next page (if available) previousCursor?: PaginationCursor; // Cursor to fetch the previous page (if available) currentPage?: number; // Current page number (1-based, if available) totalPages?: number; // Total number of pages (if available) supportsPageJump: boolean; // Whether this pagination type supports jumping to arbitrary pages } ``` ## Usage Examples ### Basic Pagination ``` import { Assets } from '@uipath/uipath-typescript/assets'; const assets = new Assets(sdk); // Get first page with 10 items const firstPage = await assets.getAll({ pageSize: 10 }); console.log(`Got ${firstPage.items.length} items`); console.log(`Total items: ${firstPage.totalCount}`); console.log(`Has next page: ${firstPage.hasNextPage}`); ``` ### Cursor-based Navigation ``` import { Assets, AssetGetResponse } from '@uipath/uipath-typescript/assets'; import { PaginatedResponse } from '@uipath/uipath-typescript/core'; const assets = new Assets(sdk); // Navigate through pages using cursors let currentPage = await assets.getAll({ pageSize: 10 }) as PaginatedResponse; while (currentPage.hasNextPage) { // Process current page items currentPage.items.forEach(item => console.log(item.name)); // Get next page using cursor currentPage = await assets.getAll({ cursor: currentPage.nextCursor }) as PaginatedResponse; } ``` ### Page Jumping ``` import { Assets } from '@uipath/uipath-typescript/assets'; const assets = new Assets(sdk); // Jump directly to page 5 (when supported) const page5 = await assets.getAll({ jumpToPage: 5, pageSize: 20 }); // Check if page jumping is supported if (page5.supportsPageJump) { console.log(`Currently on page ${page5.currentPage} of ${page5.totalPages}`); } ``` ### Non-paginated Requests ``` import { Assets } from '@uipath/uipath-typescript/assets'; const assets = new Assets(sdk); // Get all items without pagination const allAssets = await assets.getAll(); console.log(`Retrieved ${allAssets.items.length} assets`); console.log(`Total count: ${allAssets.totalCount}`); ``` ## Quick Reference Table | Service | Method | Supports `jumpToPage`? | | --------------------------------- | -------------------------- | ---------------------- | | Agents | `getAll()` | βœ… Yes | | Agents | `getErrors()` | βœ… Yes | | Agent Traces | `getSpansByReference()` | βœ… Yes | | Agent Traces | `getGovernanceDecisions()` | βœ… Yes | | Assets | `getAll()` | βœ… Yes | | Buckets | `getAll()` | βœ… Yes | | Buckets | `getFiles()` | βœ… Yes | | Jobs | `getAll()` | βœ… Yes | | Entities | `getAll()` | βœ… Yes | | Entities | `getAllRecords()` | βœ… Yes | | Entities | `queryRecordsById()` | βœ… Yes | | Processes | `getAll()` | βœ… Yes | | ProcessInstances | `getAll()` | ❌ No | | CaseInstances | `getAll()` | ❌ No | | CaseInstances | `getActionTasks()` | βœ… Yes | | CaseInstances | `getSlaSummary()` | βœ… Yes | | Queues | `getAll()` | βœ… Yes | | Tasks | `getAll()` | βœ… Yes | | Tasks | `getUsers()` | βœ… Yes | | ConversationalAgent.conversations | `getAll()` | ❌ No | | ConversationalAgent.exchanges | `getAll()` | ❌ No | | Feedback | `getAll()` | βœ… Yes | | Feedback | `getCategories()` | βœ… Yes | | Traces | `getById()` | ❌ No | | Traces | `getSpansByIds()` | ❌ No | | Governance | `getPolicyTraces()` | βœ… Yes | # API Reference Service for managing UiPath Assets. Assets are key-value pairs that can be used to store configuration data, credentials, and other settings used by automation processes. [UiPath Assets Guide](https://docs.uipath.com/orchestrator/automation-cloud/latest/user-guide/about-assets) ### Usage ``` import { Assets } from '@uipath/uipath-typescript/assets'; const assets = new Assets(sdk); const allAssets = await assets.getAll(); ``` ## Methods ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`AssetGetResponse`> : `NonPaginatedResponse`\<`AssetGetResponse`>> Gets all assets across folders with optional filtering #### Type Parameters - `T` *extends* `AssetGetAllOptions` = `AssetGetAllOptions` #### Parameters - `options?`: `T` β€” Query options including optional folderId and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`AssetGetResponse`> : `NonPaginatedResponse`\<`AssetGetResponse`>> Promise resolving to either an array of assets NonPaginatedResponse or a PaginatedResponse when pagination options are used. [AssetGetResponse](../AssetGetResponse/) #### Example ``` // Standard array return // With folder const folderAssets = await assets.getAll({ folderId: }); // First page with pagination const page1 = await assets.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await assets.getAll({ cursor: page1.nextCursor }); } // Jump to specific page const page5 = await assets.getAll({ jumpToPage: 5, pageSize: 10 }); ``` ### getById() > **getById**(`id`: `number`, `folderId`: `number`, `options?`: `AssetGetByIdOptions`): `Promise`\<`AssetGetResponse`> Gets a single asset by ID #### Parameters - `id`: `number` β€” Asset ID - `folderId`: `number` β€” Required folder ID - `options?`: `AssetGetByIdOptions` β€” Optional query parameters (expand, select) #### Returns `Promise`\<`AssetGetResponse`> Promise resolving to a single asset [AssetGetResponse](../AssetGetResponse/) #### Example ``` // Get asset by ID const asset = await assets.getById(, ); ``` ### getByName() > **getByName**(`name`: `string`, `options?`: `AssetGetByNameOptions`): `Promise`\<`AssetGetResponse`> Retrieves a single asset by name. #### Parameters - `name`: `string` β€” Asset name to search for - `options?`: `AssetGetByNameOptions` β€” Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`) #### Returns `Promise`\<`AssetGetResponse`> Promise resolving to a single asset [AssetGetResponse](../AssetGetResponse/) #### Example ``` // By folder ID await assets.getByName('ApiKey', { folderId: 123 }); // By folder key (GUID) await assets.getByName('ApiKey', { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // By folder path await assets.getByName('ApiKey', { folderPath: 'Shared/Finance' }); // With expand await assets.getByName('ApiKey', { folderPath: 'Shared/Finance', expand: 'keyValueList' }); ``` ### updateValueById() > **updateValueById**(`id`: `number`, `newValue`: `AssetNewValue`, `options?`: `AssetUpdateValueByIdOptions`): `Promise`\<`void`> Updates the value of an existing asset by ID. Fetches the asset internally to determine its type, then updates only the value while preserving the asset's name, scope, and description. **Supported value types:** `Text`, `Integer`, and `Bool` only. Other types (`Credential`, `Secret`) throw a `ValidationError`. The `newValue` runtime type must match the asset's `valueType`: - `Text` β†’ `string` - `Integer` β†’ `number` (integer) - `Bool` β†’ `boolean` #### Parameters - `id`: `number` β€” Asset ID - `newValue`: `AssetNewValue` β€” New value to apply (string for `Text`, number for `Integer`, boolean for `Bool`) - `options?`: `AssetUpdateValueByIdOptions` β€” Folder scoping (`folderId` / `folderKey` / `folderPath`) #### Returns `Promise`\<`void`> Promise resolving when the asset has been updated #### Example ``` // Update a Text asset by folder ID await assets.updateValueById(, 'new-value', { folderId: }); // Update an Integer asset by folder key (GUID) await assets.updateValueById(, 42, { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // Update a Bool asset by folder path await assets.updateValueById(, true, { folderPath: 'Shared/Finance' }); ``` Service for managing UiPath Orchestrator Jobs. Jobs represent the execution of a process (automation) on a UiPath Robot. Each job tracks the lifecycle of a single process run, including its state, timing, input/output arguments, and associated resources. [UiPath Jobs Guide](https://docs.uipath.com/orchestrator/automation-cloud/latest/user-guide/about-jobs) ### Usage ``` import { Jobs } from '@uipath/uipath-typescript/jobs'; const jobs = new Jobs(sdk); const allJobs = await jobs.getAll(); ``` ## Methods ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`JobGetResponse`> : `NonPaginatedResponse`\<`JobGetResponse`>> Gets all jobs across folders with optional filtering and pagination. Returns jobs with full details including state, timing, and input/output arguments. Pass `folderId` to scope the query to a specific folder. Input and output fields are not included in `getAll` responses The `inputArguments`, `inputFile`, `outputArguments`, and `outputFile` fields will always be `null` in the `getAll` response. To retrieve a job's output, use the [getOutput](#getoutput) method with the job's `key` and `folderId`. #### Type Parameters - `T` *extends* `JobGetAllOptions` = `JobGetAllOptions` #### Parameters - `options?`: `T` β€” Query options including optional folderId, filtering, and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`JobGetResponse`> : `NonPaginatedResponse`\<`JobGetResponse`>> Promise resolving to either an array of jobs [NonPaginatedResponse](../NonPaginatedResponse/)\<[JobGetResponse](../../type-aliases/JobGetResponse/)> or a [PaginatedResponse](../PaginatedResponse/)\<[JobGetResponse](../../type-aliases/JobGetResponse/)> when pagination options are used. [JobGetResponse](../../type-aliases/JobGetResponse/) #### Example ``` // Get all jobs const allJobs = await jobs.getAll(); // Get all jobs in a specific folder const folderJobs = await jobs.getAll({ folderId: }); // With filtering const recentInvoiceJobs = await jobs.getAll({ filter: "processName eq 'InvoiceBot'", orderby: 'createdTime desc', }); // First page with pagination const page1 = await jobs.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await jobs.getAll({ cursor: page1.nextCursor }); } // Jump to specific page const page5 = await jobs.getAll({ jumpToPage: 5, pageSize: 10 }); ``` ### getById() > **getById**(`id`: `string`, `folderId`: `number`, `options?`: `JobGetByIdOptions`): `Promise`\<`JobGetResponse`> Gets a job by its unique key (GUID). Returns the full job details including state, timing, input/output arguments, and error information. Use `expand` to include related entities like `robot`, or `machine`. #### Parameters - `id`: `string` β€” The unique key (GUID) of the job to retrieve - `folderId`: `number` β€” The folder ID where the job resides - `options?`: `JobGetByIdOptions` β€” Optional query options for expanding or selecting fields #### Returns `Promise`\<`JobGetResponse`> Promise resolving to a [JobGetResponse](../../type-aliases/JobGetResponse/) with full job details and bound methods #### Examples ``` // Get a job by key const job = await jobs.getById(, ); console.log(job.state, job.processName); ``` ``` // With expanded related entities const job = await jobs.getById(, , { expand: 'robot,machine' }); console.log(job.robot?.name, job.machine?.name); ``` ### getOutput() > **getOutput**(`jobKey`: `string`, `folderId`: `number`): `Promise`\<`null` | `Record`\<`string`, `unknown`>> Gets the output of a completed job. Retrieves the job's output arguments, handling both inline output (stored directly on the job as a JSON string in `outputArguments`) and file-based output (stored as a blob attachment for large outputs). Returns the parsed JSON output or `null` if the job has no output. #### Parameters - `jobKey`: `string` β€” The unique key (GUID) of the job to retrieve output from - `folderId`: `number` β€” The folder ID where the job resides #### Returns `Promise`\<`null` | `Record`\<`string`, `unknown`>> Promise resolving to the parsed output as `Record`, or `null` if no output exists #### Examples ``` // Get output from a completed job const output = await jobs.getOutput(, ); if (output) { console.log('Job output:', output); } ``` ``` // Get output using bound method (jobKey and folderId are taken from the job object) const allJobs = await jobs.getAll(); const completedJob = allJobs.items.find(j => j.state === JobState.Successful); if (completedJob) { const output = await completedJob.getOutput(); } ``` ### restart() > **restart**(`jobKey`: `string`, `folderId`: `number`): `Promise`\<`JobGetResponse`> Restarts a job in a final state (Successful, Faulted, or Stopped). Creates a **new** job execution from a previously successful, faulted, or stopped job. The new job has its own unique `key`, starts in `Pending` state, and uses the same process and input arguments as the original job. To monitor the new job's progress, poll with [getById](#getbyid) using the returned job's key until the state reaches a final value. #### Parameters - `jobKey`: `string` β€” The unique key (GUID) of the job to restart - `folderId`: `number` β€” The folder ID where the job resides #### Returns `Promise`\<`JobGetResponse`> Promise resolving to the new [JobGetResponse](../../type-aliases/JobGetResponse/) with full job details #### Example ``` // Restart a faulted job const newJob = await jobs.restart(, ); console.log(newJob.state); // 'Pending' console.log(newJob.key); // new job key (different from original) ``` ### resume() > **resume**(`jobKey`: `string`, `folderId`: `number`, `options?`: `JobResumeOptions`): `Promise`\<`void`> Resumes a suspended job. Sends a resume request to a job that is currently in the `Suspended` state. The job transitions to `Resumed` and then to `Running` as it continues execution. Optionally pass input arguments to provide data for the resumed workflow. #### Parameters - `jobKey`: `string` β€” The unique key (GUID) of the suspended job to resume - `folderId`: `number` β€” The folder ID where the job resides - `options?`: `JobResumeOptions` β€” Optional parameters including input arguments #### Returns `Promise`\<`void`> Promise that resolves when the job is resumed successfully, or rejects on failure #### Examples ``` // Resume a suspended job await jobs.resume(, ); ``` ``` // Resume with input arguments await jobs.resume(, , { inputArguments: { approved: true } }); ``` ### stop() > **stop**(`jobKeys`: `string`[], `folderId`: `number`, `options?`: `JobStopOptions`): `Promise`\<`void`> Stops one or more jobs by their UUID keys. Sends a stop request for the specified jobs to the Orchestrator. Throws if any keys cannot be resolved. #### Parameters - `jobKeys`: `string`[] β€” Array of job UUID keys to stop (e.g., from [JobGetResponse](../../type-aliases/JobGetResponse/).key) - `folderId`: `number` β€” The folder ID where the jobs reside (required) - `options?`: `JobStopOptions` β€” Optional [JobStopOptions](../JobStopOptions/) including stop strategy #### Returns `Promise`\<`void`> Promise that resolves when the jobs are stopped successfully, or rejects on failure #### Examples ``` // Stop a single job with default soft stop await jobs.stop([], ); ``` ``` import { StopStrategy } from '@uipath/uipath-typescript/jobs'; // Force-kill multiple jobs await jobs.stop( [, ], , { strategy: StopStrategy.Kill } ); ``` Service for managing and executing UiPath Automation Processes. Processes (also known as automations or workflows) are the core units of automation in UiPath, representing sequences of activities that perform specific business tasks. [UiPath Processes Guide](https://docs.uipath.com/orchestrator/automation-cloud/latest/user-guide/about-processes) ### Usage ``` import { Processes } from '@uipath/uipath-typescript/processes'; const processes = new Processes(sdk); const allProcesses = await processes.getAll(); ``` ## Methods ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`ProcessGetResponse`> : `NonPaginatedResponse`\<`ProcessGetResponse`>> Gets all processes across folders with optional filtering Returns a NonPaginatedResponse with data and totalCount when no pagination parameters are provided, or a PaginatedResponse when any pagination parameter is provided #### Type Parameters - `T` *extends* `ProcessGetAllOptions` = `ProcessGetAllOptions` #### Parameters - `options?`: `T` β€” Query options including optional folderId and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`ProcessGetResponse`> : `NonPaginatedResponse`\<`ProcessGetResponse`>> Promise resolving to either an array of processes NonPaginatedResponse or a PaginatedResponse when pagination options are used. [ProcessGetResponse](../ProcessGetResponse/) #### Example ``` // Standard array return const allProcesses = await processes.getAll(); // Get processes within a specific folder const folderProcesses = await processes.getAll({ folderId: }); // Get processes with filtering const filteredProcesses = await processes.getAll({ filter: "name eq 'MyProcess'" }); // First page with pagination const page1 = await processes.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await processes.getAll({ cursor: page1.nextCursor }); } // Jump to specific page const page5 = await processes.getAll({ jumpToPage: 5, pageSize: 10 }); ``` ### getById() > **getById**(`id`: `number`, `folderId`: `number`, `options?`: `ProcessGetByIdOptions`): `Promise`\<`ProcessGetResponse`> Gets a single process by ID #### Parameters - `id`: `number` β€” Process ID - `folderId`: `number` β€” Required folder ID - `options?`: `ProcessGetByIdOptions` β€” Optional query parameters #### Returns `Promise`\<`ProcessGetResponse`> Promise resolving to a single process [ProcessGetResponse](../ProcessGetResponse/) #### Example ``` // Get process by ID const process = await processes.getById(, ); ``` ### getByName() > **getByName**(`name`: `string`, `options?`: `ProcessGetByNameOptions`): `Promise`\<`ProcessGetResponse`> Retrieves a single process by name. #### Parameters - `name`: `string` β€” Process name to search for - `options?`: `ProcessGetByNameOptions` β€” Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`) #### Returns `Promise`\<`ProcessGetResponse`> Promise resolving to a single process [ProcessGetResponse](../ProcessGetResponse/) #### Example ``` // By folder ID await processes.getByName('MyProcess', { folderId: 123 }); // By folder key (GUID) await processes.getByName('MyProcess', { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // By folder path await processes.getByName('MyProcess', { folderPath: 'Shared/Finance' }); // With expand await processes.getByName('MyProcess', { folderPath: 'Shared/Finance', expand: 'entryPoints' }); ``` ### start() #### Call Signature > **start**(`request`: `ProcessStartRequest`, `options?`: `ProcessStartOptions`): `Promise`\<`ProcessStartResponse`[]> Starts a process with the specified configuration. Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` inside the options. ##### Parameters | Parameter | Type | Description | | ---------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `request` | `ProcessStartRequest` | Process start configuration | | `options?` | `ProcessStartOptions` | Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`, `filter`, `orderby`) | ##### Returns `Promise`\<`ProcessStartResponse`[]> Promise resolving to array of started process instances [ProcessStartResponse](../ProcessStartResponse/) ##### Example ``` // By folder ID await processes.start({ processKey: '' }, { folderId: }); // By folder key (GUID) await processes.start({ processKey: '' }, { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // By folder path await processes.start({ processKey: '' }, { folderPath: 'Shared/Finance' }); // Start by process name (instead of processKey) await processes.start({ processName: 'MyProcess' }, { folderId: }); // With additional options await processes.start({ processKey: '' }, { folderId: , expand: 'Robot' }); ``` #### Call Signature > **start**(`request`: `ProcessStartRequest`, `folderId`: `number`, `options?`: `RequestOptions`): `Promise`\<`ProcessStartResponse`[]> Starts a process β€” positional `folderId` form. ##### Parameters | Parameter | Type | Description | | ---------- | --------------------- | ---------------------------- | | `request` | `ProcessStartRequest` | Process start configuration | | `folderId` | `number` | Required folder ID (numeric) | | `options?` | `RequestOptions` | Optional request options | ##### Returns `Promise`\<`ProcessStartResponse`[]> Promise resolving to array of started process instances [ProcessStartResponse](../ProcessStartResponse/) ##### Deprecated Use the options-object form: `start(request, { folderId })`. See [ProcessStartOptions](../ProcessStartOptions/) for the supported options. Service for managing UiPath Queues Queues are a fundamental component of UiPath automation that enable distributed and scalable processing of work items. [UiPath Queues Guide](https://docs.uipath.com/orchestrator/automation-cloud/latest/user-guide/about-queues-and-transactions) ### Usage ``` import { Queues } from '@uipath/uipath-typescript/queues'; const queues = new Queues(sdk); const allQueues = await queues.getAll(); ``` ## Methods ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`QueueGetResponse`> : `NonPaginatedResponse`\<`QueueGetResponse`>> Gets all queues across folders with optional filtering and folder scoping #### Type Parameters - `T` *extends* `QueueGetAllOptions` = `QueueGetAllOptions` #### Parameters - `options?`: `T` β€” Query options including optional folderId and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`QueueGetResponse`> : `NonPaginatedResponse`\<`QueueGetResponse`>> Promise resolving to either an array of queues NonPaginatedResponse or a PaginatedResponse when pagination options are used. [QueueGetResponse](../QueueGetResponse/) #### Signature getAll(options?) β†’ Promise\ #### Example ``` // Standard array return const allQueues = await queues.getAll(); // Get queues within a specific folder const folderQueues = await queues.getAll({ folderId: }); // Get queues with filtering const filteredQueues = await queues.getAll({ filter: "name eq 'MyQueue'" }); // First page with pagination const page1 = await queues.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await queues.getAll({ cursor: page1.nextCursor }); } // Jump to specific page const page5 = await queues.getAll({ jumpToPage: 5, pageSize: 10 }); ``` ### getById() > **getById**(`id`: `number`, `folderId`: `number`, `options?`: `QueueGetByIdOptions`): `Promise`\<`QueueGetResponse`> Gets a single queue by ID #### Parameters - `id`: `number` β€” Queue ID - `folderId`: `number` β€” Required folder ID - `options?`: `QueueGetByIdOptions` β€” - #### Returns `Promise`\<`QueueGetResponse`> Promise resolving to a queue definition #### Example ``` // Get queue by ID const queue = await queues.getById(, ); ``` Service for managing UiPath storage Buckets. Buckets are cloud storage containers that can be used to store and manage files used by automation processes. [UiPath Buckets Guide](https://docs.uipath.com/orchestrator/automation-cloud/latest/user-guide/about-storage-buckets) ### Usage ``` import { Buckets } from '@uipath/uipath-typescript/buckets'; const buckets = new Buckets(sdk); const allBuckets = await buckets.getAll(); ``` ## Methods ### deleteFile() > **deleteFile**(`bucketId`: `number`, `path`: `string`, `options?`: `BucketDeleteFileOptions`): `Promise`\<`void`> Deletes a file from a bucket #### Parameters - `bucketId`: `number` β€” The ID of the bucket - `path`: `string` β€” The full path to the file to delete - `options?`: `BucketDeleteFileOptions` β€” Folder scoping (`folderId` / `folderKey` / `folderPath`) #### Returns `Promise`\<`void`> Promise resolving when the file is deleted #### Example ``` // Delete a file from a bucket await buckets.deleteFile(, '/folder/file.pdf', { folderId: }); ``` ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BucketGetResponse`> : `NonPaginatedResponse`\<`BucketGetResponse`>> Gets all buckets across folders with optional filtering The method returns either: - A NonPaginatedResponse with data and totalCount (when no pagination parameters are provided) - A paginated result with navigation cursors (when any pagination parameter is provided) #### Type Parameters - `T` *extends* `BucketGetAllOptions` = `BucketGetAllOptions` #### Parameters - `options?`: `T` β€” Query options including optional folderId and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BucketGetResponse`> : `NonPaginatedResponse`\<`BucketGetResponse`>> Promise resolving to either an array of buckets NonPaginatedResponse or a PaginatedResponse when pagination options are used. [BucketGetResponse](../BucketGetResponse/) #### Example ``` // Get all buckets across folders const allBuckets = await buckets.getAll(); // Get buckets within a specific folder const folderBuckets = await buckets.getAll({ folderId: }); // Get buckets with filtering const filteredBuckets = await buckets.getAll({ filter: "name eq 'MyBucket'" }); // First page with pagination const page1 = await buckets.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await buckets.getAll({ cursor: page1.nextCursor }); } // Jump to specific page const page5 = await buckets.getAll({ jumpToPage: 5, pageSize: 10 }); ``` ### getById() > **getById**(`bucketId`: `number`, `folderId`: `number`, `options?`: `BucketGetByIdOptions`): `Promise`\<`BucketGetResponse`> Gets a single bucket by ID #### Parameters - `bucketId`: `number` β€” Bucket ID - `folderId`: `number` β€” Required folder ID - `options?`: `BucketGetByIdOptions` β€” Optional query parameters #### Returns `Promise`\<`BucketGetResponse`> Promise resolving to a bucket definition [BucketGetResponse](../BucketGetResponse/) #### Example ``` // Get bucket by ID const bucket = await buckets.getById(, ); ``` ### getByName() > **getByName**(`name`: `string`, `options?`: `BucketGetByNameOptions`): `Promise`\<`BucketGetResponse`> Retrieves a single orchestrator storage bucket by name. #### Parameters - `name`: `string` β€” Bucket name to search for - `options?`: `BucketGetByNameOptions` β€” Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`) #### Returns `Promise`\<`BucketGetResponse`> Promise resolving to a single bucket [BucketGetResponse](../BucketGetResponse/) #### Example ``` // By folder ID await buckets.getByName('MyBucket', { folderId: }); // By folder key (GUID) await buckets.getByName('MyBucket', { folderKey: '' }); // By folder path await buckets.getByName('MyBucket', { folderPath: '' }); ``` ### getFileMetaData() #### Call Signature > **getFileMetaData**\<`T`>(`bucketId`: `number`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BlobItem`> : `NonPaginatedResponse`\<`BlobItem`>> Gets metadata for files in a bucket with optional filtering and pagination. Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` inside the options. The method returns either: - A NonPaginatedResponse with items array (when no pagination parameters are provided) - A PaginatedResponse with navigation cursors (when any pagination parameter is provided) ##### Type Parameters | Type Parameter | Default type | | ---------------------------------------------------------- | -------------------------------------------- | | `T` *extends* `BucketGetFileMetaDataWithPaginationOptions` | `BucketGetFileMetaDataWithPaginationOptions` | ##### Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------------------------------------------- | | `bucketId` | `number` | The ID of the bucket to get file metadata from | | `options?` | `T` | Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional parameters for filtering and pagination | ##### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BlobItem`> : `NonPaginatedResponse`\<`BlobItem`>> Promise resolving to either an array of files metadata NonPaginatedResponse or a PaginatedResponse when pagination options are used. [BlobItem](../BlobItem/) ##### Example ``` // By folder ID const fileMetadata = await buckets.getFileMetaData(, { folderId: }); // By folder key (GUID) await buckets.getFileMetaData(, { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // By folder path await buckets.getFileMetaData(, { folderPath: 'Shared/Finance' }); // Filter by prefix await buckets.getFileMetaData(, { folderId: , prefix: '/folder1' }); // First page with pagination const page1 = await buckets.getFileMetaData(, { folderId: , pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await buckets.getFileMetaData(, { folderId: , cursor: page1.nextCursor }); } ``` #### Call Signature > **getFileMetaData**\<`T`>(`bucketId`: `number`, `folderId`: `number`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BlobItem`> : `NonPaginatedResponse`\<`BlobItem`>> Gets metadata for files in a bucket β€” positional `folderId` form. ##### Type Parameters | Type Parameter | Default type | | ---------------------------------------------------------- | -------------------------------------------- | | `T` *extends* `BucketGetFileMetaDataWithPaginationOptions` | `BucketGetFileMetaDataWithPaginationOptions` | ##### Parameters | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------ | | `bucketId` | `number` | The ID of the bucket to get file metadata from | | `folderId` | `number` | Required folder ID (numeric) | | `options?` | `T` | Optional parameters for filtering and pagination | ##### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BlobItem`> : `NonPaginatedResponse`\<`BlobItem`>> Promise resolving to either an array of files metadata NonPaginatedResponse or a PaginatedResponse when pagination options are used. [BlobItem](../BlobItem/) ##### Deprecated Use the options-object form: `getFileMetaData(bucketId, { folderId })`. See [BucketGetFileMetaDataWithPaginationOptions](../../type-aliases/BucketGetFileMetaDataWithPaginationOptions/) for the supported options. ### getFiles() > **getFiles**\<`T`>(`bucketId`: `number`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BucketFile`> : `NonPaginatedResponse`\<`BucketFile`>> Lists all files in a bucket. Returns a flat, recursive listing of all files in the bucket. Supports regex filtering and filter / orderby / select / expand. [BucketFile](../BucketFile/) entries include `isDirectory` so callers can distinguish folders from files. The method returns either: - A NonPaginatedResponse with items array (when no pagination parameters are provided) - A PaginatedResponse with navigation cursors (when any pagination parameter is provided) #### Type Parameters - `T` *extends* `BucketGetFilesOptions` = `BucketGetFilesOptions` #### Parameters - `bucketId`: `number` β€” The ID of the bucket - `options?`: `T` β€” Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional parameters for regex filtering, query options, and pagination [BucketGetFilesOptions](../../type-aliases/BucketGetFilesOptions/) #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`BucketFile`> : `NonPaginatedResponse`\<`BucketFile`>> Promise resolving to either an array of files NonPaginatedResponse or a PaginatedResponse when pagination options are used. [BucketFile](../BucketFile/) #### Example ``` // List all files in the bucket const files = await buckets.getFiles(, { folderId: }); // Filter by regex pattern const pdfs = await buckets.getFiles(, { folderId: , fileNameRegex: '.*\\.pdf$' }); // First page with pagination const page1 = await buckets.getFiles(, { folderId: , pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await buckets.getFiles(, { folderId: , cursor: page1.nextCursor }); } // Jump to specific page const page5 = await buckets.getFiles(, { folderId: , jumpToPage: 5, pageSize: 10 }); ``` ### getReadUri() #### Call Signature > **getReadUri**(`bucketId`: `number`, `path`: `string`, `options?`: `BucketGetReadUriRequestOptions`): `Promise`\<`BucketGetUriResponse`> Gets a direct download URL for a file in the bucket. Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` in the options. ##### Parameters | Parameter | Type | Description | | ---------- | -------------------------------- | --------------------------------------------------------------------------------------- | | `bucketId` | `number` | The ID of the bucket | | `path` | `string` | The full path to the file | | `options?` | `BucketGetReadUriRequestOptions` | Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional `expiryInMinutes` | ##### Returns `Promise`\<`BucketGetUriResponse`> Promise resolving to blob file access information [BucketGetUriResponse](../BucketGetUriResponse/) ##### Example ``` // By folder ID await buckets.getReadUri(, '/folder/file.pdf', { folderId: }); // By folder key (GUID) await buckets.getReadUri(, '/folder/file.pdf', { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // By folder path await buckets.getReadUri(, '/folder/file.pdf', { folderPath: 'Shared/Finance' }); ``` #### Call Signature > **getReadUri**(`options`: `BucketGetReadUriOptions`): `Promise`\<`BucketGetUriResponse`> Gets a direct download URL for a file in the bucket β€” options-only form. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------- | --------------------------------------------------------------------------------------------------------------- | | `options` | `BucketGetReadUriOptions` | Contains bucketId, folder scoping (`folderId` / `folderKey` / `folderPath`), file path and optional expiry time | ##### Returns `Promise`\<`BucketGetUriResponse`> Promise resolving to blob file access information [BucketGetUriResponse](../BucketGetUriResponse/) ##### Deprecated Use the positional form: `getReadUri(bucketId, path, options?)`. See [BucketGetReadUriRequestOptions](../BucketGetReadUriRequestOptions/) for the supported options. ### uploadFile() #### Call Signature > **uploadFile**(`bucketId`: `number`, `path`: `string`, `content`: `Uint8Array`\<`ArrayBuffer`> | `Blob` | `File`, `options?`: `BucketUploadFileRequestOptions`): `Promise`\<`BucketUploadResponse`> Uploads a file to a bucket. Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` in the options. ##### Parameters | Parameter | Type | Description | | ---------- | -------------------------------- | -------------------------------------------------------- | | `bucketId` | `number` | The ID of the bucket to upload to | | `path` | `string` | Path where the file should be stored in the bucket | | `content` | `Uint8Array`\<`ArrayBuffer`> | `Blob` | | `options?` | `BucketUploadFileRequestOptions` | Folder scoping (`folderId` / `folderKey` / `folderPath`) | ##### Returns `Promise`\<`BucketUploadResponse`> Promise resolving bucket upload response [BucketUploadResponse](../BucketUploadResponse/) ##### Example ``` // By folder ID const file = new File(['file content'], 'example.txt'); await buckets.uploadFile(, '/folder/example.txt', file, { folderId: }); // By folder key (GUID) await buckets.uploadFile(, '/folder/example.txt', file, { folderKey: '5f6dadf1-3677-49dc-8aca-c2999dd4b3ba' }); // By folder path await buckets.uploadFile(, '/folder/example.txt', file, { folderPath: 'Shared/Finance' }); // In Node env with Uint8Array or Buffer const content = new TextEncoder().encode('file content'); await buckets.uploadFile(, '/folder/example.txt', content, { folderId: }); ``` #### Call Signature > **uploadFile**(`options`: `BucketUploadFileOptions`): `Promise`\<`BucketUploadResponse`> Uploads a file to a bucket β€” options-only form. ##### Parameters | Parameter | Type | Description | | --------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `options` | `BucketUploadFileOptions` | Options for file upload including bucket ID, folder scoping (`folderId` / `folderKey` / `folderPath`), path, and content | ##### Returns `Promise`\<`BucketUploadResponse`> Promise resolving bucket upload response [BucketUploadResponse](../BucketUploadResponse/) ##### Deprecated Use the positional form: `uploadFile(bucketId, path, content, options?)`. See [BucketUploadFileRequestOptions](../BucketUploadFileRequestOptions/) for the supported options. Service for managing UiPath Action Center Tasks are task-based automation components that can be integrated into applications and processes. They represent discrete units of work that can be triggered and monitored through the UiPath API. [UiPath Action Center Guide](https://docs.uipath.com/automation-cloud/docs/actions) ### Usage ``` import { Tasks } from '@uipath/uipath-typescript/tasks'; const tasks = new Tasks(sdk); const allTasks = await tasks.getAll(); ``` ## Methods ### assign() > **assign**(`options`: `TaskAssignmentOptions` | `TaskAssignmentOptions`[]): `Promise`\<`OperationResponse`\<`TaskAssignmentOptions`[] | `TaskAssignmentResponse`[]>> Assigns tasks to users #### Parameters - `options`: `TaskAssignmentOptions` | `TaskAssignmentOptions`[] β€” Single task assignment or array of task assignments #### Returns `Promise`\<`OperationResponse`\<`TaskAssignmentOptions`[] | `TaskAssignmentResponse`[]>> Promise resolving to array of task assignment results [TaskAssignmentResponse](../TaskAssignmentResponse/) #### Examples ``` // Assign a single task to a user by ID const result = await tasks.assign({ taskId: , userId: }); // Or using instance method const task = await tasks.getById(); const result = await task.assign({ userId: }); // Assign a single task to a user by email const result = await tasks.assign({ taskId: , userNameOrEmail: "user@example.com" }); // Assign multiple tasks const result = await tasks.assign([ { taskId: , userId: }, { taskId: , userNameOrEmail: "user@example.com" } ]); ``` ``` import { TaskAssignmentCriteria } from '@uipath/uipath-typescript/tasks'; // Assign to a directory group by userId + criteria β€” Action Center // distributes the task across the group's members based on the criteria const result = await tasks.assign({ taskId: , userId: , // a DirectoryGroup id from tasks.getUsers() assignmentCriteria: TaskAssignmentCriteria.AllUsers }); // ...or identify the group by name instead of id const result2 = await tasks.assign({ taskId: , userNameOrEmail: "", assignmentCriteria: TaskAssignmentCriteria.AllUsers }); ``` ### complete() > **complete**(`options`: `TaskCompletionOptions`, `folderId`: `number`): `Promise`\<`OperationResponse`\<`TaskCompletionOptions`>> Completes a task with the specified type and data #### Parameters - `options`: `TaskCompletionOptions` β€” The completion options including task type, taskId, data, and action - `folderId`: `number` β€” Required folder ID #### Returns `Promise`\<`OperationResponse`\<`TaskCompletionOptions`>> Promise resolving to completion result [TaskCompleteOptions](../../type-aliases/TaskCompleteOptions/) #### Example ``` // Complete an app task await tasks.complete({ type: TaskType.App, taskId: , data: {}, action: "submit" }, ); // folderId is required // Complete an external task await tasks.complete({ type: TaskType.External, taskId: }, ); // folderId is required ``` ### create() > **create**(`options`: `TaskCreateOptions`, `folderId`: `number`): `Promise`\<`TaskCreateResponse`> Creates a new task #### Parameters - `options`: `TaskCreateOptions` β€” The task to be created - `folderId`: `number` β€” Required folder ID #### Returns `Promise`\<`TaskCreateResponse`> Promise resolving to the created task [TaskCreateResponse](../../type-aliases/TaskCreateResponse/) #### Example ``` import { TaskPriority } from '@uipath/uipath-typescript'; const task = await tasks.create({ title: "My Task", priority: TaskPriority.Medium }, ); // folderId is required ``` ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`TaskGetResponse`> : `NonPaginatedResponse`\<`TaskGetResponse`>> Gets all tasks across folders with optional filtering #### Type Parameters - `T` *extends* `TaskGetAllOptions` = `TaskGetAllOptions` #### Parameters - `options?`: `T` β€” Query options including optional folderId, asTaskAdmin flag and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`TaskGetResponse`> : `NonPaginatedResponse`\<`TaskGetResponse`>> Promise resolving to either an array of tasks NonPaginatedResponse or a PaginatedResponse when pagination options are used. [TaskGetResponse](../../type-aliases/TaskGetResponse/) #### Example ``` // Standard array return const allTasks = await tasks.getAll(); // Get tasks within a specific folder const folderTasks = await tasks.getAll({ folderId: 123 }); // Get tasks with admin permissions // This fetches tasks across folders where the user has Task.View, Task.Edit and TaskAssignment.Create permissions const adminTasks = await tasks.getAll({ asTaskAdmin: true }); // Get tasks without admin permissions (default) // This fetches tasks across folders where the user has Task.View and Task.Edit permissions const userTasks = await tasks.getAll({ asTaskAdmin: false }); // First page with pagination const page1 = await tasks.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await tasks.getAll({ cursor: page1.nextCursor }); } // Jump to specific page const page5 = await tasks.getAll({ jumpToPage: 5, pageSize: 10 }); ``` ### getById() > **getById**(`id`: `number`, `options?`: `TaskGetByIdOptions`, `folderId?`: `number`): `Promise`\<`TaskGetResponse`> Gets a task by ID #### Parameters - `id`: `number` β€” The ID of the task to retrieve - `options?`: `TaskGetByIdOptions` β€” Optional query parameters including taskType for faster retrieval [TaskGetByIdOptions](../TaskGetByIdOptions/) - `folderId?`: `number` β€” Optional folder ID (REQUIRED when options.taskType is provided) #### Returns `Promise`\<`TaskGetResponse`> Promise resolving to the task [TaskGetResponse](../../type-aliases/TaskGetResponse/) #### Example ``` // Get a task by ID const task = await tasks.getById(); // Get a form task by ID const formTask = await tasks.getById(, {}, ); // Access form task properties console.log(formTask.formLayout); // Get a document validation task by ID (faster with taskType provided in the options) const dvTask = await tasks.getById(, { taskType: TaskType.DocumentValidation }, ); ``` ### getUsers() > **getUsers**\<`T`>(`folderId`: `number`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`UserLoginInfo`> : `NonPaginatedResponse`\<`UserLoginInfo`>> Gets task users (users, robots, groups etc) in the given folder who have Tasks.View and Tasks.Edit permissions Returns a NonPaginatedResponse with data and totalCount when no pagination parameters are provided, or a PaginatedResponse when any pagination parameter is provided #### Type Parameters - `T` *extends* `TaskGetUsersOptions` = `TaskGetUsersOptions` #### Parameters - `folderId`: `number` β€” The folder ID to get task users from - `options?`: `T` β€” Optional query and pagination parameters #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`UserLoginInfo`> : `NonPaginatedResponse`\<`UserLoginInfo`>> Promise resolving to either an array of task users NonPaginatedResponse or a PaginatedResponse when pagination options are used. [UserLoginInfo](../UserLoginInfo/) #### Example ``` // Get task users from a folder const users = await tasks.getUsers(); // Access user properties console.log(users.items[0].name); console.log(users.items[0].emailAddress); ``` ### reassign() > **reassign**(`options`: `TaskAssignmentOptions` | `TaskAssignmentOptions`[]): `Promise`\<`OperationResponse`\<`TaskAssignmentOptions`[] | `TaskAssignmentResponse`[]>> Reassigns tasks to new users #### Parameters - `options`: `TaskAssignmentOptions` | `TaskAssignmentOptions`[] β€” Single task assignment or array of task assignments #### Returns `Promise`\<`OperationResponse`\<`TaskAssignmentOptions`[] | `TaskAssignmentResponse`[]>> Promise resolving to array of task assignment results [TaskAssignmentResponse](../TaskAssignmentResponse/) #### Examples ``` // Reassign a single task to a user by ID const result = await tasks.reassign({ taskId: , userId: }); // Or using instance method const task = await tasks.getById(); const result = await task.reassign({ userId: }); // Reassign a single task to a user by email const result = await tasks.reassign({ taskId: , userNameOrEmail: "user@example.com" }); // Reassign multiple tasks const result = await tasks.reassign([ { taskId: , userId: }, { taskId: , userNameOrEmail: "user@example.com" } ]); ``` ``` import { TaskAssignmentCriteria } from '@uipath/uipath-typescript/tasks'; // Reassign to a directory group by userId + criteria const result = await tasks.reassign({ taskId: , userId: , // a DirectoryGroup id from tasks.getUsers() assignmentCriteria: TaskAssignmentCriteria.AllUsers }); // ...or identify the group by name instead of id const result2 = await tasks.reassign({ taskId: , userNameOrEmail: "", assignmentCriteria: TaskAssignmentCriteria.AllUsers }); ``` ### unassign() > **unassign**(`taskId`: `number` | `number`[]): `Promise`\<`OperationResponse`\<`TaskAssignmentResponse`[] | { `taskId`: `number`; }[]>> Unassigns tasks (removes current assignees) #### Parameters - `taskId`: `number` | `number`[] β€” Single task ID or array of task IDs to unassign #### Returns `Promise`\<`OperationResponse`\<`TaskAssignmentResponse`[] | { `taskId`: `number`; }[]>> Promise resolving to array of task assignment results [TaskAssignmentResponse](../TaskAssignmentResponse/) #### Example ``` // Unassign a single task const result = await tasks.unassign(); // Or using instance method const task = await tasks.getById(); const result = await task.unassign(); // Unassign multiple tasks const result = await tasks.unassign([, , ]); ``` Service for managing UiPath Orchestrator Attachments. Attachments are files that can be associated with Orchestrator jobs. ## Methods ### getById() > **getById**(`id`: `string`, `options?`: `AttachmentGetByIdOptions`): `Promise`\<`AttachmentResponse`> Gets an attachment by ID #### Parameters - `id`: `string` β€” The UUID of the attachment to retrieve - `options?`: `AttachmentGetByIdOptions` β€” Optional query parameters (expand, select) #### Returns `Promise`\<`AttachmentResponse`> Promise resolving to the attachment [AttachmentResponse](../AttachmentResponse/) #### Example ``` import { Attachments } from '@uipath/uipath-typescript/attachments'; const attachments = new Attachments(sdk); const attachment = await attachments.getById('12345678-1234-1234-1234-123456789abc'); ``` Service for managing UiPath Data Fabric Entities. Entities are collections of records that can be used to store and manage data in the Data Fabric. [UiPath Data Fabric Guide](https://docs.uipath.com/data-service/automation-cloud/latest/user-guide/introduction) ### Usage ``` import { Entities } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); const allEntities = await entities.getAll(); ``` ## Methods ### deleteAttachment() > **deleteAttachment**(`entityId`: `string`, `recordId`: `string`, `fieldName`: `string`, `options?`: `EntityDeleteAttachmentOptions`): `Promise`\<`EntityDeleteAttachmentResponse`> Removes an attachment from a File-type field of an entity record. #### Parameters - `entityId`: `string` β€” UUID of the entity - `recordId`: `string` β€” UUID of the record containing the attachment - `fieldName`: `string` β€” Name of the File-type field containing the attachment - `options?`: `EntityDeleteAttachmentOptions` β€” Optional [EntityDeleteAttachmentOptions](../EntityDeleteAttachmentOptions/) (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityDeleteAttachmentResponse`> Promise resolving to [EntityDeleteAttachmentResponse](../../type-aliases/EntityDeleteAttachmentResponse/) #### Example ``` import { Entities } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); // Get the entityId from getAll() const allEntities = await entities.getAll(); const entityId = allEntities[0].id; // Get the recordId from getAllRecords() const records = await entities.getAllRecords(entityId); const recordId = records[0].Id; // Delete attachment for a specific record and field await entities.deleteAttachment(entityId, recordId, 'Documents'); // Or delete using entity method (entityId is already known) const entity = await entities.getById(entityId); await entity.deleteAttachment(recordId, 'Documents'); ``` ### deleteRecordById() > **deleteRecordById**(`entityId`: `string`, `recordId`: `string`, `options?`: `EntityDeleteRecordByIdOptions`): `Promise`\<`void`> Deletes a single record from an entity by entity ID and record ID Note: Data Fabric supports trigger events only on individual deletes, not on deleting multiple records. Use this method if you need trigger events to fire for the deleted record. #### Parameters - `entityId`: `string` β€” UUID of the entity - `recordId`: `string` β€” UUID of the record to delete - `options?`: `EntityDeleteRecordByIdOptions` β€” Optional [EntityDeleteRecordByIdOptions](../EntityDeleteRecordByIdOptions/) (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. #### Returns `Promise`\<`void`> Promise resolving to void on success #### Example ``` import { Entities } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); await entities.deleteRecordById("", ""); // Folder-scoped: pass the entity's folder key await entities.deleteRecordById("", "", { folderKey: "" }); ``` ### deleteRecordsById() > **deleteRecordsById**(`id`: `string`, `recordIds`: `string`[], `options?`: `EntityDeleteRecordsOptions`): `Promise`\<`EntityDeleteResponse`> Deletes data from an entity by entity ID Note: Records deleted using deleteRecordsById will not trigger Data Fabric trigger events. Use [deleteRecordById](#deleterecordbyid) if you need trigger events to fire for the deleted record. #### Parameters - `id`: `string` β€” UUID of the entity - `recordIds`: `string`[] β€” Array of record UUIDs to delete - `options?`: `EntityDeleteRecordsOptions` β€” Delete options The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityDeleteResponse`> Promise resolving to delete response [EntityDeleteResponse](../EntityDeleteResponse/) #### Example ``` // Basic usage const result = await entities.deleteRecordsById(, [ , ]); // Folder-scoped entity: pass the entity's folder key await entities.deleteRecordsById(, [ , ], { folderKey: "" }); ``` ### downloadAttachment() > **downloadAttachment**(`entityId`: `string`, `recordId`: `string`, `fieldName`: `string`, `options?`: `EntityDownloadAttachmentOptions`): `Promise`\<`Blob`> Downloads an attachment stored in a File-type field of an entity record. #### Parameters - `entityId`: `string` β€” UUID of the entity - `recordId`: `string` β€” UUID of the record containing the attachment - `fieldName`: `string` β€” Name of the File-type field containing the attachment - `options?`: `EntityDownloadAttachmentOptions` β€” Optional [EntityDownloadAttachmentOptions](../EntityDownloadAttachmentOptions/) (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. #### Returns `Promise`\<`Blob`> Promise resolving to Blob containing the file content #### Example ``` import { Entities } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); // First, get records to obtain the record ID const records = await entities.getAllRecords(""); // Get the recordId for the record that contains the attachment const recordId = records.items[0].Id; // Get the entityId from getAll() const allEntities = await entities.getAll(); const entityId = allEntities[0].id; // Get the recordId from getAllRecords() const records = await entities.getAllRecords(entityId); const recordId = records[0].Id; // Download attachment using service method const response = await entities.downloadAttachment(entityId, recordId, 'Documents'); // Or download using entity method (entityId is already known) const entity = await entities.getById(entityId); const blob = await entity.downloadAttachment(recordId, 'Documents'); // Browser: Display Image const url = URL.createObjectURL(response); document.getElementById('image').src = url; // Call URL.revokeObjectURL(url) when done // Browser: Display PDF in iframe const url = URL.createObjectURL(response); document.getElementById('pdf-viewer').src = url; // Call URL.revokeObjectURL(url) when done // Browser: Render PDF with PDF.js const arrayBuffer = await response.arrayBuffer(); const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise; // Node.js: Save to file const buffer = Buffer.from(await response.arrayBuffer()); fs.writeFileSync('attachment.pdf', buffer); ``` ### getAll() > **getAll**(`options?`: `EntityGetAllOptions`): `Promise`\<`EntityGetResponse`[]> Gets entities in the tenant. Three call modes: - `getAll()` β€” default. Returns only tenant-level entities. - `getAll({ folderKey: "" })` β€” preferred for folder-scoped data. Returns only entities in that folder. - `getAll({ includeFolderEntities: true })` β€” returns tenant-level **and** folder-level entities together. `folderKey` is preferred over `includeFolderEntities` when both are set. #### Parameters - `options?`: `EntityGetAllOptions` β€” Optional [EntityGetAllOptions](../EntityGetAllOptions/) (`folderKey` to list a single folder's entities β€” preferred when scoping to a folder; `includeFolderEntities: true` to list tenant + folder entities together) The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityGetResponse`[]> Promise resolving to an array of entity metadata [EntityGetResponse](../../type-aliases/EntityGetResponse/) #### Example ``` // Tenant-only (default) const tenantEntities = await entities.getAll(); // A single folder's entities (preferred when targeting a specific folder) const folderEntities = await entities.getAll({ folderKey: "" }); // Tenant + folder entities together const allEntities = await entities.getAll({ includeFolderEntities: true }); // Iterate through entities tenantEntities.forEach(entity => { console.log(`Entity: ${entity.displayName} (${entity.name})`); console.log(`Type: ${entity.entityType}`); }); // Find a specific entity by name const customerEntity = tenantEntities.find(e => e.name === 'Customer'); // Use entity methods directly if (customerEntity) { const records = await customerEntity.getAllRecords(); console.log(`Customer records: ${records.items.length}`); // Insert a single record const insertResult = await customerEntity.insertRecord({ name: "John", age: 30 }); // Or batch insert multiple records const batchResult = await customerEntity.insertRecords([ { name: "Jane", age: 25 }, { name: "Bob", age: 35 } ]); } ``` ### getAllRecords() > **getAllRecords**\<`T`>(`entityId`: `string`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`EntityRecord`> : `NonPaginatedResponse`\<`EntityRecord`>> Gets entity records by entity ID `MULTILINE_MAX` fields are returned as a size marker (e.g. `"HasValue=true Length=512"`) instead of the full content β€” use [getRecordById](#getrecordbyid) to retrieve the full value. #### Type Parameters - `T` *extends* `EntityGetRecordsByIdOptions` = `EntityGetRecordsByIdOptions` #### Parameters - `entityId`: `string` β€” UUID of the entity - `options?`: `T` β€” Query options The `folderKey` property is **experimental**. #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`EntityRecord`> : `NonPaginatedResponse`\<`EntityRecord`>> Promise resolving to either an array of entity records NonPaginatedResponse or a PaginatedResponse when pagination options are used. [EntityRecord](../EntityRecord/) #### Example ``` // Basic usage (non-paginated) const records = await entities.getAllRecords(""); // With expansion level const records = await entities.getAllRecords(, { expansionLevel: 1 }); // With pagination const paginatedResponse = await entities.getAllRecords(, { pageSize: 50, expansionLevel: 1 }); // Navigate to next page const nextPage = await entities.getAllRecords(, { cursor: paginatedResponse.nextCursor, expansionLevel: 1 }); // Folder-scoped entity: pass the entity's folder key const records = await entities.getAllRecords("", { folderKey: "" }); ``` ### getById() > **getById**(`id`: `string`, `options?`: `EntityGetByIdOptions`): `Promise`\<`EntityGetResponse`> Gets entity metadata by entity ID with attached operation methods #### Parameters - `id`: `string` β€” UUID of the entity - `options?`: `EntityGetByIdOptions` β€” Optional [EntityGetByIdOptions](../EntityGetByIdOptions/) (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityGetResponse`> Promise resolving to entity metadata with operation methods [EntityGetResponse](../../type-aliases/EntityGetResponse/) #### Example ``` import { Entities, ChoiceSets } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); const choicesets = new ChoiceSets(sdk); // Get entity metadata with methods const entity = await entities.getById(""); // Folder-scoped: pass the entity's folder key const folderEntity = await entities.getById("", { folderKey: "" }); // Call operations directly on the entity const records = await entity.getAllRecords(); // If a field references a ChoiceSet, get the choiceSetId from records.fields const choiceSetId = records.fields[0].referenceChoiceSet?.id; if (choiceSetId) { const choiceSetValues = await choicesets.getById(choiceSetId); } // Insert a single record const insertResult = await entity.insertRecord({ name: "John", age: 30 }); // Or batch insert multiple records const batchResult = await entity.insertRecords([ { name: "Jane", age: 25 }, { name: "Bob", age: 35 } ]); ``` ### getRecordById() > **getRecordById**(`entityId`: `string`, `recordId`: `string`, `options?`: `EntityGetRecordByIdOptions`): `Promise`\<`EntityRecord`> Gets a single entity record by entity ID and record ID Returns the full record, including the complete content of `MULTILINE_MAX` fields. #### Parameters - `entityId`: `string` β€” UUID of the entity - `recordId`: `string` β€” UUID of the record - `options?`: `EntityGetRecordByIdOptions` β€” Query options The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityRecord`> Promise resolving to a single entity record [EntityRecord](../EntityRecord/) #### Example ``` // First, get records to obtain the record ID const records = await entities.getAllRecords(""); // Get the recordId for the record const recordId = records.items[0].Id; // Get the record const record = await entities.getRecordById(, recordId); // With expansion level const record = await entities.getRecordById(, recordId, { expansionLevel: 1 }); // Folder-scoped entity: pass the entity's folder key const record = await entities.getRecordById(, recordId, { folderKey: "" }); ``` ### importRecordsById() > **importRecordsById**(`id`: `string`, `file`: `EntityFileType`, `options?`: `EntityImportRecordsByIdOptions`): `Promise`\<`EntityImportRecordsResponse`> Imports records from a CSV file into an entity #### Parameters - `id`: `string` β€” UUID of the entity - `file`: `EntityFileType` β€” CSV file to import as a Blob or File or Uint8Array - `options?`: `EntityImportRecordsByIdOptions` β€” Optional [EntityImportRecordsByIdOptions](../EntityImportRecordsByIdOptions/) (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityImportRecordsResponse`> Promise resolving to [EntityImportRecordsResponse](../EntityImportRecordsResponse/) with record counts #### Example ``` // Browser: upload from file input const fileInput = document.getElementById('csv-input') as HTMLInputElement; const result = await entities.importRecordsById(, fileInput.files[0]); console.log(`Inserted ${result.insertedRecords} of ${result.totalRecords} records`); // Folder-scoped entity: pass the entity's folder key await entities.importRecordsById(, fileInput.files[0], { folderKey: "" }); ``` ### insertRecordById() > **insertRecordById**(`id`: `string`, `data`: `Record`\<`string`, `any`>, `options?`: `EntityInsertRecordOptions`): `Promise`\<`EntityInsertResponse`> Inserts a single record into an entity by entity ID Note: Data Fabric supports trigger events only on individual inserts, not on inserting multiple records. Use this method if you need trigger events to fire for the inserted record. #### Parameters - `id`: `string` β€” UUID of the entity - `data`: `Record`\<`string`, `any`> β€” Record to insert - `options?`: `EntityInsertRecordOptions` β€” Insert options The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityInsertResponse`> Promise resolving to the inserted record with generated record ID [EntityInsertResponse](../EntityInsertResponse/) #### Example ``` // Basic usage const result = await entities.insertRecordById(, { name: "John", age: 30 }); // With options const result = await entities.insertRecordById(, { name: "John", age: 30 }, { expansionLevel: 1 }); // Folder-scoped entity: pass the entity's folder key await entities.insertRecordById(, { name: "John", age: 30 }, { folderKey: "" }); ``` ### insertRecordsById() > **insertRecordsById**(`id`: `string`, `data`: `Record`\<`string`, `any`>[], `options?`: `EntityInsertRecordsOptions`): `Promise`\<`EntityBatchInsertResponse`> Inserts one or more records into an entity by entity ID Note: Records inserted using insertRecordsById will not trigger Data Fabric trigger events. Use [insertRecordById](#insertrecordbyid) if you need trigger events to fire for each inserted record. #### Parameters - `id`: `string` β€” UUID of the entity - `data`: `Record`\<`string`, `any`>[] β€” Array of records to insert - `options?`: `EntityInsertRecordsOptions` β€” Insert options The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityBatchInsertResponse`> Promise resolving to insert response [EntityBatchInsertResponse](../EntityBatchInsertResponse/) #### Example ``` // Basic usage const result = await entities.insertRecordsById(, [ { name: "John", age: 30 }, { name: "Jane", age: 25 } ]); // With options const result = await entities.insertRecordsById(, [ { name: "John", age: 30 }, { name: "Jane", age: 25 } ], { expansionLevel: 1, failOnFirst: true }); // Folder-scoped entity: pass the entity's folder key await entities.insertRecordsById(, [ { name: "John", age: 30 }, { name: "Jane", age: 25 } ], { folderKey: "" }); ``` ### queryRecordsById() > **queryRecordsById**\<`T`>(`id`: `string`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`EntityRecord`> : `NonPaginatedResponse`\<`EntityRecord`>> Queries entity records with filters, sorting, aggregates, and SDK-managed pagination `MULTILINE_MAX` fields are returned as a size marker (e.g. `"HasValue=true Length=512"`) instead of the full content β€” use [getRecordById](#getrecordbyid) to retrieve the full value. #### Type Parameters - `T` *extends* `EntityQueryRecordsOptions` = `EntityQueryRecordsOptions` #### Parameters - `id`: `string` β€” UUID of the entity - `options?`: `T` β€” Query options including filterGroup, selectedFields, sortOptions, aggregates, groupBy, joins, and pagination The `folderKey` property is **experimental**. #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`EntityRecord`> : `NonPaginatedResponse`\<`EntityRecord`>> Promise resolving to [NonPaginatedResponse](../NonPaginatedResponse/) without pagination options, or [PaginatedResponse](../PaginatedResponse/) when `pageSize`, `cursor`, or `jumpToPage` are provided #### Example ``` import { Entities, LogicalOperator, QueryFilterOperator, EntityAggregateFunction, JoinType } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); // Non-paginated query with a filter const result = await entities.queryRecordsById(, { filterGroup: { logicalOperator: LogicalOperator.And, queryFilters: [{ fieldName: "status", operator: QueryFilterOperator.Equals, value: "active" }] }, sortOptions: [{ fieldName: "createdTime", isDescending: true }], }); console.log(`Found ${result.totalCount} records`); // With pagination const page1 = await entities.queryRecordsById(, { pageSize: 25 }); if (page1.hasNextPage) { const page2 = await entities.queryRecordsById(, { cursor: page1.nextCursor }); } // Aggregate: count of records per status await entities.queryRecordsById(, { selectedFields: ["status"], groupBy: ["status"], aggregates: [ { function: EntityAggregateFunction.Count, field: "Id", alias: "total" }, ], }); // Folder-scoped entity: pass the entity's folder key await entities.queryRecordsById(, { filterGroup: { queryFilters: [{ fieldName: "status", operator: QueryFilterOperator.Equals, value: "active" }] }, folderKey: "", }); // Aggregate: total sum and average across all records (no grouping) await entities.queryRecordsById(, { aggregates: [ { function: EntityAggregateFunction.Sum, field: "amount", alias: "totalAmount" }, { function: EntityAggregateFunction.Avg, field: "amount", alias: "avgAmount" }, ], }); // Multi-join: pull fields from related entities into the query await entities.queryRecordsById(, { selectedFields: ["Id", "amount"], joins: [ { entityName: "Order", joinType: JoinType.LeftJoin, joinFieldName: "customerId", relatedEntityName: "Customer", relatedFieldName: "Id", }, { entityName: "Customer", joinType: JoinType.LeftJoin, joinFieldName: "regionId", relatedEntityName: "Region", relatedFieldName: "Id", }, ], }); ``` ### updateRecordById() > **updateRecordById**(`entityId`: `string`, `recordId`: `string`, `data`: `Record`\<`string`, `any`>, `options?`: `EntityUpdateRecordOptions`): `Promise`\<`EntityUpdateRecordResponse`> Updates a single record in an entity by entity ID Note: Data Fabric supports trigger events only on individual updates, not on updating multiple records. Use this method if you need trigger events to fire for the updated record. #### Parameters - `entityId`: `string` β€” UUID of the entity - `recordId`: `string` β€” UUID of the record to update - `data`: `Record`\<`string`, `any`> β€” Key-value pairs of fields to update - `options?`: `EntityUpdateRecordOptions` β€” Update options The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityUpdateRecordResponse`> Promise resolving to the updated record [EntityUpdateRecordResponse](../EntityUpdateRecordResponse/) #### Example ``` // Basic usage const result = await entities.updateRecordById(, , { name: "John Updated", age: 31 }); // With options const result = await entities.updateRecordById(, , { name: "John Updated", age: 31 }, { expansionLevel: 1 }); // Folder-scoped entity: pass the entity's folder key await entities.updateRecordById(, , { name: "John Updated" }, { folderKey: "" }); ``` ### updateRecordsById() > **updateRecordsById**(`id`: `string`, `data`: `EntityRecord`[], `options?`: `EntityUpdateRecordsOptions`): `Promise`\<`EntityUpdateResponse`> Updates data in an entity by entity ID Note: Records updated using updateRecordsById will not trigger Data Fabric trigger events. Use [updateRecordById](#updaterecordbyid) if you need trigger events to fire for each updated record. #### Parameters - `id`: `string` β€” UUID of the entity - `data`: `EntityRecord`[] β€” Array of records to update. Each record MUST contain the record id. - `options?`: `EntityUpdateRecordsOptions` β€” Update options The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityUpdateResponse`> Promise resolving to update response [EntityUpdateResponse](../EntityUpdateResponse/) #### Example ``` // Basic usage const result = await entities.updateRecordsById(, [ { Id: "123", name: "John Updated", age: 31 }, { Id: "456", name: "Jane Updated", age: 26 } ]); // With options const result = await entities.updateRecordsById(, [ { Id: "123", name: "John Updated", age: 31 }, { Id: "456", name: "Jane Updated", age: 26 } ], { expansionLevel: 1, failOnFirst: true }); // Folder-scoped entity: pass the entity's folder key await entities.updateRecordsById(, [ { Id: "123", name: "John Updated" } ], { folderKey: "" }); ``` ### uploadAttachment() > **uploadAttachment**(`entityId`: `string`, `recordId`: `string`, `fieldName`: `string`, `file`: `EntityFileType`, `options?`: `EntityUploadAttachmentOptions`): `Promise`\<`EntityUploadAttachmentResponse`> Uploads an attachment to a File-type field of an entity record. Uses multipart/form-data to upload the file content to the specified field. #### Parameters - `entityId`: `string` β€” UUID of the entity - `recordId`: `string` β€” UUID of the record to upload the attachment to - `fieldName`: `string` β€” Name of the File-type field - `file`: `EntityFileType` β€” File to upload (Blob, File, or Uint8Array) - `options?`: `EntityUploadAttachmentOptions` β€” Optional [EntityUploadAttachmentOptions](../EntityUploadAttachmentOptions/) (e.g. `expansionLevel`, `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. #### Returns `Promise`\<`EntityUploadAttachmentResponse`> Promise resolving to [EntityUploadAttachmentResponse](../../type-aliases/EntityUploadAttachmentResponse/) #### Example ``` import { Entities } from '@uipath/uipath-typescript/entities'; const entities = new Entities(sdk); // Get the entityId from getAll() const allEntities = await entities.getAll(); const entityId = allEntities[0].id; // Get the recordId from getAllRecords() const records = await entities.getAllRecords(entityId); const recordId = records[0].Id; // Browser: Upload a file from an input element const fileInput = document.getElementById('file-input') as HTMLInputElement; const file = fileInput.files[0]; const response = await entities.uploadAttachment(entityId, recordId, 'Documents', file); // Folder-scoped entity: pass the entity's folder key await entities.uploadAttachment(entityId, recordId, 'Documents', file, { folderKey: "" }); // Node.js: Upload a file from disk const fileBuffer = fs.readFileSync('document.pdf'); const blob = new Blob([fileBuffer], { type: 'application/pdf' }); const response = await entities.uploadAttachment(entityId, recordId, 'Documents', blob); ``` Service for managing UiPath Data Fabric Choice Sets Choice Sets are enumerated lists of values that can be used as field types in entities. They enable single-select or multi-select fields, such as expense types, categories, or status values. [UiPath Choice Sets Guide](https://docs.uipath.com/data-service/automation-cloud/latest/user-guide/choice-sets) ### Usage ``` import { ChoiceSets } from '@uipath/uipath-typescript/entities'; const choicesets = new ChoiceSets(sdk); const allChoiceSets = await choicesets.getAll(); ``` ## Methods ### getAll() > **getAll**(`options?`: `ChoiceSetGetAllOptions`): `Promise`\<`ChoiceSetGetAllResponse`[]> Gets choice sets in the tenant. Three call modes: - `getAll()` β€” default. Returns only tenant-level choice sets. - `getAll({ folderKey: "" })` β€” preferred for folder-scoped data. Returns only choice sets in that folder. - `getAll({ includeFolderChoiceSets: true })` β€” returns tenant-level **and** folder-level choice sets together. `folderKey` is preferred over `includeFolderChoiceSets` when both are set. #### Parameters - `options?`: `ChoiceSetGetAllOptions` β€” Optional [ChoiceSetGetAllOptions](../ChoiceSetGetAllOptions/) (`folderKey` to list a single folder's choice sets β€” preferred when scoping to a folder; `includeFolderChoiceSets: true` to list tenant + folder choice sets together) The `folderKey` property is **experimental**. #### Returns `Promise`\<`ChoiceSetGetAllResponse`[]> Promise resolving to an array of choice set metadata [ChoiceSetGetAllResponse](../ChoiceSetGetAllResponse/) #### Example ``` // Tenant-only (default) const tenantChoiceSets = await choicesets.getAll(); // A single folder's choice sets (preferred when targeting a specific folder) const folderChoiceSets = await choicesets.getAll({ folderKey: "" }); // Tenant + folder choice sets together const allChoiceSets = await choicesets.getAll({ includeFolderChoiceSets: true }); // Find a specific choice set by name const expenseTypes = tenantChoiceSets.find(cs => cs.name === 'ExpenseTypes'); ``` ### getById() > **getById**\<`T`>(`choiceSetId`: `string`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`ChoiceSetGetResponse`> : `NonPaginatedResponse`\<`ChoiceSetGetResponse`>> Gets choice set values by choice set ID with optional pagination The method returns either: - A NonPaginatedResponse with items array (when no pagination parameters are provided) - A PaginatedResponse with navigation cursors (when any pagination parameter is provided) #### Type Parameters - `T` *extends* `ChoiceSetGetByIdOptions` = `ChoiceSetGetByIdOptions` #### Parameters - `choiceSetId`: `string` β€” UUID of the choice set - `options?`: `T` β€” Pagination options and optional `folderKey` (omit for tenant-level choice sets) The `folderKey` property is **experimental**. #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`ChoiceSetGetResponse`> : `NonPaginatedResponse`\<`ChoiceSetGetResponse`>> Promise resolving to choice set values or paginated result [ChoiceSetGetResponse](../ChoiceSetGetResponse/) #### Example ``` // First, get the choice set ID using getAll() const allChoiceSets = await choicesets.getAll(); const expenseTypes = allChoiceSets.find(cs => cs.name === 'ExpenseTypes'); const choiceSetId = expenseTypes.id; // Get all values (non-paginated) const values = await choicesets.getById(choiceSetId); // Iterate through choice set values for (const value of values.items) { console.log(`Value: ${value.displayName}`); } // First page with pagination const page1 = await choicesets.getById(choiceSetId, { pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await choicesets.getById(choiceSetId, { cursor: page1.nextCursor }); } // Folder-scoped choice set const folderValues = await choicesets.getById(choiceSetId, { folderKey: "" }); ``` Service for managing UiPath Maestro Processes UiPath Maestro is a cloud-native orchestration layer that coordinates bots, AI agents, and humans for seamless, intelligent automation of complex workflows. [UiPath Maestro Guide](https://docs.uipath.com/maestro/automation-cloud/latest/user-guide/introduction-to-maestro) ### Usage ``` import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes'; const maestroProcesses = new MaestroProcesses(sdk); const allProcesses = await maestroProcesses.getAll(); ``` ## Methods ### getAll() > **getAll**(): `Promise`\<`MaestroProcessGetAllResponse`[]> Get all processes with their instance statistics #### Returns `Promise`\<`MaestroProcessGetAllResponse`[]> Promise resolving to array of MaestroProcess objects with methods [MaestroProcessGetAllResponse](../../type-aliases/MaestroProcessGetAllResponse/) #### Example ``` // Get all processes const allProcesses = await maestroProcesses.getAll(); // Access process information and incidents for (const process of allProcesses) { console.log(`Process: ${process.processKey}`); console.log(`Running instances: ${process.runningCount}`); console.log(`Faulted instances: ${process.faultedCount}`); // Get incidents for this process const incidents = await process.getIncidents(); console.log(`Incidents: ${incidents.length}`); } ``` ### getElementStats() > **getElementStats**(`request`: `MaestroProcessStatsRequest`): `Promise`\<`ElementStats`[]> Get element stats for process instances Returns per-element execution counts (success, fail, terminated, paused, in-progress) and duration percentile metrics (min, max, avg, p50, p95, p99) for BPMN elements within a process. #### Parameters - `request`: `MaestroProcessStatsRequest` β€” Process scope + time range to aggregate over #### Returns `Promise`\<`ElementStats`[]> Promise resolving to an array of [ElementStats](../ElementStats/) #### Example ``` // First, list processes to find the processKey, packageId, and available versions const processes = await maestroProcesses.getAll(); const process = processes[0]; // Get element metrics for that process const elements = await maestroProcesses.getElementStats({ processKey: process.processKey, packageId: process.packageId, packageVersion: process.packageVersions[0], startTime: new Date('2026-04-01'), endTime: new Date(), }); // Analyze element performance for (const element of elements) { console.log(`Element: ${element.elementId}`); console.log(` Success: ${element.successCount}, Failed: ${element.failCount}`); console.log(` Avg duration: ${element.avgDurationMs}ms, P95: ${element.p95DurationMs}ms`); } // Using bound method on a process β€” auto-fills processKey and packageId const boundElements = await process.getElementStats( new Date('2026-04-01'), new Date(), process.packageVersions[0] ); ``` ### getIncidents() > **getIncidents**(`processKey`: `string`, `folderKey`: `string`): `Promise`\<`ProcessIncidentGetResponse`[]> Get incidents for a specific process #### Parameters - `processKey`: `string` β€” The key of the process to get incidents for - `folderKey`: `string` β€” The folder key for authorization #### Returns `Promise`\<`ProcessIncidentGetResponse`[]> Promise resolving to array of incidents for the process [ProcessIncidentGetResponse](../ProcessIncidentGetResponse/) #### Example ``` // Get incidents for a specific process const incidents = await maestroProcesses.getIncidents('', ''); // Access incident details for (const incident of incidents) { console.log(`Element: ${incident.incidentElementActivityName} (${incident.incidentElementActivityType})`); console.log(`Status: ${incident.incidentStatus}`); console.log(`Error: ${incident.errorMessage}`); } ``` ### getIncidentsTimeline() > **getIncidentsTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TimelineOptions`): `Promise`\<`IncidentTimelineResponse`[]> Get incident counts aggregated by time bucket for maestro processes. Returns time-grouped counts of incidents that occurred within each bucket, useful for rendering incident time-series charts. Use `groupBy` to control the time bucket size (hour, day, or week) β€” defaults to day if not provided. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TimelineOptions` β€” Optional settings for filtering and time bucket granularity #### Returns `Promise`\<`IncidentTimelineResponse`[]> Promise resolving to an array of [IncidentTimelineResponse](../IncidentTimelineResponse/) #### Examples ``` // Get daily incident counts for the last 7 days const now = new Date(); const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); const incidents = await maestroProcesses.getIncidentsTimeline(sevenDaysAgo, now); for (const incident of incidents) { console.log(`${incident.startTime} β†’ ${incident.endTime}: ${incident.count} incidents`); } ``` ``` import { TimeInterval } from '@uipath/uipath-typescript/maestro-processes'; // Get weekly breakdown const incidents = await maestroProcesses.getIncidentsTimeline(startTime, endTime, { groupBy: TimeInterval.Week, }); ``` ``` // Filter to a specific process const filtered = await maestroProcesses.getIncidentsTimeline(startTime, endTime, { processKeys: [''], }); ``` ### getInstanceStats() > **getInstanceStats**(`request`: `MaestroProcessStatsRequest`): `Promise`\<`InstanceStats`> Get instance stats for a process. Returns total instance counts broken down by status (running, completed, faulted, etc.) and the average execution duration for all instances of a process within a time range. #### Parameters - `request`: `MaestroProcessStatsRequest` β€” Process scope + time range to aggregate over #### Returns `Promise`\<`InstanceStats`> Promise resolving to [InstanceStats](../InstanceStats/) #### Example ``` // First, list processes to find the processKey, packageId, and available versions const processes = await maestroProcesses.getAll(); const process = processes[0]; // Get instance status breakdown for that process const counts = await maestroProcesses.getInstanceStats({ processKey: process.processKey, packageId: process.packageId, packageVersion: process.packageVersions[0], startTime: new Date('2026-04-01'), endTime: new Date(), }); console.log(`Total: ${counts.totalCount}`); console.log(`Running: ${counts.runningCount}, Completed: ${counts.completedCount}`); console.log(`Faulted: ${counts.faultedCount}, Avg duration: ${counts.avgDurationMs}ms`); // Using bound method on a process β€” auto-fills processKey and packageId const boundCounts = await process.getInstanceStats( new Date('2026-04-01'), new Date(), process.packageVersions[0] ); ``` ### getInstanceStatusTimeline() > **getInstanceStatusTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TimelineOptions`): `Promise`\<`InstanceStatusTimelineResponse`[]> Get all instances status counts aggregated by date for maestro processes. Returns time-grouped counts of instances grouped by status (Completed, Faulted, Cancelled), useful for rendering time-series charts. Use `groupBy` to control the time bucket size (hour, day, or week) β€” defaults to day if not provided. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TimelineOptions` β€” Optional settings for filtering and time bucket granularity #### Returns `Promise`\<`InstanceStatusTimelineResponse`[]> Promise resolving to an array of [InstanceStatusTimelineResponse](../InstanceStatusTimelineResponse/) #### Examples ``` // Get daily instance status for the last 7 days const now = new Date(); const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); const statuses = await maestroProcesses.getInstanceStatusTimeline(sevenDaysAgo, now); for (const entry of statuses) { console.log(`${entry.startTime} β€” ${entry.status}: ${entry.count}`); } ``` ``` import { TimeInterval } from '@uipath/uipath-typescript/maestro-processes'; // Get hourly breakdown const statuses = await maestroProcesses.getInstanceStatusTimeline(startTime, endTime, { groupBy: TimeInterval.Hour, }); ``` ``` // Filter to a specific process const filtered = await maestroProcesses.getInstanceStatusTimeline(startTime, endTime, { processKeys: [''], }); ``` ``` // Get all-time data (from Unix epoch to now) const allTime = await maestroProcesses.getInstanceStatusTimeline(new Date(0), new Date()); ``` ### getTopElementFailedCount() > **getTopElementFailedCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`ElementGetTopFailedCountResponse`[]> Get the top 10 BPMN elements ranked by failure count within a time range. Returns an array of up to 10 elements sorted by how many times they failed, useful for identifying the most error-prone activities in processes. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`ElementGetTopFailedCountResponse`[]> Promise resolving to an array of [ElementGetTopFailedCountResponse](../ElementGetTopFailedCountResponse/) #### Examples ``` import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes'; const maestroProcesses = new MaestroProcesses(sdk); // Get top failing elements for the last 7 days const topFailing = await maestroProcesses.getTopElementFailedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const element of topFailing) { console.log(`${element.elementName} (${element.elementType}): ${element.failedCount} failures`); } ``` ``` // Get top failing elements for a specific process const filtered = await maestroProcesses.getTopElementFailedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { processKey: '' } ); ``` ### getTopExecutionDuration() > **getTopExecutionDuration**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`ProcessGetTopDurationResponse`[]> Get the top 5 processes ranked by total duration within a time range. Returns an array of up to 5 processes sorted by their total execution time, useful for identifying the longest-running processes in a given period. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`ProcessGetTopDurationResponse`[]> Promise resolving to an array of [ProcessGetTopDurationResponse](../ProcessGetTopDurationResponse/) #### Examples ``` import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes'; const maestroProcesses = new MaestroProcesses(sdk); // Get top processes by duration for the last 7 days const topProcesses = await maestroProcesses.getTopExecutionDuration( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const process of topProcesses) { console.log(`${process.packageId}: ${process.duration}ms total`); } ``` ``` // Get top processes by duration for a specific package const filtered = await maestroProcesses.getTopExecutionDuration( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { packageId: '' } ); ``` ### getTopFaultedCount() > **getTopFaultedCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`ProcessGetTopFaultedCountResponse`[]> Get the top 10 processes ranked by failure count within a time range. Returns an array of up to 10 processes sorted by how many instances faulted, useful for identifying the most error-prone processes in a given period. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`ProcessGetTopFaultedCountResponse`[]> Promise resolving to an array of [ProcessGetTopFaultedCountResponse](../ProcessGetTopFaultedCountResponse/) #### Examples ``` import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes'; const maestroProcesses = new MaestroProcesses(sdk); // Get top processes by faulted count for the last 7 days const topFailing = await maestroProcesses.getTopFaultedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const process of topFailing) { console.log(`${process.packageId}: ${process.faultedCount} failures`); } ``` ``` // Get top processes by faulted count for a specific package const filtered = await maestroProcesses.getTopFaultedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { packageId: '' } ); ``` ### getTopRunCount() > **getTopRunCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`ProcessGetTopRunCountResponse`[]> Get the top 5 processes ranked by run count within a time range. Returns an array of up to 5 processes sorted by how many times they were executed, useful for identifying the most active processes in a given period. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`ProcessGetTopRunCountResponse`[]> Promise resolving to an array of [ProcessGetTopRunCountResponse](../ProcessGetTopRunCountResponse/) #### Examples ``` import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes'; const maestroProcesses = new MaestroProcesses(sdk); // Get top processes by run count for the last 7 days const topProcesses = await maestroProcesses.getTopRunCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const process of topProcesses) { console.log(`${process.packageId}: ${process.runCount} runs`); } ``` ``` // Get top processes by run count for a specific package const filtered = await maestroProcesses.getTopRunCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { packageId: '' } ); ``` Service for managing UiPath Maestro Process instances Maestro process instances are the running instances of Maestro processes. [UiPath Maestro Process Instances Guide](https://docs.uipath.com/maestro/automation-cloud/latest/user-guide/all-instances-view) ### Usage ``` import { ProcessInstances } from '@uipath/uipath-typescript/maestro-processes'; const processInstances = new ProcessInstances(sdk); const allInstances = await processInstances.getAll(); ``` ## Methods ### cancel() > **cancel**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `ProcessInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Cancel a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to cancel - `folderKey`: `string` β€” The folder key for authorization - `options?`: `ProcessInstanceOperationOptions` β€” Optional cancellation options with comment #### Returns `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Promise resolving to operation result with instance data #### Example ``` // Cancel a process instance const result = await processInstances.cancel( , ); // Or using instance method const instance = await processInstances.getById( , ); const result = await instance.cancel(); console.log(`Cancelled: ${result.success}`); // Cancel with a comment const resultWithComment = await instance.cancel({ comment: 'Cancelling due to invalid input data' }); if (resultWithComment.success) { console.log(`Instance ${resultWithComment.data.instanceId} status: ${resultWithComment.data.status}`); } ``` ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`ProcessInstanceGetResponse`> : `NonPaginatedResponse`\<`ProcessInstanceGetResponse`>> Get all process instances with optional filtering and pagination The method returns either: - A NonPaginatedResponse with items array (when no pagination parameters are provided) - A PaginatedResponse with navigation cursors (when any pagination parameter is provided) #### Type Parameters - `T` *extends* `ProcessInstanceGetAllWithPaginationOptions` = `ProcessInstanceGetAllWithPaginationOptions` #### Parameters - `options?`: `T` β€” Query parameters for filtering instances and pagination #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`ProcessInstanceGetResponse`> : `NonPaginatedResponse`\<`ProcessInstanceGetResponse`>> Promise resolving to either an array of process instances NonPaginatedResponse or a PaginatedResponse when pagination options are used. [ProcessInstanceGetResponse](../../type-aliases/ProcessInstanceGetResponse/) #### Example ``` // Get all instances (non-paginated) const instances = await processInstances.getAll(); // Cancel faulted instances using methods directly on instances for (const instance of instances.items) { if (instance.latestRunStatus === 'Faulted') { await instance.cancel({ comment: 'Cancelling faulted instance' }); } } // With filtering const filteredInstances = await processInstances.getAll({ processKey: 'MyProcess' }); // First page with pagination const page1 = await processInstances.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await processInstances.getAll({ cursor: page1.nextCursor }); } ``` ### getBpmn() > **getBpmn**(`instanceId`: `string`, `folderKey`: `string`): `Promise`\<`string`> Get BPMN XML file for a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to get BPMN for - `folderKey`: `string` β€” The folder key for authorization #### Returns `Promise`\<`string`> Promise resolving to BPMN XML file [BpmnXmlString](../../type-aliases/BpmnXmlString/) #### Example ``` // Get BPMN XML for a process instance const bpmnXml = await processInstances.getBpmn( , ); // Render BPMN diagram in frontend using bpmn-js import BpmnViewer from 'bpmn-js/lib/Viewer'; const viewer = new BpmnViewer({ container: '#bpmn-diagram' }); await viewer.importXML(bpmnXml); // Zoom to fit the diagram viewer.get('canvas').zoom('fit-viewport'); ``` ### getById() > **getById**(`id`: `string`, `folderKey`: `string`): `Promise`\<`ProcessInstanceGetResponse`> Get a process instance by ID with operation methods (cancel, pause, resume, retry) #### Parameters - `id`: `string` β€” The ID of the instance to retrieve - `folderKey`: `string` β€” The folder key for authorization #### Returns `Promise`\<`ProcessInstanceGetResponse`> Promise resolving to a process instance [ProcessInstanceGetResponse](../../type-aliases/ProcessInstanceGetResponse/) #### Example ``` // Get a specific process instance const instance = await processInstances.getById( , ); // Access instance properties console.log(`Status: ${instance.latestRunStatus}`); ``` ### getExecutionHistory() > **getExecutionHistory**(`instanceId`: `string`, `folderKey`: `string`): `Promise`\<`ProcessInstanceExecutionHistoryResponse`[]> Get execution history (spans) for a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to get history for - `folderKey`: `string` β€” The folder key for authorization #### Returns `Promise`\<`ProcessInstanceExecutionHistoryResponse`[]> Promise resolving to execution history [ProcessInstanceExecutionHistoryResponse](../ProcessInstanceExecutionHistoryResponse/) #### Example ``` // Get execution history for a process instance const history = await processInstances.getExecutionHistory( , ); // Analyze execution timeline history.forEach(span => { console.log(`Activity: ${span.name}`); console.log(`Start: ${span.startedTime}`); console.log(`End: ${span.endTime}`); }); ``` ### getIncidents() > **getIncidents**(`instanceId`: `string`, `folderKey`: `string`): `Promise`\<`ProcessIncidentGetResponse`[]> Get incidents for a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to get incidents for - `folderKey`: `string` β€” The folder key for authorization #### Returns `Promise`\<`ProcessIncidentGetResponse`[]> Promise resolving to array of incidents for the processinstance [ProcessIncidentGetResponse](../ProcessIncidentGetResponse/) #### Example ``` // Get incidents for a specific instance const incidents = await processInstances.getIncidents('', ''); // Access process incident details for (const incident of incidents) { console.log(`Element: ${incident.incidentElementActivityName} (${incident.incidentElementActivityType})`); console.log(`Severity: ${incident.incidentSeverity}`); console.log(`Error: ${incident.errorMessage}`); } ``` ### getVariables() > **getVariables**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `ProcessInstanceGetVariablesOptions`): `Promise`\<`ProcessInstanceGetVariablesResponse`> Get global variables for a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to get variables for - `folderKey`: `string` β€” The folder key for authorization - `options?`: `ProcessInstanceGetVariablesOptions` β€” Optional options including parentElementId to filter by parent element #### Returns `Promise`\<`ProcessInstanceGetVariablesResponse`> Promise resolving to variables response with elements and globals [ProcessInstanceGetVariablesResponse](../ProcessInstanceGetVariablesResponse/) #### Example ``` // Get all variables for a process instance const variables = await processInstances.getVariables( , ); // Access global variables console.log('Global variables:', variables.globalVariables); // Iterate through global variables with metadata variables.globalVariables?.forEach(variable => { console.log(`Variable: ${variable.name} (${variable.id})`); console.log(` Type: ${variable.type}`); console.log(` Element: ${variable.elementId}`); console.log(` Value: ${variable.value}`); }); // Get variables for a specific parent element const elementVariables = await processInstances.getVariables( , , { parentElementId: } ); ``` ### pause() > **pause**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `ProcessInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Pause a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to pause - `folderKey`: `string` β€” The folder key for authorization - `options?`: `ProcessInstanceOperationOptions` β€” Optional pause options with comment #### Returns `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Promise resolving to operation result with instance data ### resume() > **resume**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `ProcessInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Resume a process instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to resume - `folderKey`: `string` β€” The folder key for authorization - `options?`: `ProcessInstanceOperationOptions` β€” Optional resume options with comment #### Returns `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Promise resolving to operation result with instance data ### retry() > **retry**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `ProcessInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Retry a faulted process instance Re-runs the failed elements of the instance (and the elements that follow) within the same instance, spawning new jobs. Use to recover from transient/flaky failures. #### Parameters - `instanceId`: `string` β€” The ID of the instance to retry - `folderKey`: `string` β€” The folder key for authorization - `options?`: `ProcessInstanceOperationOptions` β€” Optional retry options with comment #### Returns `Promise`\<`OperationResponse`\<`ProcessInstanceOperationResponse`>> Promise resolving to operation result with instance data #### Example ``` // Retry a faulted process instance const result = await processInstances.retry( , ); // Or using instance method const instance = await processInstances.getById( , ); if (instance.latestRunStatus === 'Faulted') { const result = await instance.retry({ comment: 'Retrying flaky failure' }); console.log(`Retried: ${result.success}`); } ``` Service for managing UiPath Maestro Cases UiPath Maestro Case Management describes solutions that help manage and automate the full flow of complex E2E scenarios. ### Usage ``` import { Cases } from '@uipath/uipath-typescript/cases'; const cases = new Cases(sdk); const allCases = await cases.getAll(); ``` ## Methods ### getAll() > **getAll**(): `Promise`\<`CaseGetAllWithMethodsResponse`[]> Get all case management processes with their instance statistics #### Returns `Promise`\<`CaseGetAllWithMethodsResponse`[]> Promise resolving to an array of [CaseGetAllWithMethodsResponse](../../type-aliases/CaseGetAllWithMethodsResponse/) #### Example ``` // Get all case management processes const allCases = await cases.getAll(); // Access case information for (const caseProcess of allCases) { console.log(`Case Process: ${caseProcess.processKey}`); console.log(`Running instances: ${caseProcess.runningCount}`); console.log(`Completed instances: ${caseProcess.completedCount}`); } ``` ### getElementStats() > **getElementStats**(`request`: `MaestroProcessStatsRequest`): `Promise`\<`ElementStats`[]> Get element stats for case instances Returns per-element execution counts (success, fail, terminated, paused, in-progress) and duration percentile metrics (min, max, avg, p50, p95, p99) for BPMN elements within a case. #### Parameters - `request`: `MaestroProcessStatsRequest` β€” Process scope + time range to aggregate over #### Returns `Promise`\<`ElementStats`[]> Promise resolving to an array of [ElementStats](../ElementStats/) #### Example ``` // First, list cases to find the processKey, packageId, and available versions const allCases = await cases.getAll(); const caseItem = allCases[0]; // Get element metrics for that case const elements = await cases.getElementStats({ processKey: caseItem.processKey, packageId: caseItem.packageId, packageVersion: caseItem.packageVersions[0], startTime: new Date('2026-04-01'), endTime: new Date(), }); // Find elements with failures const failedElements = elements.filter(e => e.failCount > 0); for (const element of failedElements) { console.log(`Failed element: ${element.elementId}, failures: ${element.failCount}`); } // Using bound method on a case β€” auto-fills processKey and packageId const boundElements = await caseItem.getElementStats( new Date('2026-04-01'), new Date(), caseItem.packageVersions[0] ); ``` ### getIncidentsTimeline() > **getIncidentsTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TimelineOptions`): `Promise`\<`IncidentTimelineResponse`[]> Get incident counts aggregated by time bucket for case management processes. Returns time-grouped counts of incidents that occurred within each bucket, useful for rendering incident time-series charts. Use `groupBy` to control the time bucket size (hour, day, or week) β€” defaults to day if not provided. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TimelineOptions` β€” Optional settings for filtering and time bucket granularity #### Returns `Promise`\<`IncidentTimelineResponse`[]> Promise resolving to an array of [IncidentTimelineResponse](../IncidentTimelineResponse/) #### Examples ``` // Get daily incident counts for the last 7 days const now = new Date(); const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); const incidents = await cases.getIncidentsTimeline(sevenDaysAgo, now); for (const incident of incidents) { console.log(`${incident.startTime} β†’ ${incident.endTime}: ${incident.count} incidents`); } ``` ``` import { TimeInterval } from '@uipath/uipath-typescript/cases'; // Get weekly breakdown const incidents = await cases.getIncidentsTimeline(startTime, endTime, { groupBy: TimeInterval.Week, }); ``` ``` // Filter to a specific case process const filtered = await cases.getIncidentsTimeline(startTime, endTime, { processKeys: [''], }); ``` ### getInstanceStats() > **getInstanceStats**(`request`: `MaestroProcessStatsRequest`): `Promise`\<`InstanceStats`> Get instance stats for a case. Returns total instance counts broken down by status (running, completed, faulted, etc.) and the average execution duration for all instances of a case within a time range. #### Parameters - `request`: `MaestroProcessStatsRequest` β€” Process scope + time range to aggregate over #### Returns `Promise`\<`InstanceStats`> Promise resolving to [InstanceStats](../InstanceStats/) #### Example ``` // First, list cases to find the processKey, packageId, and available versions const allCases = await cases.getAll(); const caseItem = allCases[0]; // Get instance status breakdown for that case const counts = await cases.getInstanceStats({ processKey: caseItem.processKey, packageId: caseItem.packageId, packageVersion: caseItem.packageVersions[0], startTime: new Date('2026-04-01'), endTime: new Date(), }); console.log(`Total: ${counts.totalCount}`); console.log(`Completed: ${counts.completedCount}, Faulted: ${counts.faultedCount}`); // Using bound method on a case β€” auto-fills processKey and packageId const boundCounts = await caseItem.getInstanceStats( new Date('2026-04-01'), new Date(), caseItem.packageVersions[0] ); ``` ### getInstanceStatusTimeline() > **getInstanceStatusTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TimelineOptions`): `Promise`\<`InstanceStatusTimelineResponse`[]> Get all instances status counts aggregated by date for case management processes. Returns time-grouped counts of case instances grouped by status (Completed, Faulted, Cancelled), useful for rendering time-series charts. Use `groupBy` to control the time bucket size (hour, day, or week) β€” defaults to day if not provided. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TimelineOptions` β€” Optional settings for filtering and time bucket granularity #### Returns `Promise`\<`InstanceStatusTimelineResponse`[]> Promise resolving to an array of [InstanceStatusTimelineResponse](../InstanceStatusTimelineResponse/) #### Examples ``` // Get daily instance status for the last 7 days const now = new Date(); const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); const statuses = await cases.getInstanceStatusTimeline(sevenDaysAgo, now); for (const entry of statuses) { console.log(`${entry.startTime} β€” ${entry.status}: ${entry.count}`); } ``` ``` import { TimeInterval } from '@uipath/uipath-typescript/cases'; // Get weekly breakdown const statuses = await cases.getInstanceStatusTimeline(startTime, endTime, { groupBy: TimeInterval.Week, }); ``` ``` // Filter to a specific case process const filtered = await cases.getInstanceStatusTimeline(startTime, endTime, { processKeys: [''], }); ``` ``` // Get all-time data (from Unix epoch to now) const allTime = await cases.getInstanceStatusTimeline(new Date(0), new Date()); ``` ### getTopElementFailedCount() > **getTopElementFailedCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`ElementGetTopFailedCountResponse`[]> Get the top 10 BPMN elements ranked by failure count within a time range. Returns an array of up to 10 elements sorted by how many times they failed, useful for identifying the most error-prone activities in case processes. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`ElementGetTopFailedCountResponse`[]> Promise resolving to an array of [ElementGetTopFailedCountResponse](../ElementGetTopFailedCountResponse/) #### Examples ``` import { Cases } from '@uipath/uipath-typescript/cases'; const cases = new Cases(sdk); // Get top failing elements for the last 7 days const topFailing = await cases.getTopElementFailedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const element of topFailing) { console.log(`${element.elementName} (${element.elementType}): ${element.failedCount} failures`); } ``` ``` // Get top failing elements for a specific process const filtered = await cases.getTopElementFailedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { processKey: '' } ); ``` ### getTopExecutionDuration() > **getTopExecutionDuration**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`CaseGetTopDurationResponse`[]> Get the top 5 case processes ranked by total duration within a time range. Returns an array of up to 5 case processes sorted by their total execution time, useful for identifying the longest-running case processes in a given period. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`CaseGetTopDurationResponse`[]> Promise resolving to an array of [CaseGetTopDurationResponse](../CaseGetTopDurationResponse/) #### Examples ``` import { Cases } from '@uipath/uipath-typescript/cases'; const cases = new Cases(sdk); // Get top case processes by duration for the last 7 days const topProcesses = await cases.getTopExecutionDuration( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const process of topProcesses) { console.log(`${process.packageId}: ${process.duration}ms total`); } ``` ``` // Get top case processes by duration for a specific package const filtered = await cases.getTopExecutionDuration( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { packageId: '' } ); ``` ### getTopFaultedCount() > **getTopFaultedCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`CaseGetTopFaultedCountResponse`[]> Get the top 10 case processes ranked by failure count within a time range. Returns an array of up to 10 case processes sorted by how many instances faulted, useful for identifying the most error-prone case processes in a given period. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`CaseGetTopFaultedCountResponse`[]> Promise resolving to an array of [CaseGetTopFaultedCountResponse](../CaseGetTopFaultedCountResponse/) #### Examples ``` import { Cases } from '@uipath/uipath-typescript/cases'; const cases = new Cases(sdk); // Get top case processes by faulted count for the last 7 days const topFailing = await cases.getTopFaultedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const process of topFailing) { console.log(`${process.packageId}: ${process.faultedCount} failures`); } ``` ``` // Get top case processes by faulted count for a specific package const filtered = await cases.getTopFaultedCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { packageId: '' } ); ``` ### getTopRunCount() > **getTopRunCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `TopQueryOptions`): `Promise`\<`CaseGetTopRunCountResponse`[]> Get the top 5 case processes ranked by run count within a time range. Returns an array of up to 5 case processes sorted by how many times they were executed, useful for identifying the most active case processes in a given period. #### Parameters - `startTime`: `Date` β€” Start of the time range to query - `endTime`: `Date` β€” End of the time range to query - `options?`: `TopQueryOptions` β€” Optional filters (packageId, processKey, version) #### Returns `Promise`\<`CaseGetTopRunCountResponse`[]> Promise resolving to an array of [CaseGetTopRunCountResponse](../CaseGetTopRunCountResponse/) #### Examples ``` import { Cases } from '@uipath/uipath-typescript/cases'; const cases = new Cases(sdk); // Get top case processes by run count for the last 7 days const topProcesses = await cases.getTopRunCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date() ); for (const process of topProcesses) { console.log(`${process.packageId}: ${process.runCount} runs`); } ``` ``` // Get top case processes by run count for a specific package const filtered = await cases.getTopRunCount( new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), new Date(), { packageId: '' } ); ``` Service model for managing Maestro Case Instances Maestro case instances are the running instances of Maestro cases. ### Usage ``` import { CaseInstances } from '@uipath/uipath-typescript/cases'; const caseInstances = new CaseInstances(sdk); const allInstances = await caseInstances.getAll(); ``` Note Methods that rely on the Insights Real-Time Monitoring service (`getSlaSummary`, `getStagesSlaSummary`) may have up to ~1 minute latency before reflecting the latest updates. See [Real-Time Monitoring Overview](https://docs.uipath.com/insights/automation-cloud/latest/user-guide/real-time-monitoring-overview) for details. ## Methods ### close() > **close**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `CaseInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Close/Cancel a case instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to cancel - `folderKey`: `string` β€” Required folder key - `options?`: `CaseInstanceOperationOptions` β€” Optional close options with comment #### Returns `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Promise resolving to operation result with instance data #### Example ``` // Close a case instance const result = await caseInstances.close( , ); // Or using instance method const instance = await caseInstances.getById( , ); const result = await instance.close(); console.log(`Closed: ${result.success}`); // Close with a comment const resultWithComment = await instance.close({ comment: 'Closing due to invalid input data' }); if (resultWithComment.success) { console.log(`Instance ${resultWithComment.data.instanceId} status: ${resultWithComment.data.status}`); } ``` ### getActionTasks() > **getActionTasks**\<`T`>(`caseInstanceId`: `string`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`TaskGetResponse`> : `NonPaginatedResponse`\<`TaskGetResponse`>> Get human in the loop tasks associated with a case instance The method returns either: - An array of tasks (when no pagination parameters are provided) - A paginated result with navigation cursors (when any pagination parameter is provided) #### Type Parameters - `T` *extends* `TaskGetAllOptions` = `TaskGetAllOptions` #### Parameters - `caseInstanceId`: `string` β€” The ID of the case instance - `options?`: `T` β€” Optional filtering and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`TaskGetResponse`> : `NonPaginatedResponse`\<`TaskGetResponse`>> Promise resolving to human in the loop tasks associated with the case instance #### Example ``` // Get all tasks for a case instance (non-paginated) const actionTasks = await caseInstances.getActionTasks( , ); // First page with pagination const page1 = await caseInstances.getActionTasks( , { pageSize: 10 } ); // Iterate through tasks for (const task of page1.items) { console.log(`Task: ${task.title}`); console.log(`Task: ${task.status}`); } // Jump to specific page const page5 = await caseInstances.getActionTasks( , { jumpToPage: 5, pageSize: 10 } ); ``` ### getAll() > **getAll**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`CaseInstanceGetResponse`> : `NonPaginatedResponse`\<`CaseInstanceGetResponse`>> Get all case instances with optional filtering and pagination #### Type Parameters - `T` *extends* `CaseInstanceGetAllWithPaginationOptions` = `CaseInstanceGetAllWithPaginationOptions` #### Parameters - `options?`: `T` β€” Query parameters for filtering instances and pagination #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`CaseInstanceGetResponse`> : `NonPaginatedResponse`\<`CaseInstanceGetResponse`>> Promise resolving to either an array of case instances NonPaginatedResponse or a PaginatedResponse when pagination options are used. [CaseInstanceGetResponse](../../type-aliases/CaseInstanceGetResponse/) #### Example ``` // Get all case instances (non-paginated) const instances = await caseInstances.getAll(); // Cancel/Close faulted instances using methods directly on instances for (const instance of instances.items) { if (instance.latestRunStatus === 'Faulted') { await instance.close({ comment: 'Closing faulted case instance' }); } } // With filtering const filteredInstances = await caseInstances.getAll({ processKey: 'MyCaseProcess' }); // First page with pagination const page1 = await caseInstances.getAll({ pageSize: 10 }); // Navigate using cursor if (page1.hasNextPage) { const page2 = await caseInstances.getAll({ cursor: page1.nextCursor }); } ``` ### getById() > **getById**(`instanceId`: `string`, `folderKey`: `string`): `Promise`\<`CaseInstanceGetResponse`> Get a specific case instance by ID #### Parameters - `instanceId`: `string` β€” The case instance ID - `folderKey`: `string` β€” Required folder key #### Returns `Promise`\<`CaseInstanceGetResponse`> Promise resolving to case instance with methods [CaseInstanceGetResponse](../../type-aliases/CaseInstanceGetResponse/) #### Example ``` // Get a specific case instance const instance = await caseInstances.getById( , ); // Access instance properties console.log(`Status: ${instance.latestRunStatus}`); ``` ### getExecutionHistory() > **getExecutionHistory**(`instanceId`: `string`, `folderKey`: `string`): `Promise`\<`CaseInstanceExecutionHistoryResponse`> Get execution history for a case instance #### Parameters - `instanceId`: `string` β€” The ID of the case instance - `folderKey`: `string` β€” Required folder key #### Returns `Promise`\<`CaseInstanceExecutionHistoryResponse`> Promise resolving to instance execution history [CaseInstanceExecutionHistoryResponse](../CaseInstanceExecutionHistoryResponse/) #### Example ``` // Get execution history for a case instance const history = await caseInstances.getExecutionHistory( , ); // Access element executions if (history.elementExecutions) { for (const execution of history.elementExecutions) { console.log(`Element: ${execution.elementName} - Status: ${execution.status}`); } } ``` ### getSlaSummary() > **getSlaSummary**\<`T`>(`options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`SlaSummaryResponse`> : `NonPaginatedResponse`\<`SlaSummaryResponse`>> Get SLA summary for all case instances across folders. Returns SLA status, due times, escalation info, and instance metadata for each case instance. The default page size is 50, so only the top 50 items are returned when no pagination options are provided. #### Type Parameters - `T` *extends* `CaseInstanceSlaSummaryOptions` = `CaseInstanceSlaSummaryOptions` #### Parameters - `options?`: `T` β€” Optional filtering and pagination options #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`SlaSummaryResponse`> : `NonPaginatedResponse`\<`SlaSummaryResponse`>> Promise resolving to [SlaSummaryResponse](../SlaSummaryResponse/), paginated or non-paginated based on options #### Example ``` // Non-paginated (returns top 50 items by default) const summary = await caseInstances.getSlaSummary(); console.log(`Found ${summary.totalCount} cases`); // Filter by case instance ID const filtered = await caseInstances.getSlaSummary({ caseInstanceId: '' }); // Filter by time range const timeFiltered = await caseInstances.getSlaSummary({ startTimeUtc: new Date('2026-01-01'), endTimeUtc: new Date('2026-01-31') }); // With pagination const page1 = await caseInstances.getSlaSummary({ pageSize: 25 }); if (page1.hasNextPage) { const page2 = await caseInstances.getSlaSummary({ cursor: page1.nextCursor }); } // Jump to specific page const page3 = await caseInstances.getSlaSummary({ jumpToPage: 3, pageSize: 25 }); ``` ### getStages() > **getStages**(`caseInstanceId`: `string`, `folderKey`: `string`): `Promise`\<`CaseGetStageResponse`[]> Get stages and its associated tasks information for a case instance #### Parameters - `caseInstanceId`: `string` β€” The ID of the case instance - `folderKey`: `string` β€” Required folder key #### Returns `Promise`\<`CaseGetStageResponse`[]> Promise resolving to an array of case stages with their tasks and status #### Example ``` // Get stages for a case instance const stages = await caseInstances.getStages( , ); // Iterate through stages for (const stage of stages) { console.log(`Stage: ${stage.name} - Status: ${stage.status}`); // Check tasks in the stage for (const taskGroup of stage.tasks) { for (const task of taskGroup) { console.log(` Task: ${task.name} - Status: ${task.status}`); } } } ``` ### getStagesSlaSummary() > **getStagesSlaSummary**(`options?`: `CaseInstanceStageSLAOptions`): `Promise`\<`CaseInstanceStageSLAResponse`[]> Get stages SLA summary for case instances across folders. Returns stage-level SLA status and escalation information for each case instance, aggregated from Insights Real-Time Monitoring. #### Parameters - `options?`: `CaseInstanceStageSLAOptions` β€” Optional filtering options #### Returns `Promise`\<`CaseInstanceStageSLAResponse`[]> Promise resolving to an array of [CaseInstanceStageSLAResponse](../CaseInstanceStageSLAResponse/) #### Example ``` // Get stages SLA summary for all case instances const stagesSla = await caseInstances.getStagesSlaSummary(); for (const item of stagesSla) { console.log(`Instance: ${item.caseInstanceId}`); for (const stage of item.stages) { console.log(` Stage: ${stage.name} - SLA Status: ${stage.slaStatus}, Due: ${stage.slaDueTime}`); } } // Filter by case instance ID const filtered = await caseInstances.getStagesSlaSummary({ caseInstanceId: '' }); // Using bound method on a case instance const instance = await caseInstances.getById('', ''); const stagesSla = await instance.getStagesSlaSummary(); ``` ### pause() > **pause**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `CaseInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Pause a case instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to pause - `folderKey`: `string` β€” Required folder key - `options?`: `CaseInstanceOperationOptions` β€” Optional pause options with comment #### Returns `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Promise resolving to operation result with instance data ### reopen() > **reopen**(`instanceId`: `string`, `folderKey`: `string`, `options`: `CaseInstanceReopenOptions`): `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Reopen a case instance from a specified element #### Parameters - `instanceId`: `string` β€” The ID of the case instance - `folderKey`: `string` β€” Required folder key - `options`: `CaseInstanceReopenOptions` β€” Reopen options containing stageId (the stage ID to resume from) and an optional comment #### Returns `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Promise resolving to operation result with instance data [CaseInstanceOperationResponse](../CaseInstanceOperationResponse/) #### Example ``` import { CaseInstances } from '@uipath/uipath-typescript/cases'; const caseInstances = new CaseInstances(sdk); // First, get the available stages for the case instance const stages = await caseInstances.getStages('', ''); const stageId = stages[0].id; // Select the stage to reopen from // Reopen a case instance from a specific stage const result = await caseInstances.reopen( '', '', { stageId } ); // Reopen with a comment const result = await caseInstances.reopen( '', '', { stageId, comment: 'Reopening to retry failed stage' } ); // Or using instance method const instance = await caseInstances.getById('', ''); const stages = await instance.getStages(); const result = await instance.reopen({ stageId: stages[0].id }); ``` ### resume() > **resume**(`instanceId`: `string`, `folderKey`: `string`, `options?`: `CaseInstanceOperationOptions`): `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Resume a case instance #### Parameters - `instanceId`: `string` β€” The ID of the instance to resume - `folderKey`: `string` β€” Required folder key - `options?`: `CaseInstanceOperationOptions` β€” Optional resume options with comment #### Returns `Promise`\<`OperationResponse`\<`CaseInstanceOperationResponse`>> Promise resolving to operation result with instance data ### sendMessage() > **sendMessage**(`instanceId`: `string`, `folderKey`: `string`, `name`: `string`, `options?`: `CaseInstanceSendMessageOptions`): `Promise`\<`void`> Send a message to a running case instance Messages resolve wait points in the case β€” selecting the next stage when the case is waiting for a user to choose one, or starting a manually-triggered (ad-hoc) case task. #### Parameters - `instanceId`: `string` β€” The ID of the case instance to send the message to - `folderKey`: `string` β€” Required folder key - `name`: `string` β€” The message name β€” a well-known `CaseInstanceMessageName` or a custom message name defined in the case model - `options?`: `CaseInstanceSendMessageOptions` β€” Optional message options with itemData payload and reference override #### Returns `Promise`\<`void`> Promise that resolves when the message is accepted #### Example ``` import { CaseInstances, CaseInstanceMessageName } from '@uipath/uipath-typescript/cases'; const caseInstances = new CaseInstances(sdk); // Select the next stage when the case is waiting for a user to choose one await caseInstances.sendMessage( '', '', CaseInstanceMessageName.UserSelectStage, { itemData: { stageName: 'Review' } } ); // Start a manually-triggered (ad-hoc) case task await caseInstances.sendMessage( '', '', CaseInstanceMessageName.UserAdhocTrigger, { itemData: { taskNames: ['Approve Invoice'] } } ); // Or using instance method const instance = await caseInstances.getById('', ''); await instance.sendMessage( CaseInstanceMessageName.UserAdhocTrigger, { itemData: { taskNames: ['Approve Invoice'] } } ); ``` Service for managing UiPath Conversational Agents β€” AI-powered chat interfaces that enable natural language interactions with UiPath automation. Discover agents, create conversations, and stream real-time responses over WebSocket. [UiPath Conversational Agents Guide](https://docs.uipath.com/agents/automation-cloud/latest/user-guide/conversational-agents) ## How It Works ### Lifecycle ``` graph TD A["Agent"] -->|conversations.create| B["Conversation"] B -->|startSession| C["Session"] B -->|exchanges.getAll| F(["History"]) C -->|onSessionStarted| D["Ready"] D -->|startExchange| E["Exchange"] E -->|sendMessage| G["Message"] ``` ### Real-Time Event Flow Once a session is started, events flow through a nested stream hierarchy: ``` graph TD S["SessionStream"] S -->|onExchangeStart| E["ExchangeStream"] S -->|onSessionEnd| SE(["session closed"]) E -->|onMessageStart| M["MessageStream"] E -->|sendExchangeEnd| STOP(["stop response"]) E -->|onExchangeEnd| EE(["exchange complete"]) M -->|onContentPartStart| CP["ContentPartStream"] M -->|onToolCallStart| TC["ToolCallStream"] M -->|onInterruptStart| IR(["awaiting approval"]) CP -->|onChunk| CH(["streaming data"]) TC -->|onToolCallEnd| TCE(["tool result"]) ``` ## Usage ``` import { ConversationalAgent } from '@uipath/uipath-typescript/conversational-agent'; const conversationalAgent = new ConversationalAgent(sdk); // 1. Discover agents const agents = await conversationalAgent.getAll(); const agent = agents[0]; // 2. Create a conversation const conversation = await agent.conversations.create({ label: 'My Chat' }); // 3. Start real-time session and listen for responses const session = conversation.startSession(); session.onExchangeStart((exchange) => { exchange.onMessageStart((message) => { if (message.isAssistant) { message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => process.stdout.write(chunk.data ?? '')); } }); } }); }); // 4. Wait for session to be ready, then send a message session.onSessionStarted(() => { const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello!' }); }); // 5. Stop a response mid-stream // Use sendExchangeEnd() on any active exchange to stop the agent session.onSessionStarted(() => { const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Tell me a long story' }); // Stop after 5 seconds setTimeout(() => exchange.sendExchangeEnd(), 5000); }); // 6. End session when done conversation.endSession(); // 7. Retrieve conversation history (offline) const exchanges = await conversation.exchanges.getAll(); ``` ## Properties | Property | Modifier | Type | Description | | --------------- | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `conversations` | `readonly` | `ConversationServiceModel` | Service for creating and managing conversations. See [ConversationServiceModel](../ConversationServiceModel/). | | `user` | `readonly` | `UserSettingsServiceModel` | Service for reading and updating the current user's profile/context settings. See [UserSettingsServiceModel](../UserSettingsServiceModel/). | ## Methods ### getAll() > **getAll**(`folderId?`: `number`): `Promise`\<`AgentGetResponse`[]> Gets all available conversational agents #### Parameters - `folderId?`: `number` β€” Optional folder ID to filter agents #### Returns `Promise`\<`AgentGetResponse`[]> Promise resolving to an array of agents [AgentGetResponse](../../type-aliases/AgentGetResponse/) #### Examples ``` const agents = await conversationalAgent.getAll(); const agent = agents[0]; // Create conversation directly from agent (agentId and folderId are auto-filled) const conversation = await agent.conversations.create({ label: 'My Chat' }); ``` ``` const agents = await conversationalAgent.getAll(folderId); ``` ### getById() > **getById**(`id`: `number`, `folderId`: `number`): `Promise`\<`AgentGetByIdResponse`> Gets a specific agent by ID #### Parameters - `id`: `number` β€” ID of the agent release - `folderId`: `number` β€” ID of the folder containing the agent #### Returns `Promise`\<`AgentGetByIdResponse`> Promise resolving to the agent [AgentGetByIdResponse](../../type-aliases/AgentGetByIdResponse/) #### Example ``` const agent = await conversationalAgent.getById(agentId, folderId); // Create conversation directly from agent (agentId and folderId are auto-filled) const conversation = await agent.conversations.create({ label: 'My Chat' }); ``` ### onConnectionStatusChanged() > **onConnectionStatusChanged**(`handler`: (`status`: `ConnectionStatus`, `error`: `null` | `Error`) => `void`): () => `void` Registers a handler that is called whenever the WebSocket connection status changes. #### Parameters - `handler`: (`status`: `ConnectionStatus`, `error`: `null` | `Error`) => `void` β€” Callback receiving a ConnectionStatus (`'Disconnected'` #### Returns Cleanup function to remove the handler #### Example ``` const cleanup = conversationalAgent.onConnectionStatusChanged((status, error) => { console.log('Connection status:', status); if (error) { console.error('Connection error:', error.message); } }); // Later, remove the handler cleanup(); ``` Service for creating and managing conversations with UiPath Conversational Agents A conversation is a long-lived interaction with a specific agent with shared context. It persists across sessions and can be resumed at any time. To retrieve the conversation history, use the [Exchanges](../ExchangeServiceModel/) service. For real-time chat, see [Session](../SessionStream/). ### Usage ``` import { ConversationalAgent } from '@uipath/uipath-typescript/conversational-agent'; const conversationalAgent = new ConversationalAgent(sdk); // Access conversations through the main service const conversation = await conversationalAgent.conversations.create(agentId, folderId); // Or through agent objects (agentId/folderId auto-filled) const agents = await conversationalAgent.getAll(); const agentConversation = await agents[0].conversations.create({ label: 'My Chat' }); ``` ## Methods ### create() > **create**(`agentId`: `number`, `folderId`: `number`, `options?`: `ConversationCreateOptions`): `Promise`\<`ConversationCreateResponse`> Creates a new conversation The returned conversation has bound methods for lifecycle management: `update()`, `delete()`, and `startSession()`. #### Parameters - `agentId`: `number` β€” The agent ID to create the conversation for - `folderId`: `number` β€” The folder ID containing the agent - `options?`: `ConversationCreateOptions` β€” Optional settings for the conversation #### Returns `Promise`\<`ConversationCreateResponse`> Promise resolving to [ConversationCreateResponse](../ConversationCreateResponse/) with bound methods #### Examples ``` const conversation = await conversationalAgent.conversations.create( agentId, folderId, { label: 'Customer Support Session' } ); // Update the conversation await conversation.update({ label: 'Renamed Chat' }); // Start a real-time session const session = conversation.startSession(); // Delete the conversation await conversation.delete(); ``` ``` const conversation = await conversationalAgent.conversations.create( agentId, folderId, { agentInput: { inline: { userId: 'user-123', language: 'en' } } } ); ``` ### deleteById() > **deleteById**(`id`: `string`): `Promise`\<`ConversationDeleteResponse`> Deletes a conversation by ID #### Parameters - `id`: `string` β€” The conversation ID to delete #### Returns `Promise`\<`ConversationDeleteResponse`> Promise resolving to [ConversationDeleteResponse](../ConversationDeleteResponse/) #### Example ``` await conversationalAgent.conversations.deleteById(conversationId); ``` ### disconnect() > **disconnect**(): `void` Closes the WebSocket connection and releases all session resources. In Node.js the WebSocket keeps the event loop alive until disconnected, so call this to allow the process to exit cleanly. In the browser the runtime handles socket cleanup on page unload, so this is effectively a no-op. #### Returns `void` #### Example ``` conversationalAgent.conversations.disconnect(); ``` ### endSession() > **endSession**(`conversationId`: `string`): `void` Ends an active session for a conversation Sends a session end event and releases the socket for the conversation. If no active session exists for the given conversation, this is a no-op. #### Parameters - `conversationId`: `string` β€” The conversation ID to end the session for #### Returns `void` #### Example ``` // End session for a specific conversation conversationalAgent.conversations.endSession(conversationId); ``` ### getAll() > **getAll**(`options?`: `ConversationGetAllOptions`): `Promise`\<`PaginatedResponse`\<`ConversationGetResponse`>> Gets conversations with pagination and optional sort/filter parameters Returns a paginated response. When called without `pageSize`/`cursor`, a default page size is applied - inspect `hasNextPage`/`nextCursor` to navigate further pages. #### Parameters - `options?`: `ConversationGetAllOptions` β€” Options for querying conversations #### Returns `Promise`\<`PaginatedResponse`\<`ConversationGetResponse`>> Promise resolving to a [PaginatedResponse](../PaginatedResponse/)\<[ConversationGetResponse](../../type-aliases/ConversationGetResponse/)> #### Examples ``` // First page const firstPage = await conversationalAgent.conversations.getAll(); for (const conversation of firstPage.items) { console.log(`${conversation.label} - created: ${conversation.createdTime}`); } // Navigate using cursor if (firstPage.hasNextPage) { const nextPage = await conversationalAgent.conversations.getAll({ cursor: firstPage.nextCursor }); } ``` ``` import { SortOrder } from '@uipath/uipath-typescript/conversational-agent'; // First page const firstPage = await conversationalAgent.conversations.getAll({ pageSize: 10, sort: SortOrder.Descending }); // Navigate using cursor and same parameters if (firstPage.hasNextPage) { const nextPage = await conversationalAgent.conversations.getAll({ pageSize: 10, sort: SortOrder.Descending, cursor: firstPage.nextCursor }); } ``` ``` const firstPage = await conversationalAgent.conversations.getAll({ agentId: , label: 'budget' }); // Navigate using cursor and same parameters if (firstPage.hasNextPage) { const nextPage = await conversationalAgent.conversations.getAll({ agentId: , label: 'budget', cursor: firstPage.nextCursor }); } ``` ### getAttachmentUploadUri() > **getAttachmentUploadUri**(`conversationId`: `string`, `fileName`: `string`): `Promise`\<`ConversationAttachmentCreateResponse`> Registers a file attachment for a conversation and returns a URI along with pre-signed upload access details. Use the returned `fileUploadAccess` to upload the file content to blob storage, then reference `uri` in subsequent messages. #### Parameters - `conversationId`: `string` β€” The ID of the conversation to attach the file to - `fileName`: `string` β€” The name of the file to attach #### Returns `Promise`\<`ConversationAttachmentCreateResponse`> Promise resolving to [ConversationAttachmentCreateResponse](../ConversationAttachmentCreateResponse/) containing the attachment `uri` and `fileUploadAccess` details needed to upload the file content #### Examples ``` const { uri, fileUploadAccess } = await conversationalAgent.conversations.getAttachmentUploadUri(conversationId, 'report.pdf'); console.log(`Attachment URI: ${uri}`); ``` ``` const { uri, fileUploadAccess } = await conversationalAgent.conversations.getAttachmentUploadUri(conversationId, file.name); await fetch(fileUploadAccess.url, { method: fileUploadAccess.verb, body: file, headers: { 'Content-Type': file.type }, }); // Reference the URI in a message after upload console.log(`File ready at: ${uri}`); ``` ### getById() > **getById**(`id`: `string`): `Promise`\<`ConversationGetResponse`> Gets a conversation by ID The returned conversation has bound methods for lifecycle management: `update()`, `delete()`, and `startSession()`. #### Parameters - `id`: `string` β€” The conversation ID to retrieve #### Returns `Promise`\<`ConversationGetResponse`> Promise resolving to [ConversationGetResponse](../../type-aliases/ConversationGetResponse/) with bound methods #### Examples ``` const conversation = await conversationalAgent.conversations.getById(conversationId); const session = conversation.startSession(); ``` ``` //Retrieve conversation history const conversation = await conversationalAgent.conversations.getById(conversationId); const allExchanges = await conversation.exchanges.getAll(); for (const exchange of allExchanges.items) { for (const message of exchange.messages) { console.log(`${message.role}: ${message.contentParts.map(p => p.data).join('')}`); } } ``` ### getSession() > **getSession**(`conversationId`: `string`): `undefined` | `SessionStream` Retrieves an active session by conversation ID #### Parameters - `conversationId`: `string` β€” The conversation ID to get the session for #### Returns `undefined` | `SessionStream` The session helper if active, undefined otherwise #### Example ``` const session = conversationalAgent.conversations.getSession(conversationId); if (session) { // Session already started β€” safe to send exchanges directly const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello!' }); } ``` ### startSession() > **startSession**(`conversationId`: `string`, `options?`: `ConversationSessionOptions`): `SessionStream` Starts a real-time chat session for a conversation Creates a WebSocket session and returns a SessionStream for sending and receiving messages in real-time. #### Parameters - `conversationId`: `string` β€” The conversation ID to start the session for - `options?`: `ConversationSessionOptions` β€” Optional session configuration #### Returns `SessionStream` SessionStream for managing the session #### Example ``` const session = conversationalAgent.conversations.startSession(conversation.id); // Listen for responses using helper methods session.onExchangeStart((exchange) => { exchange.onMessageStart((message) => { // Use message.isAssistant to filter AI responses if (message.isAssistant) { message.onContentPartStart((part) => { // Use part.isMarkdown to handle text content if (part.isMarkdown) { part.onChunk((chunk) => console.log(chunk.data)); } }); } }); }); // Wait for session to be ready, then send a message session.onSessionStarted(() => { const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello!' }); }); // End the session when done conversationalAgent.conversations.endSession(conversation.id); ``` ### updateById() > **updateById**(`id`: `string`, `options`: `ConversationUpdateOptions`): `Promise`\<`ConversationUpdateResponse`> Updates a conversation by ID #### Parameters - `id`: `string` β€” The conversation ID to update - `options`: `ConversationUpdateOptions` β€” Fields to update #### Returns `Promise`\<`ConversationUpdateResponse`> Promise resolving to [ConversationGetResponse](../../type-aliases/ConversationGetResponse/) with bound methods #### Example ``` const updatedConversation = await conversationalAgent.conversations.updateById(conversationId, { label: 'Updated Name' }); ``` ### uploadAttachment() > **uploadAttachment**(`id`: `string`, `file`: `File`): `Promise`\<`ConversationAttachmentUploadResponse`> Uploads a file attachment to a conversation #### Parameters - `id`: `string` β€” The ID of the conversation to attach the file to - `file`: `File` β€” The file to upload #### Returns `Promise`\<`ConversationAttachmentUploadResponse`> Promise resolving to attachment metadata with URI [ConversationAttachmentUploadResponse](../ConversationAttachmentUploadResponse/) #### Example ``` const attachment = await conversationalAgent.conversations.uploadAttachment(conversationId, file); console.log(`Uploaded: ${attachment.uri}`); ``` Service for retrieving exchanges and managing feedback within a [Conversation](../ConversationServiceModel/) An exchange represents a single request-response cycle β€” typically one user question and the agent's reply. Each exchange response includes its [Messages](../MessageServiceModel/), making this the primary way to retrieve conversation history. For real-time streaming of exchanges, see [ExchangeStream](../ExchangeStream/). ### Usage ``` import { Exchanges } from '@uipath/uipath-typescript/conversational-agent'; const exchanges = new Exchanges(sdk); const conversationExchanges = await exchanges.getAll(conversationId); ``` ## Methods ### createFeedback() > **createFeedback**(`conversationId`: `string`, `exchangeId`: `string`, `options`: `CreateFeedbackOptions`): `Promise`\<`FeedbackCreateResponse`> Creates feedback for an exchange #### Parameters - `conversationId`: `string` β€” The conversation containing the exchange - `exchangeId`: `string` β€” The exchange to provide feedback for - `options`: `CreateFeedbackOptions` β€” Feedback data including rating and optional comment #### Returns `Promise`\<`FeedbackCreateResponse`> Promise resolving to the feedback creation response [FeedbackCreateResponse](../FeedbackCreateResponse/) #### Example ``` await exchanges.createFeedback( conversationId, exchangeId, { rating: FeedbackRating.Positive, comment: 'Very helpful!' } ); ``` ### getAll() > **getAll**(`conversationId`: `string`, `options?`: `ExchangeGetAllOptions`): `Promise`\<`PaginatedResponse`\<`ExchangeGetResponse`>> Gets exchanges for a conversation with pagination and optional sort parameters Returns a paginated response. When called without `pageSize`/`cursor`, the backend applies its default page size β€” inspect `hasNextPage`/`nextCursor` to navigate further pages. #### Parameters - `conversationId`: `string` β€” The conversation ID to get exchanges for - `options?`: `ExchangeGetAllOptions` β€” Options for querying exchanges including optional pagination parameters #### Returns `Promise`\<`PaginatedResponse`\<`ExchangeGetResponse`>> Promise resolving to a [PaginatedResponse](../PaginatedResponse/)\<[ExchangeGetResponse](../ExchangeGetResponse/)> #### Examples ``` // First page const firstPage = await exchanges.getAll(conversationId); // Navigate using cursor if (firstPage.hasNextPage) { const nextPage = await exchanges.getAll(conversationId, { cursor: firstPage.nextCursor }); } ``` ``` import { SortOrder } from '@uipath/uipath-typescript/conversational-agent'; const firstPage = await exchanges.getAll(conversationId, { pageSize: 10, exchangeSort: SortOrder.Descending, messageSort: SortOrder.Ascending }); // Navigate using cursor and same parameters if (firstPage.hasNextPage) { const nextPage = await exchanges.getAll(conversationId, { pageSize: 10, exchangeSort: SortOrder.Descending, messageSort: SortOrder.Ascending, cursor: firstPage.nextCursor }); } ``` ### getById() > **getById**(`conversationId`: `string`, `exchangeId`: `string`, `options?`: `ExchangeGetByIdOptions`): `Promise`\<`ExchangeGetResponse`> Gets an exchange by ID with its messages #### Parameters - `conversationId`: `string` β€” The conversation containing the exchange - `exchangeId`: `string` β€” The exchange ID to retrieve - `options?`: `ExchangeGetByIdOptions` β€” Optional parameters for message sorting #### Returns `Promise`\<`ExchangeGetResponse`> Promise resolving to [ExchangeGetResponse](../ExchangeGetResponse/) #### Example ``` const exchange = await exchanges.getById(conversationId, exchangeId); // Access messages for (const message of exchange.messages) { console.log(message.role, message.contentParts); } ``` Service for retrieving individual messages within an [Exchange](../ExchangeServiceModel/) A message is a single turn from a user, assistant, or system. Each message includes a role, contentParts (text, audio, images), toolCalls, and interrupts. Messages are also returned as part of exchange responses β€” use this service when you need to fetch a specific message by ID or retrieve external content parts. For real-time streaming of messages, see [MessageStream](../MessageStream/). ### Usage ``` import { Messages } from '@uipath/uipath-typescript/conversational-agent'; const message = new Messages(sdk); const messageDetails = await message.getById(conversationId, exchangeId, messageId); ``` ## Methods ### getById() > **getById**(`conversationId`: `string`, `exchangeId`: `string`, `messageId`: `string`): `Promise`\<`MessageGetResponse`> Gets a message by ID Returns the message including its content parts, tool calls, and interrupts. #### Parameters - `conversationId`: `string` β€” The conversation containing the message - `exchangeId`: `string` β€” The exchange containing the message - `messageId`: `string` β€” The message ID to retrieve #### Returns `Promise`\<`MessageGetResponse`> Promise resolving to [MessageGetResponse](../MessageGetResponse/) #### Example ``` const message = await messages.getById(conversationId, exchangeId, messageId); console.log(message.role); console.log(message.contentParts); console.log(message.toolCalls); ``` ### getContentPartById() > **getContentPartById**(`conversationId`: `string`, `exchangeId`: `string`, `messageId`: `string`, `contentPartId`: `string`): `Promise`\<`ContentPartGetResponse`> Gets an external content part by ID #### Parameters - `conversationId`: `string` β€” The conversation containing the content - `exchangeId`: `string` β€” The exchange containing the content - `messageId`: `string` β€” The message containing the content part - `contentPartId`: `string` β€” The content part ID to retrieve #### Returns `Promise`\<`ContentPartGetResponse`> Promise resolving to [ContentPartGetResponse](../ContentPartGetResponse/) #### Example ``` const contentPart = await messages.getContentPartById( conversationId, exchangeId, messageId, contentPartId ); ``` Service for reading and updating the current user's profile and context settings. User settings are user-supplied profile fields (name, email, role, department, company, country, timezone) that the SDK passes to a UiPath Conversational Agent on every conversation so the agent can personalize its responses. Settings are scoped to the calling user β€” identified by the access token for user tokens, or by the externalUserId option for app-scoped tokens. Accessed via `conversationalAgent.user`. ## Examples ``` import { ConversationalAgent } from '@uipath/uipath-typescript/conversational-agent'; const conversationalAgent = new ConversationalAgent(sdk); const settings = await conversationalAgent.user.getSettings(); console.log(settings.name, settings.email, settings.timezone); ``` ``` await conversationalAgent.user.updateSettings({ name: 'John Doe', timezone: 'America/New_York' }); ``` ``` await conversationalAgent.user.updateSettings({ department: null }); ``` ## Methods ### getSettings() > **getSettings**(): `Promise`\<`UserSettingsGetResponse`> Gets the current user's profile and context settings. Returns the full user settings record β€” profile fields the agent uses for personalization (name, email, role, department, company, country, timezone) plus identifiers and timestamps. Fields the user has not set are returned as `null`. #### Returns `Promise`\<`UserSettingsGetResponse`> Promise resolving to the current user's settings [UserSettingsGetResponse](../UserSettingsGetResponse/) #### Example ``` const settings = await conversationalAgent.user.getSettings(); console.log(settings.name); // e.g. 'John Doe' or null console.log(settings.email); // e.g. 'john@example.com' or null console.log(settings.timezone); // e.g. 'America/New_York' or null ``` ### updateSettings() > **updateSettings**(`options`: `UserSettingsUpdateOptions`): `Promise`\<`UserSettingsUpdateResponse`> Updates the current user's profile and context settings. Accepts a partial payload β€” only fields included in `options` are changed. Pass `null` to explicitly clear a field. Omitting a field leaves it unchanged. Returns the full updated settings record. #### Parameters - `options`: `UserSettingsUpdateOptions` β€” Fields to update; omit fields to leave them unchanged, set to `null` to clear #### Returns `Promise`\<`UserSettingsUpdateResponse`> Promise resolving to the updated user settings [UserSettingsUpdateResponse](../UserSettingsUpdateResponse/) #### Examples ``` const updated = await conversationalAgent.user.updateSettings({ name: 'John Doe', timezone: 'America/New_York' }); ``` ``` await conversationalAgent.user.updateSettings({ role: null, department: null }); ``` Service for retrieving runtime data for UiPath Agents. UiPath Agents are AI-driven automations powered by large language models and machine learning that plan, make decisions, and execute tasks in dynamic environments. See [About Agents](https://docs.uipath.com/agents/automation-cloud/latest/user-guide/about-agents) for an overview of UiPath Agents. ### Usage ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); const list = await agents.getAll( new Date('2025-01-01T00:00:00Z'), new Date('2025-02-01T00:00:00Z'), ); ``` ## Methods ### getAll() > **getAll**\<`T`>(`startTime`: `Date`, `endTime`: `Date`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`AgentListItem`> : `NonPaginatedResponse`\<`AgentListItem`>> Retrieves the list of agents on the tenant with consumption and health metadata over the requested window. Returns a [PaginatedResponse](../PaginatedResponse/) when pagination options (`pageSize`, `cursor`, or `jumpToPage`) are provided, otherwise a [NonPaginatedResponse](../NonPaginatedResponse/). #### Type Parameters - `T` *extends* `AgentGetAllOptions` = `AgentGetAllOptions` #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `T` β€” Optional pagination, sort, and filters #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`AgentListItem`> : `NonPaginatedResponse`\<`AgentListItem`>> Promise resolving to a paginated or non-paginated list of [AgentListItem](../AgentListItem/) #### Example ``` import { Agents, AgentListSortColumn } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Non-paginated β€” returns the server default page const result = await agents.getAll( new Date('2025-05-01T00:00:00Z'), new Date('2026-05-14T00:00:00Z'), ); result.items.forEach((agent) => { console.log(`${agent.agentName} β€” ${agent.unitsQuantity} units, health=${agent.healthScore}`); }); // Paginated β€” sorted by health score descending const page = await agents.getAll( new Date('2025-05-01T00:00:00Z'), new Date('2026-05-14T00:00:00Z'), { pageSize: 25, orderBy: { column: AgentListSortColumn.HealthScore, desc: true }, folderKeys: [''], }, ); if (page.hasNextPage && page.nextCursor) { const next = await agents.getAll( new Date('2025-05-01T00:00:00Z'), new Date('2026-05-14T00:00:00Z'), { cursor: page.nextCursor }, ); } ``` ### getConsumptionTimeline() > **getConsumptionTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetConsumptionTimelineOptions`): `Promise`\<`AgentGetConsumptionTimelineResponse`[]> Retrieves a time-series of Agent Units consumption over the requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetConsumptionTimelineOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetConsumptionTimelineResponse`[]> Promise resolving to an array of [AgentGetConsumptionTimelineResponse](../AgentGetConsumptionTimelineResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Agent Units consumption timeline in May 2025 const result = await agents.getConsumptionTimeline( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); result.forEach((point) => { console.log(`${point.timeSlice}: ${point.aguConsumption} Agent Units`); }); ``` ``` // Scope to specific folders and agents const result = await agents.getConsumptionTimeline( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { folderKeys: [''], agentNames: ['JokeAgent'], }, ); ``` ### getErrors() > **getErrors**\<`T`>(`startTime`: `Date`, `endTime`: `Date`, `options?`: `T`): `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`AgentError`> : `NonPaginatedResponse`\<`AgentError`>> Retrieves agent errors (error-classes observed for agents) over the requested window. Returns a [PaginatedResponse](../PaginatedResponse/) when pagination options (`pageSize`, `cursor`, or `jumpToPage`) are provided, otherwise a [NonPaginatedResponse](../NonPaginatedResponse/). #### Type Parameters - `T` *extends* `AgentGetErrorsOptions` = `AgentGetErrorsOptions` #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `T` β€” Optional pagination, sort/group, and filters #### Returns `Promise`\<`T` *extends* `HasPaginationOptions`\<`T`> ? `PaginatedResponse`\<`AgentError`> : `NonPaginatedResponse`\<`AgentError`>> Promise resolving to a paginated or non-paginated list of [AgentError](../AgentError/) #### Example ``` import { Agents, AgentErrorSortColumn } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Non-paginated β€” errors in the window const result = await agents.getErrors( new Date('2025-05-01T00:00:00Z'), new Date('2026-05-14T00:00:00Z'), ); result.items.forEach((error) => { console.log(`${error.type}: ${error.description} (count=${error.count})`); }); // Paginated β€” sorted by execution count descending const page = await agents.getErrors( new Date('2025-05-01T00:00:00Z'), new Date('2026-05-14T00:00:00Z'), { pageSize: 25, orderBy: { column: AgentErrorSortColumn.ExecutionCount, desc: true }, }, ); if (page.hasNextPage && page.nextCursor) { const next = await agents.getErrors( new Date('2025-05-01T00:00:00Z'), new Date('2026-05-14T00:00:00Z'), { cursor: page.nextCursor }, ); } ``` ### getErrorsTimeline() > **getErrorsTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetErrorsTimelineOptions`): `Promise`\<`AgentGetErrorsTimelineResponse`[]> Retrieves a time-series of error counts grouped by agent over the requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetErrorsTimelineOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetErrorsTimelineResponse`[]> Promise resolving to an array of [AgentGetErrorsTimelineResponse](../AgentGetErrorsTimelineResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // All errors in May 2025 const result = await agents.getErrorsTimeline( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); result.forEach((point) => { console.log(`${point.date} ${point.name}: ${point.value} errors`); }); ``` ``` // Scope to specific folders and top 5 agents const result = await agents.getErrorsTimeline( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { folderKeys: [''], agentNames: ['JokeAgent', 'StoryAgent'], limit: 5, }, ); ``` ### getIncidentDistribution() > **getIncidentDistribution**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetIncidentDistributionOptions`): `Promise`\<`AgentGetIncidentDistributionResponse`> Retrieves breakdown of agent incidents count β€” errors, escalations, and policy violations over a requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetIncidentDistributionOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetIncidentDistributionResponse`> Promise resolving to [AgentGetIncidentDistributionResponse](../AgentGetIncidentDistributionResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Incident distribution in May 2025 const result = await agents.getIncidentDistribution( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); console.log(`Errors: ${result.errorCount}, Escalations: ${result.escalationCount}, Policy: ${result.policyCount}`); ``` ``` // Scope to specific folders const result = await agents.getIncidentDistribution( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { folderKeys: [''], }, ); ``` ### getLatencyTimeline() > **getLatencyTimeline**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetLatencyTimelineOptions`): `Promise`\<`AgentGetLatencyTimelineResponse`[]> Retrieves a time-series of agent latency (milliseconds) over the requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetLatencyTimelineOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetLatencyTimelineResponse`[]> Promise resolving to an array of [AgentGetLatencyTimelineResponse](../AgentGetLatencyTimelineResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Latency timeline in May 2025 const result = await agents.getLatencyTimeline( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); result.forEach((point) => { console.log(`${point.date} ${point.name}: ${point.value} ms`); }); ``` ``` // Scope to specific folders and a single agent const result = await agents.getLatencyTimeline( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { folderKeys: [''], agentId: '', }, ); ``` ### getSummary() > **getSummary**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetSummaryOptions`): `Promise`\<`AgentGetSummaryResponse`> Retrieves a job-execution summary for the requested window: overall totals (total jobs, successful jobs, success rate, average duration) alongside a per-agent breakdown. When `lookbackPeriodAnalysis` is enabled, a comparable summary for the preceding window of equal length is included too. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetSummaryOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetSummaryResponse`> Promise resolving to [AgentGetSummaryResponse](../AgentGetSummaryResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Summary for May 2025 const result = await agents.getSummary( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); console.log(`Success rate: ${result.currentPeriodSummary.successRate}%`); ``` ``` import { Agents, AgentExecutionType } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Runtime-only summary with lookback comparison const result = await agents.getSummary( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { lookbackPeriodAnalysis: true, executionType: AgentExecutionType.Runtime, }, ); ``` ### getTopConsumption() > **getTopConsumption**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetTopConsumptionOptions`): `Promise`\<`AgentGetTopConsumptionResponse`> Retrieves the top-N agents ranked by unit consumption over the requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetTopConsumptionOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetTopConsumptionResponse`> Promise resolving to [AgentGetTopConsumptionResponse](../AgentGetTopConsumptionResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Top agents by consumption in May 2025 const result = await agents.getTopConsumption( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); console.log(`Total consumed: ${result.totalConsumed}`); result.agents.forEach((agent) => { console.log(`${agent.agentName}: ${agent.consumedQuantity}`); }); ``` ``` import { Agents, AgentType } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Top 5 healthy autonomous agents by consumption const result = await agents.getTopConsumption( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { limit: 5, healthy: true, agentTypes: [AgentType.Autonomous], }, ); ``` ### getTopErrorCount() > **getTopErrorCount**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetTopErrorCountOptions`): `Promise`\<`AgentGetTopErrorCountResponse`> Retrieves the top-N agents ranked by error count over the requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetTopErrorCountOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetTopErrorCountResponse`> Promise resolving to [AgentGetTopErrorCountResponse](../AgentGetTopErrorCountResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Top agents by error count in May 2025 const result = await agents.getTopErrorCount( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); result.data.forEach((agent) => { console.log(`${agent.name}: ${agent.count} errors`); }); ``` ``` // Scope to specific folders and top 5 agents const result = await agents.getTopErrorCount( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { folderKeys: [''], limit: 5, }, ); ``` ### getUnitConsumptionSummary() > **getUnitConsumptionSummary**(`startTime`: `Date`, `endTime`: `Date`, `options?`: `AgentGetUnitConsumptionSummaryOptions`): `Promise`\<`AgentGetUnitConsumptionSummaryResponse`> Retrieves an aggregate Agent Units and Platform Units consumption summary per agent over the requested window. #### Parameters - `startTime`: `Date` β€” Inclusive lower bound for the query window - `endTime`: `Date` β€” Exclusive upper bound for the query window - `options?`: `AgentGetUnitConsumptionSummaryOptions` β€” Optional filters #### Returns `Promise`\<`AgentGetUnitConsumptionSummaryResponse`> Promise resolving to [AgentGetUnitConsumptionSummaryResponse](../AgentGetUnitConsumptionSummaryResponse/) #### Examples ``` import { Agents } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Unit consumption summary for May 2025 const result = await agents.getUnitConsumptionSummary( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), ); console.log(`Agent Units complete jobs: ${result.currentPeriodSummary.totalAgentUnitConsumption.completeJobs}`); ``` ``` import { Agents, AgentExecutionType } from '@uipath/uipath-typescript/agents'; const agents = new Agents(sdk); // Runtime-only summary with lookback comparison const result = await agents.getUnitConsumptionSummary( new Date('2025-05-01T00:00:00Z'), new Date('2025-06-01T00:00:00Z'), { lookbackPeriodAnalysis: true, executionType: AgentExecutionType.Runtime, }, ); ``` Real-time WebSocket session for two-way communication within a [Conversation](../ConversationServiceModel/). Send messages and receive agent responses through a nested stream hierarchy. The `SessionStream` is the top-level entry point β€” events flow down through exchanges, messages, content parts, and tool calls. ### Usage **Important:** Always wait for `onSessionStarted` before calling `startExchange`. The session must be fully connected via WebSocket before exchanges can be sent β€” calling `startExchange` earlier may lose events or cause errors. ``` const session = conversation.startSession(); // Set up handlers for incoming assistant responses session.onExchangeStart((exchange) => { exchange.onMessageStart((message) => { if (message.isAssistant) { message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => { process.stdout.write(chunk.data ?? ''); }); } }); } }); }); // Wait for the session to be ready, then send a message session.onSessionStarted(() => { const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello!', role: MessageRole.User }); }); // End the session when done conversation.endSession(); ``` ### Related Streams | Stream | Description | | ------------------------------------------ | ----------------------------------------------------------------------------------------------------- | | [ExchangeStream](../ExchangeStream/) | A single request-response cycle within a session. Contains user and assistant messages. | | [MessageStream](../MessageStream/) | A single message (user, assistant, or system). Contains content parts and tool calls. | | [ContentPartStream](../ContentPartStream/) | A piece of streamed content (text, audio, image, transcript). Delivers data via `onChunk`. | | [ToolCallStream](../ToolCallStream/) | An external tool invocation by the assistant. Has a start event (name, input) and end event (output). | ## Properties | Property | Modifier | Type | Description | | ---------------- | ---------- | ----------------------------- | -------------------------------------------------- | | `conversationId` | `readonly` | `string` | The conversation ID this session belongs to | | `ended` | `readonly` | `boolean` | Whether this session has ended | | `exchanges` | `readonly` | `Iterable`\<`ExchangeStream`> | Iterator over all active exchanges in this session | ## Methods ### getExchange() > **getExchange**(`exchangeId`: `string`): `undefined` | `ExchangeStream` Retrieves an exchange by ID #### Parameters - `exchangeId`: `string` β€” The exchange ID to look up #### Returns `undefined` | `ExchangeStream` The exchange stream, or undefined if not found ### onErrorEnd() > **onErrorEnd**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void`): () => `void` Registers a handler for error end events at the session level #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void` β€” Callback receiving the error end event #### Returns Cleanup function to remove the handler #### Example ``` session.onErrorEnd((error) => { console.log(`Error ${error.errorId} resolved`); }); ``` ### onErrorStart() > **onErrorStart**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void`): () => `void` Registers a handler for error start events at the session level #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void` β€” Callback receiving the error event #### Returns Cleanup function to remove the handler #### Example ``` session.onErrorStart((error) => { console.error(`Session error [${error.errorId}]: ${error.message}`); }); ``` ### onExchangeStart() > **onExchangeStart**(`cb`: (`exchange`: `ExchangeStream`) => `void`): () => `void` Registers a handler for exchange start events This is the primary entry point for handling agent responses. Each exchange represents a request-response cycle containing user and assistant messages. #### Parameters - `cb`: (`exchange`: `ExchangeStream`) => `void` β€” Callback receiving each new exchange #### Returns Cleanup function to remove the handler #### Examples ``` session.onExchangeStart((exchange) => { exchange.onMessageStart((message) => { if (message.isAssistant) { message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => renderMarkdown(chunk.data ?? '')); } else if (part.isAudio) { part.onChunk((chunk) => audioPlayer.enqueue(chunk.data ?? '')); } else if (part.isImage) { part.onChunk((chunk) => imageBuffer.append(chunk.data ?? '')); } else if (part.isTranscript) { part.onChunk((chunk) => showTranscript(chunk.data ?? '')); } }); } }); }); ``` ``` session.onExchangeStart((exchange) => { exchange.onMessageCompleted((completed) => { console.log(`Message ${completed.messageId} (role: ${completed.role})`); for (const part of completed.contentParts) { console.log(part.data); } for (const tool of completed.toolCalls) { console.log(`${tool.toolName} β†’ ${tool.output}`); } }); }); ``` ``` session.onExchangeStart((exchange) => { exchange.onMessageStart((message) => { if (message.isAssistant) { // Stream tool call events message.onToolCallStart((toolCall) => { const { toolName, input } = toolCall.startEvent; console.log(`Calling ${toolName}:`, JSON.parse(input ?? '{}')); toolCall.onToolCallEnd((end) => { console.log(`Result:`, JSON.parse(end.output ?? '{}')); }); }); // Handle confirmation interrupts message.onInterruptStart(({ interruptId, startEvent }) => { if (startEvent.type === 'uipath_cas_tool_call_confirmation') { message.sendInterruptEnd(interruptId, { approved: true }); } }); } }); }); ``` ### onLabelUpdated() > **onLabelUpdated**(`cb`: (`event`: `LabelUpdatedEvent`) => `void`): () => `void` Registers a handler for conversation label updates Fired when the conversation label changes, typically when the server auto-generates a title based on the first message. #### Parameters - `cb`: (`event`: `LabelUpdatedEvent`) => `void` β€” Callback receiving the [LabelUpdatedEvent](../LabelUpdatedEvent/) with the new label #### Returns Cleanup function to remove the handler #### Example ``` session.onLabelUpdated((event) => { console.log(`New label: ${event.label} (auto: ${event.autogenerated})`); updateConversationTitle(event.label); }); ``` ### onSessionEnd() > **onSessionEnd**(`cb`: (`event`: `SessionEndEvent`) => `void`): () => `void` Registers a handler for session end events Fired when the session has fully closed. #### Parameters - `cb`: (`event`: `SessionEndEvent`) => `void` β€” Callback receiving the end event #### Returns Cleanup function to remove the handler #### Example ``` session.onSessionEnd((event) => { console.log('Session ended'); }); ``` ### onSessionEnding() > **onSessionEnding**(`cb`: (`event`: `SessionEndingEvent`) => `void`): () => `void` Registers a handler for session ending events Fired when the session is about to end. Use this for cleanup before the session fully closes. #### Parameters - `cb`: (`event`: `SessionEndingEvent`) => `void` β€” Callback receiving the ending event #### Returns Cleanup function to remove the handler #### Example ``` session.onSessionEnding((event) => { console.log('Session is ending, performing cleanup...'); }); ``` ### onSessionStarted() > **onSessionStarted**(`cb`: (`event`: `SessionStartedEvent`) => `void`): () => `void` Registers a handler for session started events Fired when the WebSocket connection is established and the session is ready to send and receive events. #### Parameters - `cb`: (`event`: `SessionStartedEvent`) => `void` β€” Callback receiving the started event #### Returns Cleanup function to remove the handler #### Example ``` session.onSessionStarted(() => { console.log('Session is ready β€” now safe to start exchanges'); const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello!', role: MessageRole.User }); }); ``` ### startExchange() > **startExchange**(`args?`: { `exchangeId?`: `string`; } & `ExchangeStartEvent`): `ExchangeStream` Starts a new exchange in this session Each exchange is a request-response cycle. Use `sendMessageWithContentPart` on the returned [ExchangeStream](../ExchangeStream/) to send a user message, or `startMessage` for fine-grained control. #### Parameters - `args?`: { `exchangeId?`: `string`; } & `ExchangeStartEvent` β€” Optional exchange start options #### Returns `ExchangeStream` The exchange stream for sending messages #### Example ``` const session = conversation.startSession(); // Listen for all assistant responses session.onExchangeStart((exchange) => { exchange.onMessageCompleted((completed) => { if (completed.role === MessageRole.Assistant) { for (const part of completed.contentParts) { console.log('Assistant:', part.data); } } }); }); // Wait for session to be ready before starting exchanges session.onSessionStarted(async () => { // Send first user message const exchange1 = session.startExchange(); await exchange1.sendMessageWithContentPart({ data: 'What is the weather today?', role: MessageRole.User }); // Send follow-up in a new exchange const exchange2 = session.startExchange(); await exchange2.sendMessageWithContentPart({ data: 'And tomorrow?', role: MessageRole.User }); }); ``` Consumer-facing model for exchange event helpers. An exchange represents a single request-response cycle within a session. Each exchange contains one or more messages (typically a user message followed by an assistant response). Use exchanges to group related turns in a multi-turn conversation. ## Examples ``` session.onExchangeStart((exchange) => { exchange.onMessageStart((message) => { if (message.isAssistant) { message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => { process.stdout.write(chunk.data ?? ''); }); } }); } }); }); ``` ``` session.onExchangeStart((exchange) => { exchange.onMessageCompleted((completed) => { for (const part of completed.contentParts) { console.log(part.data); } for (const tool of completed.toolCalls) { console.log(`${tool.toolName}: ${tool.output}`); } }); }); ``` ``` // Call startExchange inside onSessionStarted to ensure the session is ready session.onSessionStarted(() => { const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello, how can you help me?', role: MessageRole.User }); }); ``` ``` // Call startExchange inside onSessionStarted to ensure the session is ready session.onSessionStarted(() => { const exchange = session.startExchange(); const message = exchange.startMessage({ role: MessageRole.User }); const part = message.startContentPart({ mimeType: 'text/plain' }); part.sendChunk({ data: 'Hello, ' }); part.sendChunk({ data: 'how can you help me?' }); part.sendContentPartEnd(); message.sendMessageEnd(); }); ``` ## Properties | Property | Modifier | Type | Description | | ------------ | ---------- | ---------------------------- | -------------------------------------------------- | | `ended` | `readonly` | `boolean` | Whether this exchange has ended | | `exchangeId` | `readonly` | `string` | Unique identifier for this exchange | | `messages` | `readonly` | `Iterable`\<`MessageStream`> | Iterator over all active messages in this exchange | ## Methods ### getMessage() > **getMessage**(`messageId`: `string`): `undefined` | `MessageStream` Retrieves a message by ID #### Parameters - `messageId`: `string` β€” The message ID to look up #### Returns `undefined` | `MessageStream` The message stream, or undefined if not found ### onErrorEnd() > **onErrorEnd**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void`): () => `void` Registers a handler for error end events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void` β€” Callback receiving the error end event #### Returns Cleanup function to remove the handler ### onErrorStart() > **onErrorStart**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void`): () => `void` Registers a handler for error start events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void` β€” Callback receiving the error event #### Returns Cleanup function to remove the handler #### Example ``` exchange.onErrorStart((error) => { console.error(`Exchange error [${error.errorId}]: ${error.message}`); }); ``` ### onExchangeEnd() > **onExchangeEnd**(`cb`: (`endExchange`: `ExchangeEndEvent`) => `void`): () => `void` Registers a handler for exchange end events #### Parameters - `cb`: (`endExchange`: `ExchangeEndEvent`) => `void` β€” Callback receiving the end event #### Returns Cleanup function to remove the handler #### Example ``` exchange.onExchangeEnd((endEvent) => { console.log('Exchange completed'); }); ``` ### onMessageCompleted() > **onMessageCompleted**(`cb`: (`completedMessage`: { `contentParts`: `CompletedContentPart`[]; `exchangeSequence?`: `number`; `messageId`: `string`; `metaData?`: `JSONObject`; `role?`: `MessageRole`; `timestamp?`: `string`; `toolCalls`: `CompletedToolCall`[]; }) => `void`): `void` Registers a handler called when a message finishes Convenience method that combines onMessageStart + message.onCompleted. The handler receives the aggregated message data including all content parts and tool calls. #### Parameters - `cb`: (`completedMessage`: { `contentParts`: `CompletedContentPart`[]; `exchangeSequence?`: `number`; `messageId`: `string`; `metaData?`: `JSONObject`; `role?`: `MessageRole`; `timestamp?`: `string`; `toolCalls`: `CompletedToolCall`[]; }) => `void` β€” Callback receiving the completed message data #### Returns `void` #### Example ``` exchange.onMessageCompleted((message) => { console.log(`Message ${message.messageId} (role: ${message.role})`); console.log(`Content parts: ${message.contentParts.length}`); console.log(`Tool calls: ${message.toolCalls.length}`); }); ``` ### onMessageStart() > **onMessageStart**(`cb`: (`message`: `MessageStream`) => `void`): () => `void` Registers a handler for message start events Each exchange typically contains a user message and an assistant response. Use `message.isAssistant` or `message.isUser` to filter. #### Parameters - `cb`: (`message`: `MessageStream`) => `void` β€” Callback receiving each new message #### Returns Cleanup function to remove the handler #### Example ``` exchange.onMessageStart((message) => { if (message.isAssistant) { message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => process.stdout.write(chunk.data ?? '')); } }); } }); ``` ### sendExchangeEnd() > **sendExchangeEnd**(`endExchange?`: `ExchangeEndEvent`): `void` Ends the exchange. Stops further events for that exchange from being received. Use this to stop an in-progress agent response from the client side. #### Parameters - `endExchange?`: `ExchangeEndEvent` β€” Optional end event data #### Returns `void` #### Examples ``` session.onExchangeStart((exchange) => { stopButton.addEventListener('click', () => exchange.sendExchangeEnd()); }); ``` ``` const exchange = session.startExchange(); exchange.sendMessageWithContentPart({ data: 'Hello!' }); // Later, stop the response exchange.sendExchangeEnd(); ``` ### sendMessageWithContentPart() > **sendMessageWithContentPart**(`options`: { `data`: `string`; `mimeType?`: `string`; `role?`: `MessageRole`; }): `Promise`\<`void`> Sends a complete message with a content part in one step Convenience method that creates a message, adds a content part with the given data, and ends both the content part and message. #### Parameters - `options`: { `data`: `string`; `mimeType?`: `string`; `role?`: `MessageRole`; } β€” Message content options - `options.data`: `string` β€” - - `options.mimeType?`: `string` β€” - - `options.role?`: `MessageRole` β€” - #### Returns `Promise`\<`void`> #### Example ``` await exchange.sendMessageWithContentPart({ data: 'What is the weather today?', role: MessageRole.User }); ``` ### startMessage() > **startMessage**(`args?`: { `messageId?`: `string`; } & `Partial`\<`MessageStartEvent`>): `MessageStream` Starts a new message in this exchange Use this for fine-grained control over message construction. For simple text messages, prefer [sendMessageWithContentPart](#sendmessagewithcontentpart). #### Parameters - `args?`: { `messageId?`: `string`; } & `Partial`\<`MessageStartEvent`> β€” Optional message start options including role #### Returns `MessageStream` The message stream for sending content #### Example ``` const message = exchange.startMessage({ role: MessageRole.User }); const part = message.startContentPart({ mimeType: 'text/plain' }); part.sendChunk({ data: 'Analyze this image: ' }); part.sendContentPartEnd(); message.sendMessageEnd(); ``` Consumer-facing model for message event helpers. A message represents a single turn from a user, assistant, or system. Messages contain content parts (text, audio, images) and tool calls. The `role` property and convenience booleans (`isUser`, `isAssistant`, `isSystem`) let you filter by sender. ## Examples ``` exchange.onMessageStart((message) => { if (message.isAssistant) { message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => { process.stdout.write(chunk.data ?? ''); }); } }); } }); ``` ``` exchange.onMessageStart((message) => { if (message.isAssistant) { message.onToolCallStart((toolCall) => { console.log(`Tool: ${toolCall.startEvent.toolName}`); }); message.onInterruptStart(({ interruptId, startEvent }) => { if (startEvent.type === 'uipath_cas_tool_call_confirmation') { message.sendInterruptEnd(interruptId, { approved: true }); } }); } }); ``` ``` exchange.onMessageStart((message) => { if (message.isAssistant) { message.onCompleted((completed) => { console.log(`Message ${completed.messageId} finished`); for (const part of completed.contentParts) { console.log(part.data); } for (const tool of completed.toolCalls) { console.log(`${tool.toolName} β†’ ${tool.output}`); } }); } }); ``` ``` const message = exchange.startMessage({ role: MessageRole.User }); await message.sendContentPart({ data: 'Hello!', mimeType: 'text/plain' }); message.sendMessageEnd(); ``` ## Properties | Property | Modifier | Type | Description | | -------------- | ---------- | -------------------------------- | ------------------------------------------------------ | | `contentParts` | `readonly` | `Iterable`\<`ContentPartStream`> | Iterator over all active content parts in this message | | `ended` | `readonly` | `boolean` | Whether this message has ended | | `isAssistant` | `readonly` | `boolean` | Whether this message is from the assistant | | `isSystem` | `readonly` | `boolean` | Whether this message is a system message | | `isUser` | `readonly` | `boolean` | Whether this message is from the user | | `messageId` | `readonly` | `string` | Unique identifier for this message | | `role` | `readonly` | `undefined` | `MessageRole` | | `toolCalls` | `readonly` | `Iterable`\<`ToolCallStream`> | Iterator over all active tool calls in this message | ## Methods ### getContentPart() > **getContentPart**(`contentPartId`: `string`): `undefined` | `ContentPartStream` Retrieves a content part by ID #### Parameters - `contentPartId`: `string` β€” The content part ID to look up #### Returns `undefined` | `ContentPartStream` The content part stream, or undefined if not found ### getToolCall() > **getToolCall**(`toolCallId`: `string`): `undefined` | `ToolCallStream` Retrieves a tool call by ID #### Parameters - `toolCallId`: `string` β€” The tool call ID to look up #### Returns `undefined` | `ToolCallStream` The tool call stream, or undefined if not found ### onCompleted() > **onCompleted**(`cb`: (`completedMessage`: { `contentParts`: `CompletedContentPart`[]; `exchangeSequence?`: `number`; `messageId`: `string`; `metaData?`: `JSONObject`; `role?`: `MessageRole`; `timestamp?`: `string`; `toolCalls`: `CompletedToolCall`[]; }) => `void`): `void` Registers a handler called when the entire message finishes The handler receives the aggregated message data including all completed content parts and tool calls. #### Parameters - `cb`: (`completedMessage`: { `contentParts`: `CompletedContentPart`[]; `exchangeSequence?`: `number`; `messageId`: `string`; `metaData?`: `JSONObject`; `role?`: `MessageRole`; `timestamp?`: `string`; `toolCalls`: `CompletedToolCall`[]; }) => `void` β€” Callback receiving the completed message data #### Returns `void` #### Example ``` message.onCompleted((completed) => { console.log(`Message ${completed.messageId} (role: ${completed.role})`); console.log('Text:', completed.contentParts.map(p => p.data).join('')); console.log('Tool calls:', completed.toolCalls.length); }); ``` ### onContentPartCompleted() > **onContentPartCompleted**(`cb`: (`completedContentPart`: `CompletedContentPart`) => `void`): `void` Registers a handler called when a content part finishes Convenience method that combines onContentPartStart + onContentPartEnd. The handler receives the full buffered content part data including text, citations, and any citation errors. #### Parameters - `cb`: (`completedContentPart`: `CompletedContentPart`) => `void` β€” Callback receiving the completed content part data #### Returns `void` #### Example ``` message.onContentPartCompleted((completed) => { console.log(`[${completed.mimeType}] ${completed.data}`); // Access citations if present for (const citation of completed.citations) { const citedText = completed.data.substring(citation.offset, citation.offset + citation.length); console.log(`Citation "${citedText}" from:`, citation.sources); } // Check for citation errors for (const error of completed.citationErrors) { console.warn(`Citation error [${error.citationId}]: ${error.errorType}`); } }); ``` ### onContentPartStart() > **onContentPartStart**(`cb`: (`contentPart`: `ContentPartStream`) => `void`): () => `void` Registers a handler for content part start events Content parts are streamed pieces of content (text, audio, images, transcripts). Use `part.isMarkdown`, `part.isAudio`, etc. to determine type. #### Parameters - `cb`: (`contentPart`: `ContentPartStream`) => `void` β€” Callback receiving each new content part #### Returns Cleanup function to remove the handler #### Example ``` message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => renderMarkdown(chunk.data ?? '')); } else if (part.isAudio) { part.onChunk((chunk) => audioPlayer.enqueue(chunk.data ?? '')); } else if (part.isImage) { part.onChunk((chunk) => imageBuffer.append(chunk.data ?? '')); } else if (part.isTranscript) { part.onChunk((chunk) => showTranscript(chunk.data ?? '')); } }); ``` ### onErrorEnd() > **onErrorEnd**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void`): () => `void` Registers a handler for error end events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void` β€” Callback receiving the error end event #### Returns Cleanup function to remove the handler ### onErrorStart() > **onErrorStart**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void`): () => `void` Registers a handler for error start events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void` β€” Callback receiving the error event #### Returns Cleanup function to remove the handler #### Example ``` message.onErrorStart((error) => { console.error(`Message error [${error.errorId}]: ${error.message}`); }); ``` ### onInterruptEnd() > **onInterruptEnd**(`cb`: (`interrupt`: { `endEvent`: `InterruptEndEvent`; `interruptId`: `string`; }) => `void`): () => `void` Registers a handler for interrupt end events #### Parameters - `cb`: (`interrupt`: { `endEvent`: `InterruptEndEvent`; `interruptId`: `string`; }) => `void` β€” Callback receiving the interrupt ID and end event #### Returns Cleanup function to remove the handler #### Example ``` message.onInterruptEnd(({ interruptId, endEvent }) => { console.log(`Interrupt ${interruptId} resolved`); }); ``` ### onInterruptStart() > **onInterruptStart**(`cb`: (`interrupt`: { `interruptId`: `string`; `startEvent`: `InterruptStartEvent`; }) => `void`): () => `void` Registers a handler for interrupt start events Interrupts represent pause points where the agent needs external input, such as tool call confirmation requests. #### Parameters - `cb`: (`interrupt`: { `interruptId`: `string`; `startEvent`: `InterruptStartEvent`; }) => `void` β€” Callback receiving the interrupt ID and start event #### Returns Cleanup function to remove the handler #### Example ``` message.onInterruptStart(({ interruptId, startEvent }) => { if (startEvent.type === 'uipath_cas_tool_call_confirmation') { // Show confirmation UI, then respond message.sendInterruptEnd(interruptId, { approved: true }); } }); ``` ### onMessageEnd() > **onMessageEnd**(`cb`: (`endMessage`: `MessageEndEvent`) => `void`): () => `void` Registers a handler for message end events #### Parameters - `cb`: (`endMessage`: `MessageEndEvent`) => `void` β€” Callback receiving the end event #### Returns Cleanup function to remove the handler #### Example ``` message.onMessageEnd((endEvent) => { console.log('Message ended'); }); ``` ### onToolCallCompleted() > **onToolCallCompleted**(`cb`: (`completedToolCall`: `CompletedToolCall`) => `void`): `void` Registers a handler called when a tool call finishes Convenience method that combines onToolCallStart + onToolCallEnd. The handler receives the merged start and end event data. #### Parameters - `cb`: (`completedToolCall`: `CompletedToolCall`) => `void` β€” Callback receiving the completed tool call data #### Returns `void` #### Example ``` message.onToolCallCompleted((toolCall) => { console.log(`Tool: ${toolCall.toolName}`); console.log(`Input: ${toolCall.input}`); console.log(`Output: ${toolCall.output}`); }); ``` ### onToolCallConfirm() > **onToolCallConfirm**(`callback`: (`args`: { `confirmEvent`: `ToolCallConfirmationEvent`; `toolCallId`: `string`; }) => `void`): () => `void` Registers a handler for tool-call confirmation events on this message Fired when a peer responds to a tool call that was emitted with `requireConfirmation: true`. The handler runs at the message level, so it fires even if no per-tool-call stream exists for the confirmed `toolCallId`. #### Parameters - `callback`: (`args`: { `confirmEvent`: `ToolCallConfirmationEvent`; `toolCallId`: `string`; }) => `void` β€” Callback receiving the toolCallId and the confirmation event #### Returns Cleanup function to remove the handler #### Example ``` message.onToolCallConfirm(({ toolCallId, confirmEvent }) => { if (confirmEvent.approved) executeTool(toolCallId, confirmEvent.input); else cancelToolCall(toolCallId); }); ``` ### onToolCallStart() > **onToolCallStart**(`cb`: (`toolCall`: `ToolCallStream`) => `void`): () => `void` Registers a handler for tool call start events Tool calls represent the agent invoking external tools. Each tool call has a name, input, and eventually an output when it completes. #### Parameters - `cb`: (`toolCall`: `ToolCallStream`) => `void` β€” Callback receiving each new tool call #### Returns Cleanup function to remove the handler #### Example ``` message.onToolCallStart((toolCall) => { const { toolName, input } = toolCall.startEvent; console.log(`Calling ${toolName}:`, JSON.parse(input ?? '{}')); toolCall.onToolCallEnd((end) => { console.log(`Result:`, JSON.parse(end.output ?? '{}')); }); }); ``` ### sendContentPart() > **sendContentPart**(`args`: { `data?`: `string`; `mimeType?`: `string`; }): `Promise`\<`void`> Sends a complete content part with data in one step Convenience method that creates a content part, sends the data as a chunk, and ends the content part. Defaults to mimeType "text/markdown". #### Parameters - `args`: { `data?`: `string`; `mimeType?`: `string`; } β€” Content part data and optional mime type - `args.data?`: `string` β€” - - `args.mimeType?`: `string` β€” - #### Returns `Promise`\<`void`> #### Examples ``` await message.sendContentPart({ data: 'Hello world!' }); ``` ``` await message.sendContentPart({ data: 'Plain text content', mimeType: 'text/plain' }); ``` ### sendInterruptEnd() > **sendInterruptEnd**(`interruptId`: `string`, `endInterrupt`: `InterruptEndEvent`): `void` Sends an interrupt end event to resolve a pending interrupt Call this to respond to an interrupt received via onInterruptStart. #### Parameters - `interruptId`: `string` β€” The interrupt ID to respond to - `endInterrupt`: `InterruptEndEvent` β€” The response data (e.g., approval for tool call confirmation) #### Returns `void` #### Example ``` message.sendInterruptEnd(interruptId, { approved: true }); ``` ### sendMessageEnd() > **sendMessageEnd**(`endMessage?`: `MessageEndEvent`): `void` Ends the message #### Parameters - `endMessage?`: `MessageEndEvent` β€” Optional end event data #### Returns `void` #### Example ``` message.sendMessageEnd(); ``` ### startContentPart() > **startContentPart**(`args`: { `contentPartId?`: `string`; } & `ContentPartStartEvent`): `ContentPartStream` Starts a new content part stream in this message Use this for streaming content in chunks. For sending complete content in one call, prefer [sendContentPart](#sendcontentpart). #### Parameters - `args`: { `contentPartId?`: `string`; } & `ContentPartStartEvent` β€” Content part start options including mime type #### Returns `ContentPartStream` The content part stream for sending chunks #### Example ``` const part = message.startContentPart({ mimeType: 'text/markdown' }); part.sendChunk({ data: '# Hello\n' }); part.sendChunk({ data: 'This is **markdown** content.' }); part.sendContentPartEnd(); ``` ### startToolCall() > **startToolCall**(`args`: { `toolCallId?`: `string`; } & `ToolCallStartEvent`): `ToolCallStream` Starts a new tool call in this message #### Parameters - `args`: { `toolCallId?`: `string`; } & `ToolCallStartEvent` β€” Tool call start options including tool name #### Returns `ToolCallStream` The tool call stream for managing the tool call lifecycle #### Example ``` const toolCall = message.startToolCall({ toolName: 'get-weather', input: JSON.stringify({ city: 'London' }) }); toolCall.sendToolCallEnd({ output: JSON.stringify({ temperature: 18, condition: 'cloudy' }) }); ``` Model for content part event helpers. A content part is a single piece of content within a message β€” text, audio, an image, or a transcript. Use the type-check properties (`isText`, `isMarkdown`, `isHtml`, `isAudio`, `isImage`, `isTranscript`) to determine the content type and handle it accordingly. ## Examples ``` message.onContentPartStart((part) => { if (part.isMarkdown) { part.onChunk((chunk) => { process.stdout.write(chunk.data ?? ''); }); } }); ``` ``` message.onContentPartStart((part) => { if (part.isText) { part.onChunk((chunk) => showPlainText(chunk.data ?? '')); } else if (part.isMarkdown) { part.onChunk((chunk) => renderMarkdown(chunk.data ?? '')); } else if (part.isHtml) { part.onChunk((chunk) => renderHtml(chunk.data ?? '')); } else if (part.isAudio) { part.onChunk((chunk) => audioPlayer.enqueue(chunk.data ?? '')); } else if (part.isImage) { part.onChunk((chunk) => imageBuffer.append(chunk.data ?? '')); } else if (part.isTranscript) { part.onChunk((chunk) => showTranscript(chunk.data ?? '')); } }); ``` ``` message.onContentPartStart((part) => { part.onCompleted((completed) => { console.log(`Full text: ${completed.data}`); // Access citations β€” each has offset, length, and sources for (const citation of completed.citations) { const citedText = completed.data.substring( citation.offset, citation.offset + citation.length ); console.log(`"${citedText}" cited from:`, citation.sources); } }); }); ``` ``` message.onContentPartCompleted((completed) => { console.log(`[${completed.mimeType}] ${completed.data}`); }); ``` ## Properties | Property | Modifier | Type | Description | | --------------- | ---------- | ----------- | --------------------------------------------------------------- | | `contentPartId` | `readonly` | `string` | Unique identifier for this content part | | `ended` | `readonly` | `boolean` | Whether this content part has ended | | `isAudio` | `readonly` | `boolean` | Whether this content part is audio content | | `isHtml` | `readonly` | `boolean` | Whether this content part is HTML. Matches `text/html`. | | `isImage` | `readonly` | `boolean` | Whether this content part is an image | | `isMarkdown` | `readonly` | `boolean` | Whether this content part is markdown. Matches `text/markdown`. | | `isText` | `readonly` | `boolean` | Whether this content part is plain text. Matches `text/plain`. | | `isTranscript` | `readonly` | `boolean` | Whether this content part is a transcript (from speech-to-text) | | `mimeType` | `readonly` | `undefined` | `string` | ## Methods ### onChunk() > **onChunk**(`cb`: (`chunk`: `ContentPartChunkEvent`) => `void`): () => `void` Registers a handler for content part chunks Chunks are the fundamental unit of streaming data. Each chunk contains a piece of the content (text, audio data, etc.). #### Parameters - `cb`: (`chunk`: `ContentPartChunkEvent`) => `void` β€” Callback receiving each chunk #### Returns Cleanup function to remove the handler #### Example ``` part.onChunk((chunk) => { process.stdout.write(chunk.data ?? ''); }); ``` ### onCompleted() > **onCompleted**(`cb`: (`completedContentPart`: `CompletedContentPart`) => `void`): `void` Registers a handler called when this content part finishes The handler receives the aggregated content part data including all buffered text, citations, and any citation errors. #### Parameters - `cb`: (`completedContentPart`: `CompletedContentPart`) => `void` β€” Callback receiving the completed content part data #### Returns `void` #### Example ``` part.onCompleted((completed) => { console.log(`Content type: ${completed.mimeType}`); console.log(`Full text: ${completed.data}`); // Citations provide offset/length into the text and source references for (const citation of completed.citations) { const citedText = completed.data.substring( citation.offset, citation.offset + citation.length ); console.log(`"${citedText}" β€” sources:`, citation.sources); } // Citation errors indicate malformed citation ranges if (completed.citationErrors.length > 0) { console.warn('Citation errors:', completed.citationErrors); } }); ``` ### onContentPartEnd() > **onContentPartEnd**(`cb`: (`endContentPart`: `ContentPartEndEvent`) => `void`): () => `void` Registers a handler for content part end events #### Parameters - `cb`: (`endContentPart`: `ContentPartEndEvent`) => `void` β€” Callback receiving the end event #### Returns Cleanup function to remove the handler #### Example ``` part.onContentPartEnd((endEvent) => { console.log('Content part finished'); }); ``` ### onErrorEnd() > **onErrorEnd**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void`): () => `void` Registers a handler for error end events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void` β€” Callback receiving the error end event #### Returns Cleanup function to remove the handler ### onErrorStart() > **onErrorStart**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void`): () => `void` Registers a handler for error start events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void` β€” Callback receiving the error event #### Returns Cleanup function to remove the handler #### Example ``` part.onErrorStart((error) => { console.error(`Content part error: ${error.message}`); }); ``` ### sendChunk() > **sendChunk**(`chunk`: `ContentPartChunkEvent`): `void` Sends a content part chunk #### Parameters - `chunk`: `ContentPartChunkEvent` β€” Chunk data to send #### Returns `void` #### Example ``` part.sendChunk({ data: 'Hello ' }); part.sendChunk({ data: 'world!' }); ``` ### sendContentPartEnd() > **sendContentPartEnd**(`endContentPart?`: `ContentPartEndEvent`): `void` Ends the content part stream #### Parameters - `endContentPart?`: `ContentPartEndEvent` β€” Optional end event data #### Returns `void` #### Example ``` part.sendContentPartEnd(); ``` Consumer-facing model for tool call event helpers. A tool call represents the agent invoking an external tool (API call, database query, etc.) during a conversation. Tool calls live within a message and have a start event (with tool name and input) and an end event (with the output/result). ## Examples ``` message.onToolCallStart((toolCall) => { console.log(`Tool: ${toolCall.startEvent.toolName}`); toolCall.onToolCallEnd((endEvent) => { console.log('Tool call completed:', endEvent.output); }); }); ``` ``` message.onToolCallStart((toolCall) => { const { toolName, input } = toolCall.startEvent; const parsedInput = JSON.parse(input ?? '{}'); console.log(`Calling ${toolName} with:`, parsedInput); toolCall.onToolCallEnd((endEvent) => { const result = JSON.parse(endEvent.output ?? '{}'); console.log(`${toolName} returned:`, result); }); }); ``` ``` message.onToolCallStart(async (toolCall) => { const { toolName, input } = toolCall.startEvent; // Execute the tool and return the result const result = await executeTool(toolName, input); toolCall.sendToolCallEnd({ output: JSON.stringify(result) }); }); ``` ``` // BEFORE β€” legacy interrupt flow message.onInterruptStart(async ({ interruptId, startEvent }) => { if (startEvent.type !== InterruptType.ToolCallConfirmation) return; const { toolName, inputSchema, inputValue } = startEvent.value; const decision = await showConfirmationDialog({ toolName, inputSchema, input: inputValue, }); message.sendInterruptEnd(interruptId, { approved: decision.approved, input: decision.editedInput, }); }); // AFTER β€” new tool-call confirmation flow message.onToolCallStart(async (toolCall) => { const { toolName, input, requireConfirmation, inputSchema } = toolCall.startEvent; if (!requireConfirmation) return; const decision = await showConfirmationDialog({ toolName, inputSchema, input }); if (decision.approved) { toolCall.sendToolCallConfirm({ approved: true, input: decision.editedInput }); } else { toolCall.sendToolCallConfirm({ approved: false }); } }); ``` ``` message.onToolCallStart((toolCall) => { const { isClientSideTool, toolName } = toolCall.startEvent; if (!isClientSideTool) return; toolCall.onExecutingToolCall(async (event) => { const result = await runLocalProcess(toolName, event.input); toolCall.sendToolCallEnd({ output: result }); }); }); ``` ## Properties | Property | Modifier | Type | Description | | ------------ | ---------- | --------- | ------------------------------------ | | `ended` | `readonly` | `boolean` | Whether this tool call has ended | | `toolCallId` | `readonly` | `string` | Unique identifier for this tool call | ## Methods ### onErrorEnd() > **onErrorEnd**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void`): () => `void` Registers a handler for error end events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorEndEvent`) => `void` β€” Callback receiving the error end event #### Returns Cleanup function to remove the handler ### onErrorStart() > **onErrorStart**(`cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void`): () => `void` Registers a handler for error start events #### Parameters - `cb`: (`error`: { `errorId`: `string`; } & `ErrorStartEvent`) => `void` β€” Callback receiving the error event #### Returns Cleanup function to remove the handler #### Example ``` toolCall.onErrorStart((error) => { console.error(`Tool call error: ${error.message}`); }); ``` ### onToolCallConfirm() > **onToolCallConfirm**(`callback`: (`confirmToolCall`: `ToolCallConfirmationEvent`) => `void`): () => `void` Registers a handler for tool call confirmation events. Fired when the peer responds to a tool call that was emitted with `requireConfirmation: true` on its start event. #### Parameters - `callback`: (`confirmToolCall`: `ToolCallConfirmationEvent`) => `void` β€” Callback receiving the confirmation event #### Returns Cleanup function to remove the handler #### Example ``` toolCall.onToolCallConfirm(({ approved, input }) => { if (approved) executeTool(toolCall.startEvent.toolName, input); else cancelToolCall(); }); ``` ### onToolCallEnd() > **onToolCallEnd**(`cb`: (`endToolCall`: `ToolCallEndEvent`) => `void`): () => `void` Registers a handler for tool call end events #### Parameters - `cb`: (`endToolCall`: `ToolCallEndEvent`) => `void` β€” Callback receiving the end event #### Returns Cleanup function to remove the handler #### Example ``` toolCall.onToolCallEnd((endEvent) => { console.log('Output:', endEvent.output); }); ``` ### sendToolCallConfirm() > **sendToolCallConfirm**(`confirmToolCall`: `ToolCallConfirmationEvent`): `void` Sends a tool call confirmation (approve or reject) for a tool call that was emitted with `requireConfirmation: true`. Replaces the legacy interrupt-based confirmation flow. #### Parameters - `confirmToolCall`: `ToolCallConfirmationEvent` β€” The user's decision and (when approved) the possibly-edited input the tool should execute with #### Returns `void` #### Examples ``` toolCall.sendToolCallConfirm({ approved: true, input: editedInput }); ``` ``` toolCall.sendToolCallConfirm({ approved: false }); ``` ### sendToolCallEnd() > **sendToolCallEnd**(`endToolCall?`: `ToolCallEndEvent`): `void` Ends the tool call #### Parameters - `endToolCall?`: `ToolCallEndEvent` β€” Optional end event data #### Returns `void` #### Example ``` toolCall.sendToolCallEnd({ output: JSON.stringify({ temperature: 18, condition: 'cloudy' }) }); ```