import * as _uipath_core_telemetry from '@uipath/core-telemetry'; import { TelemetryContext } from '@uipath/core-telemetry'; /** * Authentication token information */ interface TokenInfo { token: string; type: 'secret' | 'oauth'; expiresAt?: Date; refreshToken?: string; } interface BaseConfig { baseUrl: string; orgName: string; tenantName: string; } interface OAuthFields { clientId: string; redirectUri: string; scope: string; } type UiPathSDKConfig = BaseConfig & ({ secret: string; clientId?: never; redirectUri?: never; scope?: never; } | ({ secret?: never; } & OAuthFields)); type PartialUiPathConfig = Partial; /** * IUiPath - Interface for UiPath SDK instance * * This interface defines the public contract for the UiPath SDK. * Services depend on this interface rather than the concrete UiPath class, * enabling proper type sharing across modular imports without #private field issues. * * @internal This interface is for internal SDK use only */ interface IUiPath { /** Read-only configuration for the SDK instance */ readonly config: Readonly; /** * Initialize the SDK based on the provided configuration. * For secret-based auth, this returns immediately. * For OAuth, this handles the authentication flow. */ initialize(): Promise; /** * Enables the UiPath login picker during OAuth sign-in. */ setMultiLogin(): void; /** * Check if the SDK has been initialized */ isInitialized(): boolean; /** * Check if we're in an OAuth callback state */ isInOAuthCallback(): boolean; /** * Complete OAuth authentication flow */ completeOAuth(): Promise; /** * Check if the user is authenticated (has valid token) */ isAuthenticated(): boolean; /** * Get the current authentication token */ getToken(): string | undefined; /** * Releases resources held by this SDK instance. * Cancels any in-flight token-refresh request. Call this when the coded app is unmounted. */ destroy(): void; /** * Logout from the SDK, clearing all authentication state. * After calling this method, the user will need to re-initialize to authenticate again. */ logout(): void; /** * Updates the access token used for API requests. * Use this to inject or refresh a token externally. * * @param tokenInfo - The token information containing the access token, type, expiration, and optional refresh token */ updateToken(tokenInfo: TokenInfo): void; } /** * UiPath - Core SDK class for authentication and configuration management. * * Handles authentication, configuration, and provides access to SDK internals * for service instantiation in the modular pattern. * * Supports two usage patterns: * 1. Full config in constructor — for server-side or explicit configuration * 2. No config / partial config — loads from meta tags injected by @uipath/coded-apps-dev plugin * * @example * ```typescript * // Explicit config * const sdk = new UiPath({ * baseUrl: 'https://cloud.uipath.com', * orgName: 'myorg', * tenantName: 'mytenant', * clientId: 'xxx', * redirectUri: 'http://localhost:3000/callback', * scope: 'OR.Users OR.Robots' * }); * await sdk.initialize(); * ``` * * @example * ```typescript * // Auto-load from meta tags (coded apps) * const sdk = new UiPath(); * await sdk.initialize(); * ``` */ declare class UiPath$1 implements IUiPath { #private; /** Read-only config for user convenience */ readonly config: Readonly; constructor(config?: PartialUiPathConfig); /** * Initialize the SDK based on the provided configuration. * This method handles both OAuth flow initiation and completion automatically. * For secret-based authentication, initialization is automatic and this returns immediately. * If no config was provided in constructor, loads from meta tags. */ initialize(): Promise; /** * Enables the UiPath login picker during OAuth sign-in. * * @internal */ setMultiLogin(): void; /** * Check if the SDK has been initialized */ isInitialized(): boolean; /** * Check if we're in an OAuth callback state */ isInOAuthCallback(): boolean; /** * Complete OAuth authentication flow (only call if isInOAuthCallback() is true) */ completeOAuth(): Promise; /** * Check if the user is authenticated (has valid token) */ isAuthenticated(): boolean; /** * Get the current authentication token */ getToken(): string | undefined; /** * Releases resources held by this SDK instance. * Cancels any in-flight token-refresh request. Call this when the coded app is unmounted. */ destroy(): void; /** * Logout from the SDK, clearing all authentication state. * After calling this method, the user will need to re-initialize to authenticate again. */ logout(): void; /** * Updates the access token used for API requests. * Use this to inject or refresh a token externally. * * @param tokenInfo - The token information containing the access token, type, expiration, and optional refresh token */ updateToken(tokenInfo: TokenInfo): void; } /** * Simplified universal pagination cursor * Used to fetch next/previous pages */ interface PaginationCursor { /** Opaque string containing all information needed to fetch next page */ value: string; } /** * Discriminated union for pagination methods - ensures cursor and jumpToPage are mutually exclusive */ type PaginationMethodUnion = { cursor?: PaginationCursor; jumpToPage?: never; } | { cursor?: never; jumpToPage?: number; } | { cursor?: never; jumpToPage?: never; }; /** * Pagination options. Users cannot specify both cursor and jumpToPage. */ type PaginationOptions = { /** Size of the page to fetch (items per page) */ pageSize?: number; } & PaginationMethodUnion; /** * Paginated response containing items and navigation information */ interface PaginatedResponse { /** The items in the current page */ items: T[]; /** Total count of items across all pages (if available) */ totalCount?: number; /** Whether more pages are available */ hasNextPage: boolean; /** Cursor to fetch the next page (if available) */ nextCursor?: PaginationCursor; /** Cursor to fetch the previous page (if available) */ previousCursor?: PaginationCursor; /** Current page number (1-based, if available) */ currentPage?: number; /** Total number of pages (if available) */ totalPages?: number; /** Whether this pagination type supports jumping to arbitrary pages */ supportsPageJump: boolean; } /** * Response for non-paginated calls that includes both data and total count */ interface NonPaginatedResponse { items: T[]; totalCount?: number; } /** * Helper type for defining paginated method overloads * Creates a union type of all ways pagination can be triggered */ type HasPaginationOptions = (T & { pageSize: number; }) | (T & { cursor: PaginationCursor; }) | (T & { jumpToPage: number; }); /** * Pagination types supported by the SDK */ declare enum PaginationType { OFFSET = "offset", TOKEN = "token" } /** * Interface for service access methods needed by pagination helpers */ interface PaginationServiceAccess { get(path: string, options?: any): Promise<{ data: T; }>; post(path: string, body?: any, options?: any): Promise<{ data: T; }>; requestWithPagination(method: string, path: string, paginationOptions: PaginationOptions, options: RequestWithPaginationOptions): Promise>; } /** * Field names for extracting data from paginated responses. */ interface PaginationFieldNames { itemsField?: string; totalCountField?: string; continuationTokenField?: string; } /** * Options for the requestWithPagination method in BaseService. */ interface RequestWithPaginationOptions extends RequestSpec { pagination: PaginationFieldNames & { paginationType: PaginationType; paginationParams?: { pageSizeParam?: string; offsetParam?: string; tokenParam?: string; countParam?: string; convertToSkip?: boolean; zeroBased?: boolean; }; }; } /** * HTTP methods supported by the API client */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; /** * Supported response types for API requests */ type ResponseType = 'json' | 'text' | 'blob' | 'arraybuffer' | 'stream'; /** * Query parameters type with support for arrays and nested objects */ type QueryParams = Record | null | undefined>; /** * Standard HTTP headers type */ type Headers = Record; /** * Options for request retries */ interface RetryOptions { /** Maximum number of retry attempts */ maxRetries?: number; /** Base delay between retries in milliseconds */ retryDelay?: number; /** Whether to use exponential backoff */ useExponentialBackoff?: boolean; /** Status codes that should trigger a retry */ retryableStatusCodes?: number[]; } /** * Options for request timeouts */ interface TimeoutOptions { /** Request timeout in milliseconds */ timeout?: number; /** Whether to abort the request on timeout */ abortOnTimeout?: boolean; } /** * Options for request body transformation */ interface BodyOptions { /** Whether to stringify the body */ stringify?: boolean; /** Content type override */ contentType?: string; } /** * Pagination metadata for API requests */ interface PaginationMetadata { /** Type of pagination used by the API endpoint */ paginationType: PaginationType; /** Response field containing items array (defaults to 'value') */ itemsField?: string; /** Response field containing total count (defaults to '@odata.count') */ totalCountField?: string; /** Response field containing continuation token (defaults to 'continuationToken') */ continuationTokenField?: string; } /** * Base interface for all API requests */ interface RequestSpec { /** HTTP method for the request */ method?: HttpMethod; /** URL endpoint for the request */ url?: string; /** Query parameters to be appended to the URL */ params?: QueryParams; /** HTTP headers to include with the request */ headers?: Headers; /** Raw body content (takes precedence over data) */ body?: unknown; /** Expected response type */ responseType?: ResponseType; /** Request timeout options */ timeoutOptions?: TimeoutOptions; /** Retry behavior options */ retryOptions?: RetryOptions; /** Body transformation options */ bodyOptions?: BodyOptions; /** AbortSignal for cancelling the request */ signal?: AbortSignal; /** Pagination metadata for the request */ pagination?: PaginationMetadata; } interface ApiResponse { data: T; } /** * Base class for all UiPath SDK services. * * Provides common functionality for authentication, configuration, and API communication. * All service classes extend this base to inherit dependency injection and HTTP client access. * * This class implements the dependency injection pattern where services receive a configured * UiPath instance. The ApiClient is created internally and handles all HTTP operations * including authentication token management. * * @remarks * Service classes should extend this base and call `super(uiPath)` in their constructor. * Protected HTTP methods (get, post, put, patch, delete) are available to all subclasses. * */ declare class BaseService { #private; /** * SDK configuration (read-only). Available to subclasses so they can * fall back to init-time defaults like `folderKey`. */ protected readonly config: { folderKey?: string; }; /** * Creates a base service instance with dependency injection. * * Extracts configuration, execution context, and token manager from the UiPath instance * to initialize an authenticated API client. The ApiClient handles all HTTP operations * and token management internally. * * @param instance - UiPath SDK instance providing authentication and configuration. * Services receive this via dependency injection in the modular pattern. * @param headers - Optional default headers to include in every request (e.g. `x-uipath-external-user-id` for * CAS external-app auth) * * @example * ```typescript * // Services automatically call this via super() * export class EntityService extends BaseService { * constructor(instance: IUiPath) { * super(instance); // Initializes the internal ApiClient * } * } * * // Usage in modular pattern * import { UiPath } from '@uipath/uipath-typescript/core'; * import { Entities } from '@uipath/uipath-typescript/entities'; * * const sdk = new UiPath(config); * await sdk.initialize(); * const entities = new Entities(sdk); * ``` */ constructor(instance: IUiPath, headers?: Record); /** * Gets a valid authentication token, refreshing if necessary. * Use this when you need to manually add Authorization headers (e.g., direct uploads). * * @returns Promise resolving to a valid access token string * @throws AuthenticationError if no token is available or refresh fails */ protected getValidAuthToken(): Promise; /** * Creates a service accessor for pagination helpers * This allows pagination helpers to access protected methods without making them public */ protected createPaginationServiceAccess(): PaginationServiceAccess; protected request(method: string, path: string, options?: RequestSpec): Promise>; protected requestWithSpec(spec: RequestSpec): Promise>; protected get(path: string, options?: RequestSpec): Promise>; protected post(path: string, data?: unknown, options?: RequestSpec): Promise>; protected put(path: string, data?: unknown, options?: RequestSpec): Promise>; protected patch(path: string, data?: unknown, options?: RequestSpec): Promise>; protected delete(path: string, options?: RequestSpec): Promise>; /** * Execute a request with cursor-based pagination */ protected requestWithPagination(method: string, path: string, paginationOptions: PaginationOptions, options: RequestWithPaginationOptions): Promise>; /** * Validates and prepares pagination parameters from options */ private validateAndPreparePaginationParams; /** * Prepares request parameters for pagination based on pagination type */ private preparePaginationRequestParams; /** * Creates a paginated response from API response */ private createPaginatedResponseFromResponse; /** * Determines if there are more pages based on pagination type and metadata */ private determineHasMorePages; } /** * Shared types for the Data Fabric domain — used by both Entities and ChoiceSets. * Lives here (not in either service's `*.types.ts`) to avoid cross-domain coupling * between sibling services. */ /** * Common shape for every folder-scoped Data Fabric operation. * Forwarded on the wire as the `X-UIPATH-FolderKey` header. */ interface EntityFolderScopedOptions { /** * Key identifying the folder the entity belongs to. Omit for tenant-level entities. * * @experimental Folder-scoped Data Fabric is in preview — the contract may change. */ folderKey?: string; } /** * Entity field data type names (SQL-level types returned by the API) */ declare enum EntityFieldDataType { UUID = "UUID", STRING = "STRING", INTEGER = "INTEGER", DATETIME = "DATETIME", DATETIME_WITH_TZ = "DATETIME_WITH_TZ", DECIMAL = "DECIMAL", FLOAT = "FLOAT", DOUBLE = "DOUBLE", DATE = "DATE", BOOLEAN = "BOOLEAN", BIG_INTEGER = "BIG_INTEGER", MULTILINE_TEXT = "MULTILINE_TEXT", /** * Large multi-line text (up to 128 KB). Unlike {@link MULTILINE_TEXT}, the full * value is lazy-loaded: list/query operations return a size marker * (e.g. `"HasValue=true Length=512"`) instead of the content; reading a single * record by ID returns the full value. */ MULTILINE_MAX = "MULTILINE_MAX", FILE = "FILE", CHOICE_SET_SINGLE = "CHOICE_SET_SINGLE", CHOICE_SET_MULTIPLE = "CHOICE_SET_MULTIPLE", AUTO_NUMBER = "AUTO_NUMBER", RELATIONSHIP = "RELATIONSHIP" } /** * Represents a single entity record */ interface EntityRecord { /** * Unique identifier for the record */ Id: string; /** * Additional dynamic fields for the entity */ [key: string]: any; } /** * Options for getting an entity by Id * @deprecated Use {@link EntityGetRecordByIdOptions} instead for better clarity on getting all records of an entity. This type will be removed in future versions. */ type EntityGetRecordsByIdOptions = { /** Level of entity expansion (default: 0) */ expansionLevel?: number; } & PaginationOptions & EntityFolderScopedOptions; /** * Options for getting all records of an entity */ type EntityGetAllRecordsOptions = EntityGetRecordsByIdOptions; /** * Options for getting a single entity record by entity ID and record ID */ interface EntityGetRecordByIdOptions extends EntityFolderScopedOptions { /** Level of entity expansion (default: 0) */ expansionLevel?: number; } /** * Common options for entity operations that modify multiple records */ interface EntityOperationOptions extends EntityFolderScopedOptions { /** Level of entity expansion (default: 0) */ expansionLevel?: number; /** Whether to fail on first error (default: false) */ failOnFirst?: boolean; } /** * Options for inserting a single record into an entity * @deprecated Use {@link EntityInsertRecordOptions} instead for better clarity on inserting a single record into an entity. This type will be removed in future versions. */ interface EntityInsertOptions extends EntityFolderScopedOptions { /** Level of entity expansion (default: 0) */ expansionLevel?: number; } /** * Options for inserting a single record into an entity */ interface EntityInsertRecordOptions extends EntityInsertOptions { } /** * Options for batch inserting data into an entity * @deprecated Use {@link EntityInsertRecordsOptions} instead for better clarity on inserting multiple records into an entity. This type will be removed in future versions. */ interface EntityBatchInsertOptions extends EntityOperationOptions { } /** * Options for inserting multiple records into an entity */ interface EntityInsertRecordsOptions extends EntityOperationOptions { } /** * Options for updating a single record in an entity */ interface EntityUpdateRecordOptions extends EntityGetRecordByIdOptions { } /** * Options for updating data in an entity * @deprecated Use {@link EntityUpdateRecordsOptions} instead for better clarity on updating records in an entity. This type will be removed in future versions. */ interface EntityUpdateOptions extends EntityOperationOptions { } /** * Options for updating data in an entity */ interface EntityUpdateRecordsOptions extends EntityOperationOptions { } /** * Options for deleting data from an entity * @deprecated Use {@link EntityDeleteRecordsOptions} instead for better clarity on deleting records from an entity. This type will be removed in future versions. */ interface EntityDeleteOptions extends EntityFolderScopedOptions { /** Whether to fail on first error (default: false) */ failOnFirst?: boolean; } /** * Options for deleting records in an entity */ interface EntityDeleteRecordsOptions extends EntityDeleteOptions { } interface EntityDeleteRecordByIdOptions extends EntityFolderScopedOptions { } interface EntityImportRecordsByIdOptions extends EntityFolderScopedOptions { } /** * Logical operator for combining query filter groups */ declare enum LogicalOperator$1 { /** Combine conditions with AND — all conditions must match */ And = 0, /** Combine conditions with OR — any condition must match */ Or = 1 } /** * Comparison operators for entity query filters. * Not all operators are valid for all field types. */ declare enum QueryFilterOperator { Equals = "=", NotEquals = "!=", GreaterThan = ">", LessThan = "<", GreaterThanOrEqual = ">=", LessThanOrEqual = "<=", Contains = "contains", NotContains = "not contains", StartsWith = "startswith", EndsWith = "endswith", In = "in", NotIn = "not in" } /** * A single filter condition for querying entity records * * Values are always strings. For numeric or boolean fields, pass the string representation * (e.g., `"42"`, `"true"`). For `In` / `NotIn` operators, use {@link valueList} instead of `value`. */ interface EntityQueryFilter { /** Name of the field to filter on */ fieldName: string; /** Comparison operator */ operator: QueryFilterOperator; /** Value to compare against (always a string; omit when using `valueList`) */ value?: string; /** List of values for `in` / `not in` operators */ valueList?: string[]; } /** * A group of query filters combined with a logical operator */ interface EntityQueryFilterGroup { /** Logical operator applied between filters in `queryFilters` (default: AND) */ logicalOperator?: LogicalOperator$1; /** Logical operator applied between sibling filter groups (default: AND) */ continueLogicalOperator?: LogicalOperator$1; /** Array of filter conditions */ queryFilters?: EntityQueryFilter[]; /** Nested filter groups for complex boolean expressions */ filterGroups?: EntityQueryFilterGroup[]; } /** * Sort option for query results */ interface EntityQuerySortOption { /** Name of the field to sort by */ fieldName: string; /** Whether to sort in descending order (default: false) */ isDescending?: boolean; } /** * Aggregate functions supported by the Data Fabric query API. */ declare enum EntityAggregateFunction { Count = "COUNT", Sum = "SUM", Avg = "AVG", Min = "MIN", Max = "MAX" } /** * A single aggregate expression to apply during a query. * * Aggregate results are returned as fields on each item in the response, * keyed by `alias` when provided. */ interface EntityAggregate { /** Aggregate function to apply */ function: EntityAggregateFunction; /** Field to aggregate on. For `COUNT`, any non-null field works (typically `Id`). */ field: string; /** Optional alias for the aggregate result column. */ alias?: string; } /** * A single cross-entity JOIN clause for a structured query. * * A join pulls related records together by matching a field on the base (left) * entity (`joinFieldName`) to a field on a related (right) entity * (`relatedFieldName`). Pass one {@link EntityJoin} per related entity; supplying * several composes a multi-entity (multi-join) query. Up to 3 joins are * supported (the SDK throws a `ValidationError` for more), and all of them * must share the same {@link JoinType}. * * @example * ```typescript * import { EntityJoin, JoinType } from '@uipath/uipath-typescript/entities'; * * const join: EntityJoin = { * entityName: "Order", * joinType: JoinType.LeftJoin, * joinFieldName: "customerId", * relatedEntityName: "Customer", * relatedFieldName: "Id", * }; * ``` */ interface EntityJoin { /** Name of the base (left) entity that owns `joinFieldName`. Defaults to the queried entity; set it to anchor chained joins. */ entityName?: string; /** Join type to apply (default: {@link JoinType.LeftJoin}). */ joinType?: JoinType; /** Field on the base entity used as the join key. */ joinFieldName: string; /** Name of the related (right) entity to join in. */ relatedEntityName: string; /** Field on `relatedEntityName` matched against `joinFieldName`. */ relatedFieldName: string; } /** * Options for querying entity records with filters, sorting, aggregates, and pagination. * * Use `pageSize`, `cursor`, or `jumpToPage` for SDK-managed pagination. * The SDK computes and manages offset parameters automatically. */ type EntityQueryRecordsOptions = { /** Filter conditions to apply */ filterGroup?: EntityQueryFilterGroup; /** List of field names to include in results (returns all fields if omitted) */ selectedFields?: string[]; /** Sort options for the results */ sortOptions?: EntityQuerySortOption[]; /** Level of entity expansion for related fields (default: 0) */ expansionLevel?: number; /** Aggregate expressions (COUNT, SUM, AVG, MIN, MAX) to apply across the result set. */ aggregates?: EntityAggregate[]; /** Field names to group aggregate results by. */ groupBy?: string[]; /** * Cross-entity joins. Each entry joins one related entity into the query; * supply several for a multi-join query. A maximum of 3 joins is supported * (the SDK throws a `ValidationError` for more), and all joins must be of * the same {@link JoinType}. */ joins?: EntityJoin[]; } & PaginationOptions & EntityFolderScopedOptions; /** * Response from querying entity records */ interface EntityQueryRecordsResponse { /** Array of matching entity records */ items: EntityRecord[]; /** Total number of records matching the filter (before pagination) */ totalCount: number; } /** * Common field properties shared across field definition and update types */ interface EntityFieldBase { /** Human-readable display name shown in the UI (defaults to `name` if omitted) */ displayName?: string; /** Optional field description */ description?: string; /** Whether the field is required (default: false) */ isRequired?: boolean; /** Whether the field value must be unique across records (default: false) */ isUnique?: boolean; /** Whether role-based access control is enabled for this field (default: false) */ isRbacEnabled?: boolean; /** Whether the field value is encrypted at rest (default: false) */ isEncrypted?: boolean; /** Whether the field is hidden from the UI (default: false) */ isHiddenField?: boolean; /** Default value for the field */ defaultValue?: string; /** Maximum character length for STRING fields (default: 200, range: 1–4000) and MULTILINE_TEXT fields (default: 200, range: 1–10000). */ lengthLimit?: number; /** Maximum allowed value for numeric fields (INTEGER, BIG_INTEGER, FLOAT, DOUBLE, DECIMAL — default: 1,000,000,000,000; range: ±9,007,199,254,740,991) */ maxValue?: number; /** Minimum allowed value for numeric fields (INTEGER, BIG_INTEGER, FLOAT, DOUBLE, DECIMAL — default: -1,000,000,000,000; range: ±9,007,199,254,740,991) */ minValue?: number; /** Number of decimal places for DECIMAL, FLOAT, and DOUBLE fields (default: 2, range: 0–10) */ decimalPrecision?: number; } /** * User-facing field definition for creating or updating entity schemas */ interface EntityCreateFieldOptions extends EntityFieldBase { /** * Field name — must start with a letter and contain only * letters, numbers, and underscores (e.g., `"productName"`). */ fieldName: string; /** Field data type — one of the {@link EntityFieldDataType} values (default: STRING) */ type?: EntityFieldDataType; /** Choice set ID for choice-set fields */ choiceSetId?: string; /** UUID of the referenced entity (required when `type` is `RELATIONSHIP`; ignored for `FILE`). */ referenceEntityId?: string; /** UUID of the referenced field on the target entity (required when `type` is `RELATIONSHIP`; ignored for `FILE`). */ referenceFieldId?: string; /** * Folder key of the reference target when it lives outside the source's folder. Pass `'00000000-0000-0000-0000-000000000000'` for tenant-level system targets. * * @experimental Folder-scoped Data Fabric is in preview — the contract may change. */ referenceFolderKey?: string; } interface EntityGetAllOptions extends EntityFolderScopedOptions { /** * When `true`, returns tenant-level and folder-level entities together. * Omit (or `false`, the default) to return only tenant-level entities. * Ignored when `folderKey` is provided — `folderKey` is preferred over `includeFolderEntities` when both are set. * * @experimental Folder-scoped Data Fabric is in preview — the contract may change. */ includeFolderEntities?: boolean; } interface EntityGetByIdOptions extends EntityFolderScopedOptions { } interface EntityDeleteByIdOptions extends EntityFolderScopedOptions { } /** * Options for creating a new Data Fabric entity */ interface EntityCreateOptions extends EntityFolderScopedOptions { /** Human-readable display name shown in the UI (defaults to `name` if omitted) */ displayName?: string; /** Optional entity description */ description?: string; /** Whether role-based access control is enabled for this entity (default: false) */ isRbacEnabled?: boolean; /** Whether Analytics integration is enabled for this entity (default: false) */ isAnalyticsEnabled?: boolean; /** External field source definitions (default: empty) */ externalFields?: ExternalField[]; } /** * Identifies a field by its ID and supplies metadata updates to apply */ interface EntityFieldUpdateOptions extends EntityFieldBase { /** ID of the field to update */ id: string; } /** * Identifies a field to remove by its name */ interface EntityRemoveFieldOptions { /** Name of the field to remove */ fieldName: string; } /** * Options for updating an existing entity — schema and/or metadata in a single call. * * Schema changes (`addFields`, `removeFields`, `updateFields`) and metadata changes * (`displayName`, `description`, `isRbacEnabled`) can be combined; each is applied * only when the corresponding fields are provided. */ interface EntityUpdateByIdOptions extends EntityFolderScopedOptions { /** New fields to add */ addFields?: EntityCreateFieldOptions[]; /** Fields to remove, each identified by field name */ removeFields?: EntityRemoveFieldOptions[]; /** Fields to update, each identified by its field ID */ updateFields?: EntityFieldUpdateOptions[]; /** New display name for the entity */ displayName?: string; /** New description for the entity */ description?: string; /** Whether role-based access control is enabled for this entity */ isRbacEnabled?: boolean; } /** * Response from a bulk import operation */ interface EntityImportRecordsResponse { /** Total number of records in the import file */ totalRecords: number; /** Number of records successfully inserted */ insertedRecords: number; /** Link to download the error file (if any records failed) */ errorFileLink?: string | null; } /** * Supported file types for attachment upload */ type EntityFileType = Blob | File | Uint8Array; /** * Optional options for uploading an attachment to an entity record */ interface EntityUploadAttachmentOptions extends EntityFolderScopedOptions { /** Optional expansion level (default: 0) */ expansionLevel?: number; } /** * Optional options for downloading an attachment from an entity record */ interface EntityDownloadAttachmentOptions extends EntityFolderScopedOptions { } /** * Optional options for deleting an attachment from an entity record */ interface EntityDeleteAttachmentOptions extends EntityFolderScopedOptions { } /** * Response from uploading an attachment to an entity record */ type EntityUploadAttachmentResponse = Record; /** * Response from deleting an attachment from an entity record */ type EntityDeleteAttachmentResponse = Record; /** * Represents a failure record in an entity operation */ interface FailureRecord { /** Error message */ error?: string; /** Original record that failed */ record?: Record; } /** * Response from an entity operation that modifies multiple records */ interface EntityOperationResponse { /** Records that were successfully processed */ successRecords: Record[]; /** Records that failed processing */ failureRecords: FailureRecord[]; } /** * Response from inserting a single record into an entity. * Returns the inserted record with its generated record ID and other fields. */ interface EntityInsertResponse extends EntityRecord { } /** * Response from updating a single record in an entity. * Returns the updated record. */ interface EntityUpdateRecordResponse extends EntityRecord { } /** * Response from batch inserting data into an entity */ interface EntityBatchInsertResponse extends EntityOperationResponse { } /** * Response from updating data in an entity */ interface EntityUpdateResponse extends EntityOperationResponse { } /** * Response from deleting data from an entity */ interface EntityDeleteResponse extends EntityOperationResponse { } /** * Entity type enum */ declare enum EntityType { Entity = "Entity", ChoiceSet = "ChoiceSet", InternalEntity = "InternalEntity", SystemEntity = "SystemEntity" } /** * Field type metadata */ interface FieldDataType { name: EntityFieldDataType; lengthLimit?: number; maxValue?: number; minValue?: number; decimalPrecision?: number; } /** * Reference types for fields */ declare enum ReferenceType { ManyToOne = "ManyToOne" } /** * Field display types */ declare enum FieldDisplayType { Basic = "Basic", Relationship = "Relationship", File = "File", ChoiceSetSingle = "ChoiceSetSingle", ChoiceSetMultiple = "ChoiceSetMultiple", AutoNumber = "AutoNumber" } /** * Data direction type for external fields */ declare enum DataDirectionType { ReadOnly = "ReadOnly", ReadAndWrite = "ReadAndWrite" } /** * Join type applied when matching records across entities. * * Used by {@link EntityJoin} for cross-entity query joins and by * {@link SourceJoinCriteria} in entity metadata. */ declare enum JoinType { /** LEFT JOIN — all base-entity records, with related fields empty when unmatched. */ LeftJoin = "LeftJoin" } /** * Field reference with ID */ interface Field$1 { id: string; definition?: FieldMetaData; } /** * SQL type metadata */ interface SqlType { /** Raw SQL type name (e.g., `"NVARCHAR"`, `"INT"`, `"UNIQUEIDENTIFIER"`) */ name: string; lengthLimit?: number; maxValue?: number; minValue?: number; decimalPrecision?: number; } /** * Detailed field definition */ interface FieldMetaData { id: string; name: string; isPrimaryKey: boolean; isForeignKey: boolean; isExternalField: boolean; isHiddenField: boolean; isUnique: boolean; isRequired: boolean; isSystemField: boolean; isAttachment: boolean; isEncrypted: boolean; isRbacEnabled: boolean; fieldDisplayType: FieldDisplayType; /** Transformed field data type — present after SDK transformation */ fieldDataType: FieldDataType; createdTime: string; createdBy: string; /** Raw SQL type from API — present on raw GET responses, used on write payloads */ sqlType?: SqlType; updatedTime?: string; updatedBy?: string; displayName?: string; description?: string; referenceName?: string; referenceEntity?: RawEntityGetResponse; referenceChoiceSet?: RawEntityGetResponse; referenceField?: Field$1; referenceType?: ReferenceType; choiceSetId?: string; defaultValue?: string; } /** * External object details */ interface ExternalObject { id: string; externalObjectName?: string; externalObjectDisplayName?: string; primaryKey?: string; externalConnectionId: string; entityId?: string; isPrimarySource: boolean; } /** * External connection details */ interface ExternalConnection { id: string; connectionId: string; elementInstanceId: number; folderKey: string; connectorKey?: string; connectorName?: string; connectionName?: string; } /** * External field mapping */ interface ExternalFieldMapping { id: string; externalFieldName?: string; externalFieldDisplayName?: string; externalObjectId: string; externalFieldType?: string; internalFieldId: string; directionType: DataDirectionType; } /** * External field */ interface ExternalField { fieldMetaData: FieldMetaData; externalFieldMappingDetail: ExternalFieldMapping; } /** * External source fields */ interface ExternalSourceFields { fields?: ExternalField[]; externalObjectDetail?: ExternalObject; externalConnectionDetail?: ExternalConnection; } /** * Source join criteria */ interface SourceJoinCriteria { id: string; entityId: string; joinFieldName?: string; joinType: JoinType; relatedSourceObjectId?: string; relatedSourceFieldName?: string; } /** * Entity metadata returned by getById */ interface RawEntityGetResponse { name: string; displayName: string; entityType: EntityType; description?: string; fields: FieldMetaData[]; folderId?: string; externalFields?: ExternalSourceFields[]; sourceJoinCriterias?: SourceJoinCriteria[]; recordCount?: number; storageSizeInMB?: number; usedStorageSizeInMB?: number; attachmentSizeInByte?: number; isRbacEnabled: boolean; isInsightsEnabled?: boolean; id: string; createdBy: string; createdTime: string; updatedTime?: string; updatedBy?: string; } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Entities } from '@uipath/uipath-typescript/entities'; * * const entities = new Entities(sdk); * const allEntities = await entities.getAll(); * ``` */ interface EntityServiceModel { /** * 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. * * @param options - Optional {@link 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 resolving to an array of entity metadata * {@link EntityGetResponse} * @example * ```typescript * // 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 } * ]); * } * ``` */ getAll(options?: EntityGetAllOptions): Promise; /** * Gets entity metadata by entity ID with attached operation methods * * @param id - UUID of the entity * @param options - Optional {@link EntityGetByIdOptions} (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving to entity metadata with operation methods * {@link EntityGetResponse} * @example * ```typescript * 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 } * ]); * ``` */ getById(id: string, options?: EntityGetByIdOptions): Promise; /** * 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 {@link getRecordById} to retrieve the full value. * * @param entityId - UUID of the entity * @param options - Query options The `folderKey` property is **experimental**. * @returns Promise resolving to either an array of entity records NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link EntityRecord} * @example * ```typescript * // 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: "" }); * ``` */ getAllRecords(entityId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * @deprecated Use {@link getAllRecords} instead. * @hidden */ getRecordsById(entityId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single entity record by entity ID and record ID * * Returns the full record, including the complete content of `MULTILINE_MAX` fields. * * @param entityId - UUID of the entity * @param recordId - UUID of the record * @param options - Query options The `folderKey` property is **experimental**. * @returns Promise resolving to a single entity record * {@link EntityRecord} * @example * ```typescript * // 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: "" * }); * ``` */ getRecordById(entityId: string, recordId: string, options?: EntityGetRecordByIdOptions): Promise; /** * 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. * * @param id - UUID of the entity * @param data - Record to insert * @param options - Insert options The `folderKey` property is **experimental**. * @returns Promise resolving to the inserted record with generated record ID * {@link EntityInsertResponse} * @example * ```typescript * // 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: "" * }); * ``` */ insertRecordById(id: string, data: Record, options?: EntityInsertRecordOptions): Promise; /** * @deprecated Use {@link insertRecordById} instead. * @hidden */ insertById(id: string, data: Record, options?: EntityInsertOptions): Promise; /** * Inserts one or more records into an entity by entity ID * * Note: Records inserted using insertRecordsById will not trigger Data Fabric trigger events. Use {@link insertRecordById} if you need * trigger events to fire for each inserted record. * * @param id - UUID of the entity * @param data - Array of records to insert * @param options - Insert options The `folderKey` property is **experimental**. * @returns Promise resolving to insert response * {@link EntityBatchInsertResponse} * @example * ```typescript * // 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: "" }); * ``` */ insertRecordsById(id: string, data: Record[], options?: EntityInsertRecordsOptions): Promise; /** * @deprecated Use {@link insertRecordsById} instead. * @hidden */ batchInsertById(id: string, data: Record[], options?: EntityBatchInsertOptions): Promise; /** * 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. * * @param entityId - UUID of the entity * @param recordId - UUID of the record to update * @param data - Key-value pairs of fields to update * @param options - Update options The `folderKey` property is **experimental**. * @returns Promise resolving to the updated record * {@link EntityUpdateRecordResponse} * @example * ```typescript * // 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: "" * }); * ``` */ updateRecordById(entityId: string, recordId: string, data: Record, options?: EntityUpdateRecordOptions): Promise; /** * Updates data in an entity by entity ID * * Note: Records updated using updateRecordsById will not trigger Data Fabric trigger events. Use {@link updateRecordById} if you need trigger events to fire for each updated record. * * @param id - UUID of the entity * @param data - Array of records to update. Each record MUST contain the record id. * @param options - Update options The `folderKey` property is **experimental**. * @returns Promise resolving to update response * {@link EntityUpdateResponse} * @example * ```typescript * // 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: "" }); * ``` */ updateRecordsById(id: string, data: EntityRecord[], options?: EntityUpdateRecordsOptions): Promise; /** * Deletes data from an entity by entity ID * * Note: Records deleted using deleteRecordsById will not trigger Data Fabric trigger events. Use {@link deleteRecordById} if you need trigger events to fire for the deleted record. * * @param id - UUID of the entity * @param recordIds - Array of record UUIDs to delete * @param options - Delete options The `folderKey` property is **experimental**. * @returns Promise resolving to delete response * {@link EntityDeleteResponse} * @example * ```typescript * // Basic usage * const result = await entities.deleteRecordsById(, [ * , * ]); * * // Folder-scoped entity: pass the entity's folder key * await entities.deleteRecordsById(, [ * , * ], { folderKey: "" }); * ``` */ deleteRecordsById(id: string, recordIds: string[], options?: EntityDeleteRecordsOptions): Promise; /** * 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. * * @param entityId - UUID of the entity * @param recordId - UUID of the record to delete * @param options - Optional {@link EntityDeleteRecordByIdOptions} (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving to void on success * @example * ```typescript * 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: "" }); * ``` */ deleteRecordById(entityId: string, recordId: string, options?: EntityDeleteRecordByIdOptions): Promise; /** * 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 {@link getRecordById} to retrieve the full value. * * @param id - UUID of the entity * @param options - Query options including filterGroup, selectedFields, sortOptions, aggregates, groupBy, joins, and pagination The `folderKey` property is **experimental**. * @returns Promise resolving to {@link NonPaginatedResponse} without pagination options, * or {@link PaginatedResponse} when `pageSize`, `cursor`, or `jumpToPage` are provided * @example * ```typescript * 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", * }, * ], * }); * ``` */ queryRecordsById(id: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Imports records from a CSV file into an entity * * @param id - UUID of the entity * @param file - CSV file to import as a Blob or File or Uint8Array * @param options - Optional {@link EntityImportRecordsByIdOptions} (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving to {@link EntityImportRecordsResponse} with record counts * @example * ```typescript * // 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: "" }); * ``` */ importRecordsById(id: string, file: EntityFileType, options?: EntityImportRecordsByIdOptions): Promise; /** * Downloads an attachment stored in a File-type field of an entity record. * * @param entityId - UUID of the entity * @param recordId - UUID of the record containing the attachment * @param fieldName - Name of the File-type field containing the attachment * @param options - Optional {@link EntityDownloadAttachmentOptions} (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving to Blob containing the file content * @example * ```typescript * 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); * ``` */ downloadAttachment(entityId: string, recordId: string, fieldName: string, options?: EntityDownloadAttachmentOptions): Promise; /** * 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. * * @param entityId - UUID of the entity * @param recordId - UUID of the record to upload the attachment to * @param fieldName - Name of the File-type field * @param file - File to upload (Blob, File, or Uint8Array) * @param options - Optional {@link EntityUploadAttachmentOptions} (e.g. `expansionLevel`, `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving to {@link EntityUploadAttachmentResponse} * @example * ```typescript * 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); * ``` */ uploadAttachment(entityId: string, recordId: string, fieldName: string, file: EntityFileType, options?: EntityUploadAttachmentOptions): Promise; /** * Removes an attachment from a File-type field of an entity record. * * @param entityId - UUID of the entity * @param recordId - UUID of the record containing the attachment * @param fieldName - Name of the File-type field containing the attachment * @param options - Optional {@link EntityDeleteAttachmentOptions} (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving to {@link EntityDeleteAttachmentResponse} * @example * ```typescript * 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'); * ``` */ deleteAttachment(entityId: string, recordId: string, fieldName: string, options?: EntityDeleteAttachmentOptions): Promise; /** * Creates a new Data Fabric entity with the given schema * * @param name - Entity name — must start with a letter, letters/numbers/underscores only * (e.g., `"productCatalog"`). * @param fields - Array of field definitions * @param options - Optional entity-level settings ({@link EntityCreateOptions}) The `folderKey` property is **experimental**. * @returns Promise resolving to the ID of the created entity * @example * ```typescript * import { Entities } from '@uipath/uipath-typescript/entities'; * * const entities = new Entities(sdk); * * const id = await entities.create("product_catalog", [ * { fieldName: "product_name", type: EntityFieldDataType.STRING, isRequired: true, isUnique: true }, * { fieldName: "price", type: EntityFieldDataType.INTEGER, defaultValue: "0" }, * ], { displayName: "Product Catalog", description: "Our product catalog", isRbacEnabled: true }); * * // With advanced sqlType constraints (lengthLimit, decimalPrecision, maxValue, minValue) and defaultValue * const ordersId = await entities.create("orders", [ * { fieldName: "product_name", type: EntityFieldDataType.STRING, isRequired: true, isUnique: true, lengthLimit: 500 }, * { fieldName: "price", type: EntityFieldDataType.DECIMAL, decimalPrecision: 4, maxValue: 999999, minValue: 0 }, * { fieldName: "quantity", type: EntityFieldDataType.INTEGER, maxValue: 10000, minValue: 1, defaultValue: "0" }, * ]); * * // Cross-folder references — link a folder-scoped entity to entities and * // system choice sets that live in another folder or at the tenant level. * await entities.create("orderLine", [ * { * fieldName: "order", * type: EntityFieldDataType.RELATIONSHIP, * referenceEntityId: "", * referenceFieldId: "", * referenceFolderKey: "", // target lives in a different folder * }, * { * fieldName: "userType", * type: EntityFieldDataType.CHOICE_SET_SINGLE, * choiceSetId: "", // tenant-level system choice set * // referenceFolderKey omitted → SDK looks up the target at tenant scope * }, * ], { folderKey: "" }); * ``` * @internal */ create(name: string, fields: EntityCreateFieldOptions[], options?: EntityCreateOptions): Promise; /** * Deletes a Data Fabric entity and all its records * * @param id - UUID of the entity to delete * @param options - Optional {@link EntityDeleteByIdOptions} (e.g. `folderKey` for folder-scoped entities) The `folderKey` property is **experimental**. * @returns Promise resolving when the entity is deleted * @example * ```typescript * await entities.deleteById(); * * // Folder-scoped: pass the entity's folder key * await entities.deleteById(, { folderKey: "" }); * ``` * @internal */ deleteById(id: string, options?: EntityDeleteByIdOptions): Promise; /** * Updates an existing Data Fabric entity — schema and/or metadata. * * Pass any combination of schema fields (`addFields`, `removeFields`, `updateFields`) and * metadata fields (`displayName`, `description`, `isRbacEnabled`). Each group is applied * only when the corresponding fields are provided. * * @param id - UUID of the entity to update * @param options - Changes to apply ({@link EntityUpdateByIdOptions}) The `folderKey` property is **experimental**. * @returns Promise resolving when the update is complete * * @example * ```typescript * // Schema-only: add a field and remove another * await entities.updateById(, { * addFields: [{ fieldName: "notes", type: EntityFieldDataType.MULTILINE_TEXT }], * removeFields: [{ fieldName: "old_field" }], * }); * * // Metadata-only: rename the entity * await entities.updateById(, { * displayName: "My Updated Entity", * description: "Updated description", * }); * * // Combined: update a field and rename at the same time * await entities.updateById(, { * updateFields: [{ id: , displayName: "Unit Price", isRequired: true }], * displayName: "Price Catalog", * }); * * // Add a STRING/DECIMAL field with explicit advanced sqlType constraints and defaultValue * await entities.updateById(, { * addFields: [ * { fieldName: "summary", type: EntityFieldDataType.STRING, lengthLimit: 500, defaultValue: "summary" }, * { fieldName: "amount", type: EntityFieldDataType.DECIMAL, decimalPrecision: 4, maxValue: 999999, minValue: 0 }, * ], * updateFields: [ * { id: , lengthLimit: 1000 }, * ], * }); * * // Folder-scoped entity: add a field to an entity that lives in a non-tenant folder * await entities.updateById(, { * folderKey: "", * addFields: [{ fieldName: "notes", type: EntityFieldDataType.MULTILINE_TEXT }], * }); * ``` * @internal */ updateById(id: string, options?: EntityUpdateByIdOptions): Promise; } /** * Entity methods interface - defines operations that can be performed on an entity */ interface EntityMethods { /** * Insert a single record into this entity * * 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. * * @param data - Record to insert * @param options - Insert options * @returns Promise resolving to the inserted record with generated record ID */ insertRecord(data: Record, options?: EntityInsertRecordOptions): Promise; /** * Insert multiple records into this entity using insertRecords * * Note: Inserting multiple records do not trigger Data Fabric trigger events. Use {@link insertRecord} if you need * trigger events to fire for each inserted record. * * @param data - Array of records to insert * @param options - Insert options * @returns Promise resolving to batch insert response */ insertRecords(data: Record[], options?: EntityInsertRecordsOptions): Promise; /** * Update a single record in this entity * * 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. * * @param recordId - UUID of the record to update * @param data - Key-value pairs of fields to update * @param options - Update options * @returns Promise resolving to the updated record */ updateRecord(recordId: string, data: Record, options?: EntityUpdateRecordOptions): Promise; /** * Update data in this entity * * Note: Records updated using updateRecords will not trigger Data Fabric trigger events. Use {@link updateRecord} if you need * trigger events to fire for each updated record. * * @param data - Array of records to update. Each record MUST contain the record Id, * otherwise the update will fail. * @param options - Update options * @returns Promise resolving to update response */ updateRecords(data: EntityRecord[], options?: EntityUpdateRecordsOptions): Promise; /** * Delete data from this entity * * Note: Records deleted using deleteRecords will not trigger Data Fabric trigger events. Use {@link deleteRecord} if you need trigger events to fire for the deleted record. * * @param recordIds - Array of record UUIDs to delete * @param options - Delete options * @returns Promise resolving to delete response */ deleteRecords(recordIds: string[], options?: EntityDeleteRecordsOptions): Promise; /** * Delete a single record from this entity * * 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. * * @param recordId - UUID of the record to delete * @param options - Optional {@link EntityDeleteRecordByIdOptions} (e.g. `folderKey` for folder-scoped entities) * @returns Promise resolving to void on success */ deleteRecord(recordId: string, options?: EntityDeleteRecordByIdOptions): Promise; /** * Get all records from this entity * * @param options - Query options The `folderKey` property is **experimental**. * @returns Promise resolving to query response */ getAllRecords(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single record from this entity by record ID * * @param recordId - UUID of the record * @param options - Query options including expansionLevel * @returns Promise resolving to the entity record */ getRecord(recordId: string, options?: EntityGetRecordByIdOptions): Promise; /** * Downloads an attachment stored in a File-type field of an entity record * * @param recordId - UUID of the record containing the attachment * @param fieldName - Name of the File-type field containing the attachment * @param options - Optional {@link EntityDownloadAttachmentOptions} (e.g. folderKey) The `folderKey` property is **experimental**. * @returns Promise resolving to Blob containing the file content */ downloadAttachment(recordId: string, fieldName: string, options?: EntityDownloadAttachmentOptions): Promise; /** * Uploads an attachment to a File-type field of an entity record * * @param recordId - UUID of the record to upload the attachment to * @param fieldName - Name of the File-type field * @param file - File to upload (Blob, File, or Uint8Array) * @param options - Optional {@link EntityUploadAttachmentOptions} (e.g. expansionLevel, folderKey) The `folderKey` property is **experimental**. * @returns Promise resolving to {@link EntityUploadAttachmentResponse} */ uploadAttachment(recordId: string, fieldName: string, file: EntityFileType, options?: EntityUploadAttachmentOptions): Promise; /** * Deletes an attachment from a File-type field of an entity record * * @param recordId - UUID of the record containing the attachment * @param fieldName - Name of the File-type field containing the attachment * @param options - Optional {@link EntityDeleteAttachmentOptions} (e.g. folderKey) The `folderKey` property is **experimental**. * @returns Promise resolving to {@link EntityDeleteAttachmentResponse} */ deleteAttachment(recordId: string, fieldName: string, options?: EntityDeleteAttachmentOptions): Promise; /** * @deprecated Use {@link insertRecord} instead. * @hidden */ insert(data: Record, options?: EntityInsertOptions): Promise; /** * @deprecated Use {@link insertRecords} instead. * @hidden */ batchInsert(data: Record[], options?: EntityBatchInsertOptions): Promise; /** * Queries records in this entity with filters, sorting, aggregates, and SDK-managed pagination * * @param options - Query options including filterGroup, selectedFields, sortOptions, aggregates, groupBy, joins, and pagination * @returns Promise resolving to {@link NonPaginatedResponse} without pagination options, * or {@link PaginatedResponse} when `pageSize`, `cursor`, or `jumpToPage` are provided * @example * ```typescript * import { Entities, LogicalOperator, QueryFilterOperator, EntityAggregateFunction, JoinType } from '@uipath/uipath-typescript/entities'; * * const entities = new Entities(sdk); * * const entity = await entities.getById(); * const result = await entity.queryRecords({ * filterGroup: { * logicalOperator: LogicalOperator.And, * queryFilters: [{ fieldName: "status", operator: QueryFilterOperator.Equals, value: "active" }] * }, * sortOptions: [{ fieldName: "createdTime", isDescending: true }], * }); * console.log(`Found ${result.totalCount} records`); * * // Aggregate: count of records per status * await entity.queryRecords({ * selectedFields: ["status"], * groupBy: ["status"], * aggregates: [ * { function: EntityAggregateFunction.Count, field: "Id", alias: "total" }, * ], * }); * * // Aggregate: total sum and average across all records (no grouping) * await entity.queryRecords({ * 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 entity.queryRecords({ * 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", * }, * ], * }); * ``` */ queryRecords(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Imports records from a CSV file into this entity * * @param file - CSV file to import as a Blob, File, or Uint8Array * @param options - Optional {@link EntityImportRecordsByIdOptions} (e.g. `folderKey` for folder-scoped entities) * @returns Promise resolving to {@link EntityImportRecordsResponse} with record counts * @example * ```typescript * const entity = await entities.getById(); * const fileInput = document.getElementById('csv-input') as HTMLInputElement; * const result = await entity.importRecords(fileInput.files[0]); * console.log(`Inserted ${result.insertedRecords} of ${result.totalRecords} records`); * * // Folder-scoped entity: pass the entity's folder key * await entity.importRecords(fileInput.files[0], { folderKey: "" }); * ``` */ importRecords(file: EntityFileType, options?: EntityImportRecordsByIdOptions): Promise; /** * @deprecated Use {@link getAllRecords} instead. * @hidden */ getRecords(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Deletes this entity and all its records * * @param options - Optional {@link EntityDeleteByIdOptions} (e.g. `folderKey` for folder-scoped entities) * @returns Promise resolving when the entity is deleted * @example * ```typescript * const entity = await entities.getById(); * await entity.delete(); * * // Folder-scoped entity: pass the entity's folder key * await entity.delete({ folderKey: "" }); * ``` * @internal */ delete(options?: EntityDeleteByIdOptions): Promise; /** * Updates this entity — schema and/or metadata. * * @param options - Changes to apply ({@link EntityUpdateByIdOptions}) * @returns Promise resolving when the update is complete * @example * ```typescript * const entity = await entities.getById(); * await entity.update({ * displayName: "Updated Name", * addFields: [{ fieldName: "notes", type: EntityFieldDataType.MULTILINE_TEXT }], * }); * * // Add a STRING/DECIMAL field with explicit advanced sqlType constraints * await entity.update({ * addFields: [ * { fieldName: "summary", type: EntityFieldDataType.STRING, lengthLimit: 500, defaultValue: "string" }, * { fieldName: "amount", type: EntityFieldDataType.DECIMAL, decimalPrecision: 4, maxValue: 999999, minValue: 0 }, * ], * }); * ``` * @internal */ update(options?: EntityUpdateByIdOptions): Promise; } /** * Entity with methods combining metadata with operation methods */ type EntityGetResponse = RawEntityGetResponse & EntityMethods; /** * Creates an actionable entity by combining entity metadata with data and management methods * * @param entityMetadata - Entity metadata * @param service - The entity service instance * @returns Entity metadata with added methods */ declare function createEntityWithMethods(entityData: RawEntityGetResponse, service: EntityServiceModel): EntityGetResponse; /** * Service for interacting with the Data Fabric Entity API */ declare class EntityService extends BaseService implements EntityServiceModel { getById(id: string, options?: EntityGetByIdOptions): Promise; getAllRecords(entityId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getRecordById(entityId: string, recordId: string, options?: EntityGetRecordByIdOptions): Promise; insertRecordById(id: string, data: Record, options?: EntityInsertRecordOptions): Promise; insertRecordsById(id: string, data: Record[], options?: EntityInsertRecordsOptions): Promise; updateRecordById(entityId: string, recordId: string, data: Record, options?: EntityUpdateRecordOptions): Promise; updateRecordsById(id: string, data: EntityRecord[], options?: EntityUpdateRecordsOptions): Promise; deleteRecordsById(id: string, recordIds: string[], options?: EntityDeleteRecordsOptions): Promise; deleteRecordById(entityId: string, recordId: string, options?: EntityDeleteRecordByIdOptions): Promise; getAll(options?: EntityGetAllOptions): Promise; queryRecordsById(id: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; importRecordsById(id: string, file: EntityFileType, options?: EntityImportRecordsByIdOptions): Promise; downloadAttachment(entityId: string, recordId: string, fieldName: string, options?: EntityDownloadAttachmentOptions): Promise; uploadAttachment(entityId: string, recordId: string, fieldName: string, file: EntityFileType, options?: EntityUploadAttachmentOptions): Promise; deleteAttachment(entityId: string, recordId: string, fieldName: string, options?: EntityDeleteAttachmentOptions): Promise; getRecordsById(entityId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; insertById(id: string, data: Record, options?: EntityInsertOptions): Promise; batchInsertById(id: string, data: Record[], options?: EntityBatchInsertOptions): Promise; create(name: string, fields: EntityCreateFieldOptions[], options?: EntityCreateOptions): Promise; deleteById(id: string, options?: EntityDeleteByIdOptions): Promise; updateById(id: string, options?: EntityUpdateByIdOptions): Promise; /** * Fetches the current entity schema, applies the field delta, then posts the full updated schema. * * @param entityId - UUID of the entity to update * @param options - Field changes to apply * @private */ private applySchemaUpdate; /** * Orchestrates all field mapping transformations * * @param metadata - Entity metadata to transform * @private */ private applyFieldMappings; /** * Maps SQL field types to friendly EntityFieldTypes * * @param metadata - Entity metadata with fields * @private */ private mapFieldTypes; /** * Resolves an {@link EntityFieldDataType} from a field's `fieldDisplayType` and * raw SQL type name. Prefers `fieldDisplayType` to disambiguate types that * share a SQL type (FILE, CHOICE_SET_*, AUTO_NUMBER, RELATIONSHIP); falls back * to the SQL-type-name mapping. Returns `undefined` if neither resolves. */ private tryResolveFieldDataType; /** * Transforms nested reference objects in field metadata */ private transformNestedReferences; /** * Maps external field names to consistent naming * * @param metadata - Entity metadata with externalFields * @private */ private mapExternalFields; private buildFieldsWithReferenceMeta; private buildReferenceMeta; /** Converts a user-facing EntityCreateFieldOptions to the raw API field payload */ private buildSchemaFieldPayload; /** * Derives the user-facing {@link EntityFieldDataType} for a field on the raw * API response. Throws if the field's `fieldDisplayType` and `sqlType.name` * are both unmappable. */ private resolveFieldDataType; /** * Validates that the user-supplied constraint properties on a field are * supported by the field's data type. Throws a `ValidationError` listing * any unsupported properties. */ private validateFieldConstraints; /** * Returns the sqlType constraint fields for a given field type. * * The API requires specific constraint properties to be set per SQL type; * without them the field is stored in an incomplete state, causing * "Field type cannot be changed" errors when the UI later tries to edit * advanced options. User-supplied values from `EntityCreateFieldOptions` * override the defaults where the type accepts overrides. */ private buildSqlTypeConstraints; } /** * ChoiceSet Get All Response * Only exposes essential fields to SDK users */ interface ChoiceSetGetAllResponse { /** UUID of the choice set */ id: string; /** Name identifier of the choice set */ name: string; /** Human-readable display name of the choice set*/ displayName: string; /** Description of the choice set */ description: string; /** Folder ID where the choice set is located */ folderId: string; /** User ID who created the choice set */ createdBy: string; /** User ID who last updated the choice set */ updatedBy: string; /** Creation timestamp */ createdTime: string; /** Last update timestamp */ updatedTime: string; } /** * Represents a single choice set value/record */ interface ChoiceSetGetResponse { /** Unique identifier for the choice set value */ id: string; /** Name of the choice set value */ name: string; /** Human-readable display name of the choice set value*/ displayName: string; /** Numeric identifier */ numberId: number; /** Creation timestamp */ createdTime: string; /** Last update timestamp */ updatedTime: string; /** User ID who created this value */ createdBy?: string; /** User ID who last updated this value */ updatedBy?: string; /** User ID of the record owner */ recordOwner?: string; } interface ChoiceSetGetAllOptions extends EntityFolderScopedOptions { /** * When `true`, also returns folder-level choice sets alongside tenant ones. * Omit (or `false`, the default) to return only tenant-level choice sets. * Ignored when `folderKey` is provided — `folderKey` is preferred over `includeFolderChoiceSets` when both are set. * * @experimental Folder-scoped Data Fabric is in preview — the contract may change. */ includeFolderChoiceSets?: boolean; } /** * Options for getting choice set values by choice set ID */ type ChoiceSetGetByIdOptions = PaginationOptions & EntityFolderScopedOptions; /** * Options for creating a new choice set */ interface ChoiceSetCreateOptions extends EntityFolderScopedOptions { /** Human-readable display name */ displayName?: string; /** Optional choice set description */ description?: string; } /** * Options for updating an existing choice set's metadata */ interface ChoiceSetUpdateOptions extends EntityFolderScopedOptions { /** New display name for the choice set */ displayName?: string; /** New description for the choice set */ description?: string; } interface ChoiceSetDeleteByIdOptions extends EntityFolderScopedOptions { } /** * Optional fields when inserting a single value into a choice set. * * The required `name` identifier is passed as a positional argument to * `insertValueById`. */ interface ChoiceSetValueInsertOptions extends EntityFolderScopedOptions { /** Human-readable display name */ displayName?: string; } interface ChoiceSetValueUpdateOptions extends EntityFolderScopedOptions { } interface ChoiceSetValueDeleteOptions extends EntityFolderScopedOptions { } /** * Response returned after inserting a choice-set value — the full value object. */ interface ChoiceSetValueInsertResponse extends ChoiceSetGetResponse { } /** * Response returned after updating a choice-set value — the full value object. */ interface ChoiceSetValueUpdateResponse extends ChoiceSetGetResponse { } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { ChoiceSets } from '@uipath/uipath-typescript/entities'; * * const choicesets = new ChoiceSets(sdk); * const allChoiceSets = await choicesets.getAll(); * ``` */ interface ChoiceSetServiceModel { /** * 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. * * @param options - Optional {@link 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 resolving to an array of choice set metadata * {@link ChoiceSetGetAllResponse} * @example * ```typescript * // 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'); * ``` */ getAll(options?: ChoiceSetGetAllOptions): Promise; /** * 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) * * @param choiceSetId - UUID of the choice set * @param options - Pagination options and optional `folderKey` (omit for tenant-level choice sets) The `folderKey` property is **experimental**. * @returns Promise resolving to choice set values or paginated result * {@link ChoiceSetGetResponse} * @example * ```typescript * // 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: "" }); * ``` */ getById(choiceSetId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Creates a new Data Fabric choice set * * @param name - Choice set name. Must start with a * letter, may contain only letters, numbers, and underscores, length * 3–100 characters (e.g., `"expenseTypes"`). * @param options - Optional choice-set-level settings ({@link ChoiceSetCreateOptions}) The `folderKey` property is **experimental**. * @returns Promise resolving to the UUID of the created choice set * * @example * ```typescript * // Minimal create * const expenseTypesId = await choicesets.create("expense_types"); * * // With display name and description * const priorityLevelsId = await choicesets.create("priority_levels", { * displayName: "Priority Levels", * description: "Ticket priority categories", * }); * ``` * @internal */ create(name: string, options?: ChoiceSetCreateOptions): Promise; /** * Updates an existing choice set's metadata (display name and/or description). * * **At least one of `displayName` or `description` must be provided** — * the call throws `ValidationError` if both are omitted. * * @param choiceSetId - UUID of the choice set to update * @param options - Metadata fields to change ({@link ChoiceSetUpdateOptions}) The `folderKey` property is **experimental**. * @returns Promise resolving when the update is complete * * @example * ```typescript * // First, get the choice set ID using getAll() * const allChoiceSets = await choicesets.getAll(); * const expenseTypes = allChoiceSets.find(cs => cs.name === 'expense_types'); * * await choicesets.updateById(expenseTypes.id, { * displayName: "Expense Categories", * description: "Updated description", * }); * ``` * @internal */ updateById(choiceSetId: string, options: ChoiceSetUpdateOptions): Promise; /** * Deletes a Data Fabric choice set and all its values. * * @param choiceSetId - UUID of the choice set to delete * @param options - Optional {@link ChoiceSetDeleteByIdOptions} — pass `folderKey` for folder-scoped choice sets; omit for tenant-level The `folderKey` property is **experimental**. * @returns Promise resolving when the choice set is deleted * * @example * ```typescript * // First, get the choice set ID using getAll() * const allChoiceSets = await choicesets.getAll(); * const expenseTypes = allChoiceSets.find(cs => cs.name === 'expense_types'); * * await choicesets.deleteById(expenseTypes.id); * * // Folder-scoped choice set * await choicesets.deleteById(expenseTypes.id, { folderKey: "" }); * ``` * @internal */ deleteById(choiceSetId: string, options?: ChoiceSetDeleteByIdOptions): Promise; /** * Inserts a single value into a choice set. * * @param choiceSetId - UUID of the parent choice set * @param name - Identifier name of the new value (e.g., `"TRAVEL"`) * @param options - Optional fields ({@link ChoiceSetValueInsertOptions}) The `folderKey` property is **experimental**. * @returns Promise resolving to the inserted value ({@link ChoiceSetValueInsertResponse}) * * @example * ```typescript * // First, get the choice set ID using getAll() * const allChoiceSets = await choicesets.getAll(); * const expenseTypes = allChoiceSets.find(cs => cs.name === 'expense_types'); * * const inserted = await choicesets.insertValueById(expenseTypes.id, 'TRAVEL', { * displayName: 'Travel', * }); * console.log(inserted.id); * * // Folder-scoped choice set: folderKey is required on the wire * await choicesets.insertValueById(expenseTypes.id, 'TRAVEL', { * displayName: 'Travel', * folderKey: "", * }); * ``` * @internal */ insertValueById(choiceSetId: string, name: string, options?: ChoiceSetValueInsertOptions): Promise; /** * Updates an existing choice-set value's display name. * * Only `displayName` is mutable; the value's `name` (identifier) is fixed at * insert time and cannot be changed. * * @param choiceSetId - UUID of the parent choice set * @param valueId - UUID of the value to update * @param displayName - New human-readable display name for the value * @param options - Optional {@link ChoiceSetValueUpdateOptions} — pass `folderKey` for folder-scoped choice sets; omit for tenant-level. The `folderKey` property is **experimental**. * @returns Promise resolving to the updated value ({@link ChoiceSetValueUpdateResponse}) * * @example * ```typescript * // Get the choice set ID from getAll() and the value ID from getById() * const allChoiceSets = await choicesets.getAll(); * const expenseTypes = allChoiceSets.find(cs => cs.name === 'expense_types'); * const values = await choicesets.getById(expenseTypes.id); * const travel = values.items.find(v => v.name === 'TRAVEL'); * * await choicesets.updateValueById(expenseTypes.id, travel.id, 'Business Travel'); * * // Folder-scoped choice set: folderKey is required on the wire * await choicesets.updateValueById(expenseTypes.id, travel.id, 'Business Travel', { * folderKey: "", * }); * ``` * @internal */ updateValueById(choiceSetId: string, valueId: string, displayName: string, options?: ChoiceSetValueUpdateOptions): Promise; /** * Deletes one or more values from a choice set. * * @param choiceSetId - UUID of the parent choice set * @param valueIds - Array of value UUIDs to delete * @param options - Optional {@link ChoiceSetValueDeleteOptions} — pass `folderKey` for folder-scoped choice sets; omit for tenant-level The `folderKey` property is **experimental**. * @returns Promise resolving when the values are deleted * * @example * ```typescript * // Get the value IDs from getById() * const values = await choicesets.getById(''); * const idsToDelete = values.items.slice(0, 2).map(v => v.id); * * await choicesets.deleteValuesById('', idsToDelete); * * // Folder-scoped choice set * await choicesets.deleteValuesById('', idsToDelete, { folderKey: "" }); * ``` * @internal */ deleteValuesById(choiceSetId: string, valueIds: string[], options?: ChoiceSetValueDeleteOptions): Promise; } declare class ChoiceSetService extends BaseService implements ChoiceSetServiceModel { getAll(options?: ChoiceSetGetAllOptions): Promise; /** * Internal helper that performs the choice-set fetch. Kept separate from the * public `getAll()` so that internal callers (e.g. `resolveChoiceSetName`) * can reuse it without triggering double `@track` telemetry. */ private fetchAllChoiceSets; getById(choiceSetId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; create(name: string, options?: ChoiceSetCreateOptions): Promise; updateById(choiceSetId: string, options: ChoiceSetUpdateOptions): Promise; deleteById(choiceSetId: string, options?: ChoiceSetDeleteByIdOptions): Promise; insertValueById(choiceSetId: string, name: string, options?: ChoiceSetValueInsertOptions): Promise; updateValueById(choiceSetId: string, valueId: string, displayName: string, options?: ChoiceSetValueUpdateOptions): Promise; deleteValuesById(choiceSetId: string, valueIds: string[], options?: ChoiceSetValueDeleteOptions): Promise; private resolveChoiceSetName; } /** * @internal */ declare enum DataFabricRoleType { System = "System", UserDefined = "UserDefined" } /** * @internal */ interface DataFabricRole { id: string; name: string; type: DataFabricRoleType; directoryEntityCount?: number | null; folderId?: string; } /** * @internal */ interface DataFabricRoleGetAllOptions { /** * Include role statistics in the response. * * Defaults to true to match the Data Fabric UI and CLI role-list flow. */ stats?: boolean; /** * Optional folder key for folder-aware Role V2 requests. * * Forwarded on the wire as the `X-UIPATH-FolderKey` header. */ folderKey?: string; } /** * @internal */ interface DataFabricRoleServiceModel { /** * Lists Data Fabric access roles. * * Returns tenant Data Fabric roles such as Admin, Designer, DataWriter, and * DataReader. Role IDs from this method can be passed to * `DataFabricDirectoryService.assignRoles()`. * * @param options - Optional query options * @returns Promise resolving to an array of {@link DataFabricRole} * * @example * ```typescript * import { DataFabricRoleService } from '@uipath/uipath-typescript/entities'; * * const roles = new DataFabricRoleService(sdk); * const allRoles = await roles.getAll(); * const dataWriter = allRoles.find(role => role.name === 'DataWriter'); * ``` * * @example * ```typescript * const rolesWithoutStats = await roles.getAll({ stats: false }); * ``` * * @example * ```typescript * const folderRoles = await roles.getAll({ folderKey: '' }); * ``` * * @internal */ getAll(options?: DataFabricRoleGetAllOptions): Promise; } /** * @internal */ declare class DataFabricRoleService extends BaseService implements DataFabricRoleServiceModel { getAll(options?: DataFabricRoleGetAllOptions): Promise; } /** * @internal */ declare enum DataFabricDirectoryEntityType { /** Identity user, robot user, or directory robot principal. */ User = 0, /** Identity group principal. */ Group = 1, /** External application principal. */ Application = 2 } /** * @internal */ declare enum DataFabricDirectoryEntityTypeName { User = "User", Group = "Group", Application = "Application" } /** * @internal */ type DataFabricDirectoryEntityTypeInput = DataFabricDirectoryEntityType | DataFabricDirectoryEntityTypeName; /** * @internal */ interface DataFabricDirectoryRole { id: string; name: string; } /** * @internal */ interface DataFabricDirectoryEntry { externalId: string; name: string; email?: string | null; type: DataFabricDirectoryEntityTypeName; roles: DataFabricDirectoryRole[]; objectType?: string | null; isUIEnabled: boolean; } /** * @internal */ interface DataFabricDirectoryListOptions { skip?: number; top?: number; } /** * @internal */ interface DataFabricDirectoryGetAllOptions { pageSize?: number; } /** * @internal */ interface DataFabricDirectoryListResponse { totalCount: number; results: DataFabricDirectoryEntry[]; } /** * @internal */ interface DataFabricDirectoryAssignOptions { /** * Preserve the principal's current Data Fabric roles. * * Defaults to true because the Data Fabric role assignment endpoint replaces * the role set for each principal. */ preserveExisting?: boolean; /** * Enables Data Fabric UI access for the assigned principal. * * Defaults to true. */ uiEnabled?: boolean; } /** * @internal */ interface DataFabricDirectoryAssignmentResult { principalId: string; roleIds: string[]; } /** * @internal */ interface DataFabricDirectoryServiceModel { /** * Lists one page of Data Fabric directory principals and their current roles. * * Returns directory entries with external IDs, principal metadata, and * assigned Data Fabric roles. * * @param options - Optional offset paging options * @returns Promise resolving to {@link DataFabricDirectoryListResponse} * * @example * ```typescript * import { DataFabricDirectoryService } from '@uipath/uipath-typescript/entities'; * * const directory = new DataFabricDirectoryService(sdk); * const page = await directory.list({ skip: 0, top: 50 }); * const firstPrincipal = page.results[0]; * ``` * * @internal */ list(options?: DataFabricDirectoryListOptions): Promise; /** * Lists all Data Fabric directory principals and their current roles. * * Follows the Data Fabric directory top/skip pagination and returns * normalized entries. Entries without assigned roles include an empty * `roles` array. * * @param options - Optional page-size options * @returns Promise resolving to an array of {@link DataFabricDirectoryEntry} * * @example * ```typescript * import { DataFabricDirectoryService } from '@uipath/uipath-typescript/entities'; * * const directory = new DataFabricDirectoryService(sdk); * const principals = await directory.getAll({ pageSize: 100 }); * ``` * * @internal */ getAll(options?: DataFabricDirectoryGetAllOptions): Promise; /** * Assigns Data Fabric roles to one or more principals. * * The Data Fabric API replaces the role set for each principal, so this * method preserves existing roles by default and posts the union of current * and requested role IDs. * * Role IDs can be discovered with `DataFabricRoleService.getAll()`. Set * `preserveExisting: false` only when intentionally replacing a principal's * Data Fabric role set. * * @param principalIds - Principal external ID or IDs * @param principalType - Principal type * @param roleIds - Data Fabric role IDs to assign * @param options - Optional assignment behavior * @returns Promise resolving to an array of {@link DataFabricDirectoryAssignmentResult} * * @example * ```typescript * import { DataFabricDirectoryEntityTypeName, DataFabricDirectoryService, DataFabricRoleService } from '@uipath/uipath-typescript/entities'; * * const roles = new DataFabricRoleService(sdk); * const directory = new DataFabricDirectoryService(sdk); * * const dataWriter = (await roles.getAll()).find(role => role.name === 'DataWriter'); * if (!dataWriter) { * throw new Error('DataWriter role not found'); * } * * await directory.assignRoles('', DataFabricDirectoryEntityTypeName.Group, [dataWriter.id]); * ``` * * @example * ```typescript * await directory.assignRoles('', DataFabricDirectoryEntityTypeName.User, [''], { * preserveExisting: false, * }); * ``` * * @internal */ assignRoles(principalIds: string | string[], principalType: DataFabricDirectoryEntityTypeInput, roleIds: string[], options?: DataFabricDirectoryAssignOptions): Promise; /** * Revokes all direct Data Fabric roles from one or more principals. * * The Data Fabric API removes all role assignments for each supplied external * ID. Use this when a principal should no longer have direct Data Fabric * access. Inherited access through groups is not changed. * * @param principalIds - Principal external ID or IDs * @returns Promise resolving when the roles are revoked * * @example * ```typescript * import { DataFabricDirectoryService } from '@uipath/uipath-typescript/entities'; * * const directory = new DataFabricDirectoryService(sdk); * * await directory.revokeRoles(''); * ``` * * @example * ```typescript * await directory.revokeRoles([ * '', * '', * ]); * ``` * * @internal */ revokeRoles(principalIds: string | string[]): Promise; } /** * @internal */ declare class DataFabricDirectoryService extends BaseService implements DataFabricDirectoryServiceModel { private fetchAllEntries; list(options?: DataFabricDirectoryListOptions): Promise; getAll(options?: DataFabricDirectoryGetAllOptions): Promise; assignRoles(principalIds: string | string[], principalType: DataFabricDirectoryEntityTypeInput, roleIds: string[], options?: DataFabricDirectoryAssignOptions): Promise; revokeRoles(principalIds: string | string[]): Promise; } /** * Insights Types * Shared types for Maestro insights analytics endpoints */ /** * Optional filters for Insights "top" endpoint queries. * All fields are optional — pass any combination to narrow results. */ interface TopQueryOptions { /** Filter by package identifier */ packageId?: string; /** Filter by process key */ processKey?: string; /** Filter by package version */ version?: string; } /** * Common fields returned by all Insights "top" endpoints */ interface GetTopBaseResponse { /** The package identifier */ packageId: string; /** The unique process key */ processKey: string; } /** * Response for the top run count Insights endpoint */ interface GetTopRunCountResponse extends GetTopBaseResponse { /** Number of times the process was run in the given time range */ runCount: number; } /** * Response for the top failure count Insights endpoint */ interface GetTopFaultedCountResponse extends GetTopBaseResponse { /** Number of faulted instances in the given time range */ faultedCount: number; } /** * SDK response for top elements with failure. * Shared by both MaestroProcesses and Cases — no service-specific enrichment. */ interface ElementGetTopFailedCountResponse { /** BPMN element name (falls back to element ID if name is empty) */ elementName: string; /** BPMN element type (e.g. ServiceTask, ReceiveTask, IntermediateCatchEvent) */ elementType: string; /** The unique process key this element belongs to */ processKey: string; /** Number of failed executions of this element in the given time range */ failedCount: number; } /** * Time bucketing granularity for insights time-series queries. * * Controls how data points are grouped on the time axis. */ declare enum TimeInterval { /** Group data points by hour */ Hour = "HOUR", /** Group data points by day */ Day = "DAY", /** Group data points by week */ Week = "WEEK" } /** * Options for insights time-series queries. */ interface TimelineOptions { /** * How to group data points on the time axis. * @default TimeInterval.Day */ groupBy?: TimeInterval; /** Filter by package identifier */ packageId?: string; /** Filter by package version */ version?: string; /** Filter by one or more process keys. Pass `['']` for a single process. */ processKeys?: string[]; } /** * Final instance statuses returned by the instance status timeline endpoint. * * Only includes statuses where the instance has finished execution — Completed, Faulted, or Cancelled. * Active statuses like Running or Paused are not included. */ declare enum InstanceFinalStatus { /** Instance completed successfully */ Completed = "Completed", /** Instance encountered an error */ Faulted = "Faulted", /** Instance was cancelled */ Cancelled = "Cancelled" } /** * Instance count for a process with a given status * within a specific time bucket. */ interface InstanceStatusTimelineResponse { /** Start of the time bucket in local timezone (e.g. `"5/8/2026 12:00:00 AM"`) */ startTime: string; /** Instance status */ status: InstanceFinalStatus; /** Number of instances with this status in the time bucket */ count: number; } /** * Incident count within a specific time bucket. */ interface IncidentTimelineResponse { /** Start of the time bucket in local timezone (ISO 8601, e.g. `"2026-05-04T00:00:00"`) */ startTime: string; /** End of the time bucket in local timezone (ISO 8601, e.g. `"2026-05-11T00:00:00"`) */ endTime: string; /** Number of incidents that occurred within this time bucket */ count: number; } /** * Response for the top duration Insights endpoint */ interface GetTopDurationResponse extends GetTopBaseResponse { /** Total execution duration in milliseconds */ duration: number; } /** * Duration percentile stats shared by Insights aggregate endpoints (per-element and per-process/case). * * For instance-level stats, durations are computed over terminal instances only * (Completed, Cancelled, Deleted) and default to `0` when no terminal instances exist. */ interface DurationStats { /** Minimum duration in milliseconds */ minDurationMs: number; /** Maximum duration in milliseconds */ maxDurationMs: number; /** Average duration in milliseconds */ avgDurationMs: number; /** 50th percentile (median) duration in milliseconds */ p50DurationMs: number; /** 95th percentile duration in milliseconds */ p95DurationMs: number; /** 99th percentile duration in milliseconds */ p99DurationMs: number; } /** * Instance count and duration stats aggregated by status for a process or case within a time range. * * Duration fields are computed over terminal instances only (Completed, Cancelled, Deleted) * and default to `0` when no terminal instances exist in the time range. */ interface InstanceStats extends DurationStats { /** Total number of instances across all statuses */ totalCount: number; /** Number of currently running instances */ runningCount: number; /** Number of instances in transitioning state */ transitioningCount: number; /** Number of paused instances */ pausedCount: number; /** Number of faulted instances */ faultedCount: number; /** Number of completed instances */ completedCount: number; /** Number of cancelled instances */ cancelledCount: number; /** Number of deleted instances */ deletedCount: number; } /** * Required request parameters for process-scoped insights stats endpoints * (`getElementStats`, `getInstanceStats`). * * Identifies a single process+package+version and the time range to aggregate over. */ interface MaestroProcessStatsRequest { /** Process key to filter by */ processKey: string; /** Package identifier */ packageId: string; /** Package version to filter by */ packageVersion: string; /** Start of the time range to query */ startTime: Date; /** End of the time range to query */ endTime: Date; } /** * Per-element execution counts and duration percentiles for a BPMN element within a process or case. */ interface ElementStats extends DurationStats { /** BPMN element identifier */ elementId: string; /** Number of successful executions */ successCount: number; /** Number of failed executions */ failCount: number; /** Number of terminated executions */ terminatedCount: number; /** Number of paused executions */ pausedCount: number; /** Number of in-progress executions */ inProgressCount: number; } /** * Maestro Process Types * Types and interfaces for Maestro process management */ /** * Optional filters for {@link MaestroProcessesServiceModel.getAll}. * All fields are optional — pass any combination to narrow the returned processes. */ interface MaestroProcessGetAllOptions { /** Filter by process key */ processKey?: string; /** Filter by package identifier */ packageId?: string; /** Only include processes with instances started at or after this time */ startTime?: Date; /** Only include processes with instances started at or before this time */ endTime?: Date; } /** * Process information with instance statistics */ interface RawMaestroProcessGetAllResponse { /** Unique key identifying the process */ processKey: string; /** Package identifier */ packageId: string; /** Process name */ name: string; /** Folder key where process is located */ folderKey: string; /** Folder name */ folderName: string; /** Available package versions */ packageVersions: string[]; /** Total number of versions */ versionCount: number; /** Process instance count - pending */ pendingCount: number; /** Process instance count - running */ runningCount: number; /** Process instance count - completed */ completedCount: number; /** Process instance count - paused */ pausedCount: number; /** Process instance count - cancelled */ cancelledCount: number; /** Process instance count - faulted */ faultedCount: number; /** Process instance count - retrying */ retryingCount: number; /** Process instance count - resuming */ resumingCount: number; /** Process instance count - pausing */ pausingCount: number; /** Process instance count - canceling */ cancelingCount: number; } /** * Response for a single entry in top processes by run count */ interface ProcessGetTopRunCountResponse extends GetTopRunCountResponse { /** Human-readable process name */ name: string; } /** * Response for a single entry in top processes by failure count */ interface ProcessGetTopFaultedCountResponse extends GetTopFaultedCountResponse { /** Human-readable process name */ name: string; } /** * Response for a single entry in top processes by duration */ interface ProcessGetTopDurationResponse extends GetTopDurationResponse { /** Human-readable process name */ name: string; } /** * Process Incident Status */ declare enum ProcessIncidentStatus { Open = "Open", Closed = "Closed" } /** * Process Incident Type */ declare enum ProcessIncidentType { System = "System", User = "User", Deployment = "Deployment" } /** * Process Incident Severity */ declare enum ProcessIncidentSeverity { Error = "Error", Warning = "Warning" } /** * Process Incident Debug Mode */ declare enum DebugMode { None = "None", Default = "Default", StepByStep = "StepByStep", SingleStep = "SingleStep" } /** * Process Incident Get Response */ interface ProcessIncidentGetResponse { instanceId: string; elementId: string; folderKey: string; processKey: string; incidentId: string; incidentStatus: ProcessIncidentStatus; incidentType: ProcessIncidentType | null; errorCode: string; errorMessage: string; errorTime: string; errorDetails: string; debugMode: DebugMode; incidentSeverity: ProcessIncidentSeverity | null; incidentElementActivityType: string; incidentElementActivityName: string; } /** * Process Incident Summary Get Response */ interface ProcessIncidentGetAllResponse { count: number; errorMessage: string; errorCode: string; firstOccuranceTime: string; processKey: string; } /** * Maestro Process Models * Model classes for Maestro processes */ /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { MaestroProcesses } from '@uipath/uipath-typescript/maestro-processes'; * * const maestroProcesses = new MaestroProcesses(sdk); * const allProcesses = await maestroProcesses.getAll(); * ``` */ interface MaestroProcessesServiceModel { /** * Get all processes with their instance statistics. * * Returns every Maestro process with aggregated instance counts by status. Pass `options` * to narrow the results by process key, package, or the time range their instances started in. * * @param options - Optional filters (processKey, packageId, startTime, endTime) * @returns Promise resolving to array of MaestroProcess objects with methods * {@link MaestroProcessGetAllResponse} * @example * ```typescript * // 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}`); * } * ``` * * @example * ```typescript * // Filter by package and the time range instances started in * const filtered = await maestroProcesses.getAll({ * packageId: '', * startTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), * endTime: new Date(), * }); * ``` */ getAll(options?: MaestroProcessGetAllOptions): Promise; /** * Get incidents for a specific process * * @param processKey The key of the process to get incidents for * @param folderKey The folder key for authorization * @returns Promise resolving to array of incidents for the process * {@link ProcessIncidentGetResponse} * @example * ```typescript * // 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}`); * } * ``` */ getIncidents(processKey: string, folderKey: string): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link ProcessGetTopRunCountResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopRunCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link ProcessGetTopFaultedCountResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopFaultedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link ElementGetTopFailedCountResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopElementFailedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity * @returns Promise resolving to an array of {@link InstanceStatusTimelineResponse} * * @example * ```typescript * // 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}`); * } * ``` * * @example * ```typescript * import { TimeInterval } from '@uipath/uipath-typescript/maestro-processes'; * * // Get hourly breakdown * const statuses = await maestroProcesses.getInstanceStatusTimeline(startTime, endTime, { * groupBy: TimeInterval.Hour, * }); * ``` * * @example * ```typescript * // Filter to a specific process * const filtered = await maestroProcesses.getInstanceStatusTimeline(startTime, endTime, { * processKeys: [''], * }); * ``` * * @example * ```typescript * // Get all-time data (from Unix epoch to now) * const allTime = await maestroProcesses.getInstanceStatusTimeline(new Date(0), new Date()); * ``` */ getInstanceStatusTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity * @returns Promise resolving to an array of {@link IncidentTimelineResponse} * * @example * ```typescript * // 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`); * } * ``` * * @example * ```typescript * import { TimeInterval } from '@uipath/uipath-typescript/maestro-processes'; * * // Get weekly breakdown * const incidents = await maestroProcesses.getIncidentsTimeline(startTime, endTime, { * groupBy: TimeInterval.Week, * }); * ``` * * @example * ```typescript * // Filter to a specific process * const filtered = await maestroProcesses.getIncidentsTimeline(startTime, endTime, { * processKeys: [''], * }); * ``` */ getIncidentsTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link ProcessGetTopDurationResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopExecutionDuration(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param request - Process scope + time range to aggregate over * @returns Promise resolving to an array of {@link ElementStats} * @example * ```typescript * // 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] * ); * ``` */ getElementStats(request: MaestroProcessStatsRequest): Promise; /** * 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. * * @param request - Process scope + time range to aggregate over * @returns Promise resolving to {@link InstanceStats} * @example * ```typescript * // 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] * ); * ``` */ getInstanceStats(request: MaestroProcessStatsRequest): Promise; } interface ProcessMethods { /** * Gets incidents for this process * * @returns Promise resolving to array of process incidents */ getIncidents(): Promise; /** * Get element stats for this process * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param packageVersion - Package version to filter by * @returns Promise resolving to an array of {@link ElementStats} */ getElementStats(startTime: Date, endTime: Date, packageVersion: string): Promise; /** * Get instance stats for this process * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param packageVersion - Package version to filter by * @returns Promise resolving to {@link InstanceStats} */ getInstanceStats(startTime: Date, endTime: Date, packageVersion: string): Promise; /** * Get instance status counts aggregated by date for this process. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity (processKey is auto-captured from this process) * @returns Promise resolving to an array of {@link InstanceStatusTimelineResponse} */ getInstanceStatusTimeline(startTime: Date, endTime: Date, options?: Omit): Promise; /** * Get incident counts aggregated by time bucket for this process. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity (processKey is auto-captured from this process) * @returns Promise resolving to an array of {@link IncidentTimelineResponse} */ getIncidentsTimeline(startTime: Date, endTime: Date, options?: Omit): Promise; } type MaestroProcessGetAllResponse = RawMaestroProcessGetAllResponse & ProcessMethods; /** * Creates an actionable process by combining API process data with operational methods. * * @param processData - The process data from API * @param service - The process service instance * @returns A process object with added methods */ declare function createProcessWithMethods(processData: MaestroProcessGetAllResponse, service: MaestroProcessesServiceModel): MaestroProcessGetAllResponse; /** * Constants used throughout the pagination system */ /** Maximum number of items that can be requested in a single page */ declare const MAX_PAGE_SIZE = 1000; /** Default page size when jumpToPage is used without specifying pageSize */ declare const DEFAULT_PAGE_SIZE = 50; /** Default field name for items in a paginated response */ declare const DEFAULT_ITEMS_FIELD = "value"; /** Default field name for total count in a paginated response */ declare const DEFAULT_TOTAL_COUNT_FIELD = "@odata.count"; /** * Limits the page size to the maximum allowed value * @param pageSize - Requested page size * @returns Limited page size value */ declare function getLimitedPageSize(pageSize?: number): number; /** * Process Instance Types * Types and interfaces for Maestro process instance management */ /** * Response for getting a single process instance */ interface RawProcessInstanceGetResponse { instanceId: string; packageKey: string; packageId: string; packageVersion: string; latestRunId: string; latestRunStatus: string; processKey: string; folderKey: string; userId: number; instanceDisplayName: string; startedByUser: string; source: string; creatorUserKey: string; startedTime: string; completedTime: string | null; instanceRuns: ProcessInstanceRun[]; } /** * Query options for getting process instances */ interface ProcessInstanceGetAllOptions { packageId?: string; packageVersion?: string; processKey?: string; errorCode?: string; } /** * Query options for getting process instances with pagination support */ type ProcessInstanceGetAllWithPaginationOptions = ProcessInstanceGetAllOptions & PaginationOptions; /** * Request for process instance operations (cancel, pause, resume) */ interface ProcessInstanceOperationOptions { comment?: string; } /** * Response from PIMS operations (cancel, pause, resume) */ interface ProcessInstanceOperationResponse { instanceId: string; status: string; } /** * Response for process instance execution history */ interface ProcessInstanceExecutionHistoryResponse { id: string; traceId: string; parentId: string | null; name: string; startedTime: string; endTime: string | null; attributes: string | null; updatedTime: string; expiredTime: string | null; } /** * Process Instance run */ interface ProcessInstanceRun { runId: string; status: string; startedTime: string; completedTime: string; } type BpmnXmlString = string; /** * Process Instance element metadata */ interface ElementMetaData { elementId: string; elementRunId: string; isMarker: boolean; inputs: Record; inputDefinitions: Record; outputs: Record; } /** * Process Instance global variable metadata */ interface GlobalVariableMetaData { id: string; name: string; /** * Common values: "integer", "string", "boolean" * May also contain custom types or "any" when type cannot be determined */ type: string; elementId: string; /** Name of the BPMN node/element */ source: string; value: any; } /** * Response for getting global variables for process instance */ interface ProcessInstanceGetVariablesResponse { elements: ElementMetaData[]; globalVariables: GlobalVariableMetaData[]; instanceId: string; parentElementId: string | null; } /** * Options for getting global variables */ interface ProcessInstanceGetVariablesOptions { parentElementId?: string; } interface CollectionResponse { value: T[]; } /** * Standardized result interface for all operation methods (pause, cancel, complete, update, upload, etc.) * Success responses include data from the request context or API response */ interface OperationResponse { /** * Whether the operation was successful */ success: boolean; /** * Response data (can contain error details in case of failure) */ data: TData; } /** * Common enum for job state used across services */ declare enum JobState { Pending = "Pending", Running = "Running", Stopping = "Stopping", Terminating = "Terminating", Faulted = "Faulted", Successful = "Successful", Stopped = "Stopped", Suspended = "Suspended", Resumed = "Resumed", Cancelled = "Cancelled", /** Server-side fallback for an unrecognized or missing job state. */ Unknown = "Unknown" } interface BaseOptions { expand?: string; select?: string; } /** * Common request options interface used across services for querying data */ interface RequestOptions extends BaseOptions { filter?: string; orderby?: string; } /** * Options that scope a name-based lookup (e.g. `getByName`) to a folder. * Provide one of `folderId`, `folderKey`, or `folderPath`. When more than * one is supplied, all are forwarded; the server applies precedence * `folderPath` > `folderKey` > `folderId`. */ interface FolderScopedOptions extends BaseOptions { /** Numeric folder ID. */ folderId?: number; /** Folder key (GUID-formatted string). */ folderKey?: string; /** Slash-delimited folder path, e.g. `'Shared/Finance'`. */ folderPath?: string; } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { ProcessInstances } from '@uipath/uipath-typescript/maestro-processes'; * * const processInstances = new ProcessInstances(sdk); * const allInstances = await processInstances.getAll(); * ``` */ interface ProcessInstancesServiceModel { /** * 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) * * @param options Query parameters for filtering instances and pagination * @returns Promise resolving to either an array of process instances NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link ProcessInstanceGetResponse} * @example * ```typescript * // 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 }); * } * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Get a process instance by ID with operation methods (cancel, pause, resume, retry) * @param id The ID of the instance to retrieve * @param folderKey The folder key for authorization * @returns Promise resolving to a process instance * {@link ProcessInstanceGetResponse} * @example * ```typescript * // Get a specific process instance * const instance = await processInstances.getById( * , * * ); * * // Access instance properties * console.log(`Status: ${instance.latestRunStatus}`); * ``` */ getById(id: string, folderKey: string): Promise; /** * Get execution history (spans) for a process instance * @param instanceId The ID of the instance to get history for * @param folderKey The folder key for authorization * @returns Promise resolving to execution history * {@link ProcessInstanceExecutionHistoryResponse} * @example * ```typescript * // 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}`); * }); * ``` */ getExecutionHistory(instanceId: string, folderKey: string): Promise; /** * Get BPMN XML file for a process instance * @param instanceId The ID of the instance to get BPMN for * @param folderKey The folder key for authorization * @returns Promise resolving to BPMN XML file * {@link BpmnXmlString} * @example * ```typescript * // 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'); * ``` */ getBpmn(instanceId: string, folderKey: string): Promise; /** * Cancel a process instance * @param instanceId The ID of the instance to cancel * @param folderKey The folder key for authorization * @param options Optional cancellation options with comment * @returns Promise resolving to operation result with instance data * @example * ```typescript * // 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}`); * } * ``` */ cancel(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; /** * Pause a process instance * @param instanceId The ID of the instance to pause * @param folderKey The folder key for authorization * @param options Optional pause options with comment * @returns Promise resolving to operation result with instance data */ pause(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; /** * Resume a process instance * @param instanceId The ID of the instance to resume * @param folderKey The folder key for authorization * @param options Optional resume options with comment * @returns Promise resolving to operation result with instance data */ resume(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; /** * 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. * @param instanceId The ID of the instance to retry * @param folderKey The folder key for authorization * @param options Optional retry options with comment * @returns Promise resolving to operation result with instance data * @example * ```typescript * // 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}`); * } * ``` */ retry(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; /** * Get global variables for a process instance * * @param instanceId The ID of the instance to get variables for * @param folderKey The folder key for authorization * @param options Optional options including parentElementId to filter by parent element * @returns Promise resolving to variables response with elements and globals * {@link ProcessInstanceGetVariablesResponse} * @example * ```typescript * // 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: } * ); * ``` */ getVariables(instanceId: string, folderKey: string, options?: ProcessInstanceGetVariablesOptions): Promise; /** * Get incidents for a process instance * * @param instanceId The ID of the instance to get incidents for * @param folderKey The folder key for authorization * @returns Promise resolving to array of incidents for the processinstance * {@link ProcessIncidentGetResponse} * @example * ```typescript * // 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}`); * } * ``` */ getIncidents(instanceId: string, folderKey: string): Promise; } interface ProcessInstanceMethods { /** * Cancels this process instance * * @param options - Optional cancellation options with comment * @returns Promise resolving to operation result */ cancel(options?: ProcessInstanceOperationOptions): Promise>; /** * Pauses this process instance * * @param options - Optional pause options with comment * @returns Promise resolving to operation result */ pause(options?: ProcessInstanceOperationOptions): Promise>; /** * Resumes this process instance * * @param options - Optional resume options with comment * @returns Promise resolving to operation result */ resume(options?: ProcessInstanceOperationOptions): Promise>; /** * Retries this faulted process instance * * @param options - Optional retry options with comment * @returns Promise resolving to operation result */ retry(options?: ProcessInstanceOperationOptions): Promise>; /** * Gets incidents for this process instance * * @returns Promise resolving to array of incidents for this instance */ getIncidents(): Promise; /** * Gets execution history (spans) for this process instance * * @returns Promise resolving to execution history */ getExecutionHistory(): Promise; /** * Gets BPMN XML file for this process instance * * @returns Promise resolving to BPMN XML file */ getBpmn(): Promise; /** * Gets global variables for this process instance * * @param options - Optional options including parentElementId to filter by parent element * @returns Promise resolving to variables response with elements and globals */ getVariables(options?: ProcessInstanceGetVariablesOptions): Promise; } type ProcessInstanceGetResponse = RawProcessInstanceGetResponse & ProcessInstanceMethods; /** * Creates an actionable process instance by combining API process instance data with operational methods. * * @param instanceData - The process instance data from API * @param service - The process instance service instance * @returns A process instance object with added methods */ declare function createProcessInstanceWithMethods(instanceData: RawProcessInstanceGetResponse, service: ProcessInstancesServiceModel): ProcessInstanceGetResponse; /** * Service for managing UiPath Maestro Process incidents * * Maestro Process incidents helps you identify, investigate, and resolve errors that occur during process execution. [UiPath Maestro Process Incidents Guide](https://docs.uipath.com/maestro/automation-cloud/latest/user-guide/all-incidents-view) */ interface ProcessIncidentsServiceModel { /** * Get all process incidents across all folders * * @returns Promise resolving to array of process incident * {@link ProcessIncidentGetAllResponse} * @example * ```typescript * import { ProcessIncidents } from '@uipath/uipath-typescript/maestro-processes'; * * const processIncidents = new ProcessIncidents(sdk); * * // Get all process incidents across all folders * const incidents = await processIncidents.getAll(); * * // Access process incident information * for (const incident of incidents) { * console.log(`Process: ${incident.processKey}`); * console.log(`Error: ${incident.errorMessage}`); * console.log(`Count: ${incident.count}`); * console.log(`First occurrence: ${incident.firstOccuranceTime}`); * } * ``` */ getAll(): Promise; } /** * Maestro Cases Types * Types and interfaces for Maestro case management */ /** * Optional filters for {@link CasesServiceModel.getAll}. * All fields are optional — pass any combination to narrow the returned case processes. */ interface CaseGetAllOptions { /** Filter by case process key */ processKey?: string; /** Filter by package identifier */ packageId?: string; /** Only include case processes with instances started at or after this time */ startTime?: Date; /** Only include case processes with instances started at or before this time */ endTime?: Date; } /** * Case information with instance statistics */ interface CaseGetAllResponse { /** Unique key identifying the case process */ processKey: string; /** Package identifier */ packageId: string; /** Case name */ name: string; /** Folder key of the folder where case process is located */ folderKey: string; /** Name of the folder where case process is located */ folderName: string; /** Available package versions */ packageVersions: string[]; /** Total number of versions */ versionCount: number; /** Case instance count - pending */ pendingCount: number; /** Case instance count - running */ runningCount: number; /** Case instance count - completed */ completedCount: number; /** Case instance count - paused */ pausedCount: number; /** Case instance count - cancelled */ cancelledCount: number; /** Case instance count - faulted */ faultedCount: number; /** Case instance count - retrying */ retryingCount: number; /** Case instance count - resuming */ resumingCount: number; /** Case instance count - pausing */ pausingCount: number; /** Case instance count - canceling */ cancelingCount: number; } /** * Response for a single entry in top cases by run count */ interface CaseGetTopRunCountResponse extends GetTopRunCountResponse { /** Human-readable case name */ name: string; } /** * Response for a single entry in top cases by failure count */ interface CaseGetTopFaultedCountResponse extends GetTopFaultedCountResponse { /** Human-readable case name */ name: string; } /** * Response for a single entry in top cases by duration */ interface CaseGetTopDurationResponse extends GetTopDurationResponse { /** Human-readable case name */ name: string; } /** * Maestro Cases Models * Model classes for Maestro cases */ /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Cases } from '@uipath/uipath-typescript/cases'; * * const cases = new Cases(sdk); * const allCases = await cases.getAll(); * ``` */ interface CasesServiceModel { /** * Get all case management processes with their instance statistics. * * Returns every case process with aggregated instance counts by status. Pass `options` * to narrow the results by process key, package, or the time range their instances started in. * * @param options - Optional filters (processKey, packageId, startTime, endTime) * @returns Promise resolving to an array of {@link CaseGetAllWithMethodsResponse} * @example * ```typescript * // 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}`); * } * ``` * * @example * ```typescript * // Filter by package and the time range instances started in * const filtered = await cases.getAll({ * packageId: '', * startTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), * endTime: new Date(), * }); * ``` */ getAll(options?: CaseGetAllOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link CaseGetTopRunCountResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopRunCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link CaseGetTopFaultedCountResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopFaultedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link ElementGetTopFailedCountResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopElementFailedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity * @returns Promise resolving to an array of {@link InstanceStatusTimelineResponse} * * @example * ```typescript * // 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}`); * } * ``` * * @example * ```typescript * import { TimeInterval } from '@uipath/uipath-typescript/cases'; * * // Get weekly breakdown * const statuses = await cases.getInstanceStatusTimeline(startTime, endTime, { * groupBy: TimeInterval.Week, * }); * ``` * * @example * ```typescript * // Filter to a specific case process * const filtered = await cases.getInstanceStatusTimeline(startTime, endTime, { * processKeys: [''], * }); * ``` * * @example * ```typescript * // Get all-time data (from Unix epoch to now) * const allTime = await cases.getInstanceStatusTimeline(new Date(0), new Date()); * ``` */ getInstanceStatusTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity * @returns Promise resolving to an array of {@link IncidentTimelineResponse} * * @example * ```typescript * // 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`); * } * ``` * * @example * ```typescript * import { TimeInterval } from '@uipath/uipath-typescript/cases'; * * // Get weekly breakdown * const incidents = await cases.getIncidentsTimeline(startTime, endTime, { * groupBy: TimeInterval.Week, * }); * ``` * * @example * ```typescript * // Filter to a specific case process * const filtered = await cases.getIncidentsTimeline(startTime, endTime, { * processKeys: [''], * }); * ``` */ getIncidentsTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; /** * 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. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional filters (packageId, processKey, version) * @returns Promise resolving to an array of {@link CaseGetTopDurationResponse} * @example * ```typescript * 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`); * } * ``` * * @example * ```typescript * // 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: '' } * ); * ``` */ getTopExecutionDuration(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; /** * 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. * * @param request - Process scope + time range to aggregate over * @returns Promise resolving to an array of {@link ElementStats} * @example * ```typescript * // 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] * ); * ``` */ getElementStats(request: MaestroProcessStatsRequest): Promise; /** * 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. * * @param request - Process scope + time range to aggregate over * @returns Promise resolving to {@link InstanceStats} * @example * ```typescript * // 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] * ); * ``` */ getInstanceStats(request: MaestroProcessStatsRequest): Promise; } interface CaseMethods { /** * Get element stats for this case * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param packageVersion - Package version to filter by * @returns Promise resolving to an array of {@link ElementStats} */ getElementStats(startTime: Date, endTime: Date, packageVersion: string): Promise; /** * Get instance stats for this case * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param packageVersion - Package version to filter by * @returns Promise resolving to {@link InstanceStats} */ getInstanceStats(startTime: Date, endTime: Date, packageVersion: string): Promise; /** * Get instance status counts aggregated by date for this case process. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity (processKey is auto-captured from this case) * @returns Promise resolving to an array of {@link InstanceStatusTimelineResponse} */ getInstanceStatusTimeline(startTime: Date, endTime: Date, options?: Omit): Promise; /** * Get incident counts aggregated by time bucket for this case process. * * @param startTime - Start of the time range to query * @param endTime - End of the time range to query * @param options - Optional settings for filtering and time bucket granularity (processKey is auto-captured from this case) * @returns Promise resolving to an array of {@link IncidentTimelineResponse} */ getIncidentsTimeline(startTime: Date, endTime: Date, options?: Omit): Promise; } type CaseGetAllWithMethodsResponse = CaseGetAllResponse & CaseMethods; /** * Creates an actionable case by combining API case data with operational methods. * * @param caseData - The case data from API * @param service - The cases service instance * @returns A case object with added methods */ declare function createCaseWithMethods(caseData: CaseGetAllResponse, service: CasesServiceModel): CaseGetAllWithMethodsResponse; /** * Case Instance Types * Types and interfaces for Maestro case instance management */ /** * Response for getting a single case instance */ interface RawCaseInstanceGetResponse { instanceId: string; packageKey: string; packageId: string; packageVersion: string; latestRunId: string; latestRunStatus: string; processKey: string; folderKey: string; userId: number; instanceDisplayName: string; startedByUser: string; source: string; creatorUserKey: string; startedTime: string; completedTime: string; instanceRuns: CaseInstanceRun[]; caseAppConfig?: CaseAppConfig; caseType?: string; caseTitle?: string; } /** * Case instance run information */ interface CaseInstanceRun { runId: string; status: string; startedTime: string; completedTime: string; } /** * Query options for getting case instances */ interface CaseInstanceGetAllOptions { packageId?: string; packageVersion?: string; processKey?: string; errorCode?: string; } /** * Query options for getting case instances with pagination support */ type CaseInstanceGetAllWithPaginationOptions = CaseInstanceGetAllOptions & PaginationOptions; /** * Request for case instance operations (close, pause, resume) */ interface CaseInstanceOperationOptions { comment?: string; } /** * Response for case instance operations (close, pause, resume) */ interface CaseInstanceOperationResponse { instanceId: string; status: string; } /** * Options for reopening a case instance. */ interface CaseInstanceReopenOptions extends CaseInstanceOperationOptions { /** * The stage ID from which the case instance should be reopened. */ stageId: string; } /** * Well-known message names understood by running case instances. */ declare enum CaseInstanceMessageName { /** Selects the next stage when the case instance is waiting for a user to choose one */ UserSelectStage = "UserSelectStage", /** Starts a manually-triggered (ad-hoc) case task */ UserAdhocTrigger = "UserAdhocTrigger" } /** * Options for sending a message to a case instance. */ interface CaseInstanceSendMessageOptions { /** * Data payload delivered with the message — e.g. `{ stageName: 'Review' }` for * `UserSelectStage`, or `{ taskNames: ['Approve Invoice'] }` for `UserAdhocTrigger`. */ itemData?: Record; /** * Message reference identifying the target wait point. Defaults to the case * instance itself, which is correct for most messages. */ reference?: string; } /** * Case App Configuration Overview */ interface CaseAppOverview { title: string; details: string; } /** * Case App Configuration from case JSON */ interface CaseAppConfig { caseSummary?: string; overview?: CaseAppOverview[]; } /** * SLA status for a case instance */ declare enum SlaSummaryStatus { /** Case is within SLA deadline */ ON_TRACK = "On Track", /** Case is approaching SLA deadline based on at-risk percentage threshold */ AT_RISK = "At Risk", /** Case has exceeded SLA deadline */ OVERDUE = "Overdue", /** Case instance has completed */ COMPLETED = "Completed", /** SLA status cannot be determined (no SLA deadline defined) */ UNKNOWN = "Unknown" } /** * Instance status values for case instances and process instances */ declare enum InstanceStatus { /** Instance status not yet populated by the backend */ UNKNOWN = "", CANCELLED = "Cancelled", CANCELING = "Canceling", COMPLETED = "Completed", FAULTED = "Faulted", PAUSED = "Paused", PAUSING = "Pausing", PENDING = "Pending", RESUMING = "Resuming", RETRYING = "Retrying", RUNNING = "Running", UPGRADING = "Upgrading" } /** * SLA summary response for a single case instance */ interface SlaSummaryResponse { /** Unique identifier of the case instance */ caseInstanceId: string; /** Folder key that the case instance belongs to */ folderKey: string; /** Display name of the SLA rule */ name: string; /** Human-readable reference number for a case instance */ externalId: string; /** Summary text for the case instance — may be empty */ caseSummary: string; /** Unique key of the process associated with the case instance */ processKey: string; /** SLA deadline timestamp in UTC (ISO 8601 format) */ slaDueTime: string; /** Current SLA status indicating whether the deadline is met, at risk, or breached */ slaStatus: SlaSummaryStatus; /** Index of the escalation rule currently applied to the SLA */ escalationRuleIndex: string; escalationRuleType: EscalationTriggerType; /** Current status of the case instance */ instanceStatus: InstanceStatus; /** Last modification timestamp in UTC (ISO 8601 format) */ lastModifiedTime: string; } /** * Options for querying SLA summary */ type CaseInstanceSlaSummaryOptions = PaginationOptions & { /** Filter to a specific case instance */ caseInstanceId?: string; /** Filter by event start time in UTC */ startTimeUtc?: Date; /** Filter by event end time in UTC */ endTimeUtc?: Date; }; /** * Stage SLA summary for a single stage within a case instance (from Insights RTM) */ interface CaseInstanceStageSLAStage { /** Stage element identifier */ elementId: string; /** Stage display name */ name: string; /** Current execution status of the stage */ latestStatus: string; /** SLA deadline timestamp in UTC (e.g. `"9/17/2025 8:35:38 PM"`) or empty string if no SLA is configured */ slaDueTime: string; /** SLA status for this stage */ slaStatus: SlaSummaryStatus; /** Index of the current escalation rule */ escalationRuleIndex: string; /** Type of the current escalation rule */ escalationRuleType: EscalationTriggerType; } /** * Stages SLA summary for a single case instance (from Insights RTM) */ interface CaseInstanceStageSLAResponse { /** Case instance identifier */ caseInstanceId: string; /** Stages within this case instance */ stages: CaseInstanceStageSLAStage[]; } /** * Options for querying stages SLA summary */ interface CaseInstanceStageSLAOptions { /** Filter to a specific case instance */ caseInstanceId?: string; } /** * Case stage task type */ declare enum StageTaskType { EXTERNAL_AGENT = "external-agent", RPA = "rpa", AGENTIC_PROCESS = "process", AGENT = "agent", ACTION = "action", API_WORKFLOW = "api-workflow" } /** * Stage task information */ interface StageTask { id: string; name: string; completedTime: string; startedTime: string; status: string; type: StageTaskType; } /** * Escalation recipient scope */ declare enum EscalationRecipientScope { USER = "user", USER_GROUP = "usergroup" } /** * Escalation rule recipient information */ interface EscalationRecipient { /** Type of recipient (user or usergroup) */ scope: EscalationRecipientScope; /** Identifier for a user/usergroup */ target: string; /** The email id of the user/usergroup */ value: string; } /** * Escalation action type */ declare enum EscalationActionType { NOTIFICATION = "notification" } /** * Escalation rule action configuration */ interface EscalationAction { type: EscalationActionType; recipients: EscalationRecipient[]; } /** * Escalation rule trigger type */ declare enum EscalationTriggerType { SLA_BREACHED = "sla-breached", AT_RISK = "at-risk", /** Default value when no escalation rule is defined */ NONE = "None" } /** * Escalation rule trigger metadata */ interface EscalationTriggerMetadata { type?: EscalationTriggerType; atRiskPercentage?: number; } /** * Escalation rule configuration */ interface EscalationRule { triggerInfo: EscalationTriggerMetadata; action?: EscalationAction; } /** * SLA duration unit */ declare enum SLADurationUnit { HOURS = "h", DAYS = "d", WEEKS = "w", MONTHS = "m" } /** * SLA configuration for stages */ interface StageSLA { length?: number; duration?: SLADurationUnit; escalationRule?: EscalationRule[]; } /** * Stage information from case instances */ interface CaseGetStageResponse { id: string; name: string; sla?: StageSLA; status: string; tasks: StageTask[][]; } /** * Case element execution metadata */ interface ElementExecutionMetadata { completedTime: string | null; elementId: string; elementName: string; parentElementId: string | null; startedTime: string; /** Element status (e.g., "Completed", "Faulted", "Running") */ status: string; processKey: string; /** External reference link, eg link to the HITL task in Action Center */ externalLink: string; /** List of element runs for the element */ elementRuns: ElementRunMetadata[]; } /** * Response for getting case instance element executions */ interface CaseInstanceExecutionHistoryResponse { creationUserKey: string | null; folderKey: string; instanceDisplayName: string; instanceId: string; packageId: string; packageKey: string; packageVersion: string; processKey: string; source: string; /** Element status (e.g., "Completed", "Faulted", "Running", "Pausing", "Canceling") */ status: string; startedTime: string; completedTime: string | null; elementExecutions: ElementExecutionMetadata[]; } /** * Element run metadata */ interface ElementRunMetadata { status: string; startedTime: string; completedTime: string | null; elementRunId: string; parentElementRunId: string | null; } declare enum TaskUserType { /** A user of this type is supposed to be used by a human. */ User = "User", /** A user of this type is automatically created when adding a robot, is associated with Robot role and it is used by a robot when communicating with Orchestrator. */ Robot = "Robot", /** A user of type Directory User */ DirectoryUser = "DirectoryUser", /** A user of type Directory Group */ DirectoryGroup = "DirectoryGroup", /** A user of type Directory Robot Account */ DirectoryRobot = "DirectoryRobot", /** A user of type Directory External Application */ DirectoryExternalApplication = "DirectoryExternalApplication" } interface UserLoginInfo { name: string; surname: string; userName: string; emailAddress: string; displayName: string; id: number; type: TaskUserType; } /** * Types of tasks available in Action Center. * Each type determines the task's behavior, UI rendering, and completion requirements. */ declare enum TaskType { /** A form-based task that renders a UiPath form layout for user input */ Form = "FormTask", /** An externally managed task handled outside of Action Center */ External = "ExternalTask", /** A task powered by a UiPath App */ App = "AppTask", /** A document validation task for reviewing and correcting extracted document data */ DocumentValidation = "DocumentValidationTask", /** A document classification task for categorizing documents */ DocumentClassification = "DocumentClassificationTask", /** A data labeling task for annotating training data */ DataLabeling = "DataLabelingTask" } declare enum TaskPriority { Low = "Low", Medium = "Medium", High = "High", Critical = "Critical" } declare enum TaskStatus { Unassigned = "Unassigned", Pending = "Pending", Completed = "Completed" } declare enum TaskSlaCriteria { TaskCreated = "TaskCreated", TaskAssigned = "TaskAssigned", TaskCompleted = "TaskCompleted" } declare enum TaskSlaStatus { OverdueLater = "OverdueLater", OverdueSoon = "OverdueSoon", Overdue = "Overdue", CompletedInTime = "CompletedInTime" } declare enum TaskSourceName { Agent = "Agent", Workflow = "Workflow", Maestro = "Maestro", Default = "Default" } interface TaskSource { sourceName: TaskSourceName; sourceId: string; taskSourceMetadata: Record; } /** * Task activity types */ declare enum TaskActivityType { Created = "Created", Assigned = "Assigned", Reassigned = "Reassigned", Unassigned = "Unassigned", Saved = "Saved", Forwarded = "Forwarded", Completed = "Completed", Commented = "Commented", Deleted = "Deleted", BulkSaved = "BulkSaved", BulkCompleted = "BulkCompleted", FirstOpened = "FirstOpened" } /** * Tag information for tasks */ interface Tag { name: string; displayName: string; displayValue: string; } /** * Task activity information */ interface TaskActivity { task?: RawTaskGetResponse; organizationUnitId: number; taskId: number; taskKey: string; activityType: TaskActivityType; creatorUserId: number; targetUserId: number | null; createdTime: string; } interface TaskSlaDetail { expiryTime?: string; startCriteria?: TaskSlaCriteria; endCriteria?: TaskSlaCriteria; status?: TaskSlaStatus; } interface TaskAssignment { assignee?: UserLoginInfo; task?: RawTaskGetResponse; id?: number; } /** * Base interface containing common fields shared across all task response types */ interface TaskBaseResponse { status: TaskStatus; title: string; type: TaskType; priority: TaskPriority; folderId: number; key: string; isDeleted: boolean; createdTime: string; id: number; action: string | null; externalTag: string | null; lastAssignedTime: string | null; completedTime: string | null; parentOperationId: string | null; deleterUserId: number | null; deletedTime: string | null; lastModifiedTime: string | null; } interface TaskCreateOptions { title: string; data?: Record; priority?: TaskPriority; } interface RawTaskCreateResponse extends TaskBaseResponse { waitJobState: JobState | null; assignedToUser: UserLoginInfo | null; taskSlaDetails: TaskSlaDetail[] | null; completedByUser: UserLoginInfo | null; taskAssignees: UserLoginInfo[] | null; processingTime: number | null; data: Record | null; } interface RawTaskGetResponse extends TaskBaseResponse { isCompleted: boolean; encrypted: boolean; bulkFormLayoutId: number | null; formLayoutId: number | null; taskSlaDetail: TaskSlaDetail | null; taskAssigneeName: string | null; lastModifierUserId: number | null; assignedToUser: UserLoginInfo | null; creatorUser?: UserLoginInfo; lastModifierUser?: UserLoginInfo; taskAssignments?: TaskAssignment[]; activities?: TaskActivity[]; tags?: Tag[]; formLayout?: Record; actionLabel?: string | null; taskSlaDetails?: TaskSlaDetail[] | null; completedByUser?: UserLoginInfo | null; taskAssignmentCriteria?: TaskAssignmentCriteria; taskAssignees?: UserLoginInfo[] | null; taskSource?: TaskSource | null; processingTime?: number | null; data?: Record | null; } /** * Defines how a task assignment is distributed. * * Defaults to {@link TaskAssignmentCriteria.SingleUser} (a direct single-user * assignment) when not specified. The group-based criteria tell Action Center * how to distribute the task across the members of a directory group. */ declare enum TaskAssignmentCriteria { /** Assigned to a single user, like a direct assignment. */ SingleUser = "SingleUser", /** Assigned to the group member with the fewest pending tasks. */ Workload = "Workload", /** Assigned to all users in the group. */ AllUsers = "AllUsers", /** Assigned in a round-robin manner across the group's members. */ RoundRobin = "RoundRobin" } /** * Options for task assignment operations when called from a task instance * Requires either userId or userNameOrEmail, but not both. Optionally accepts * an assignment criteria; defaults to a single-user assignment, set a group * criteria (e.g. {@link TaskAssignmentCriteria.AllUsers}) for a directory group. */ type TaskAssignOptions = ({ userId: number; userNameOrEmail?: never; } | { userId?: never; userNameOrEmail: string; }) & { /** * How the assignment is distributed. Optional — defaults to * {@link TaskAssignmentCriteria.SingleUser} (a direct single-user assignment). * Set a group criteria (e.g. {@link TaskAssignmentCriteria.AllUsers}) to * distribute the task across a directory group's members. */ assignmentCriteria?: TaskAssignmentCriteria; }; /** * Options for task assignment operations when called from the service * Extends TaskAssignOptions with the required taskId field */ type TaskAssignmentOptions = { taskId: number; } & TaskAssignOptions; interface TasksUnassignOptions { taskIds: number[]; } interface TaskAssignmentResponse { taskId?: number; userId?: number; errorCode?: number; errorMessage?: string; userNameOrEmail?: string; } /** * Options for completing a task */ type TaskCompleteOptions = { type: TaskType.External; data?: any; action?: string; } | { type: TaskType.DocumentValidation; data?: any; action?: string; } | { type: TaskType.DocumentClassification; data?: any; action?: string; } | { type: TaskType.DataLabeling; data?: any; action?: string; } | { type: TaskType.Form; data: any; action: string; } | { type: TaskType.App; data: any; action: string; }; /** * Options for completing a task when called from the service * Extends TaskCompleteOptions with the required taskId field */ type TaskCompletionOptions = TaskCompleteOptions & { taskId: number; }; /** * Options for getting tasks across folders */ type TaskGetAllOptions = RequestOptions & PaginationOptions & { /** * Optional folder ID to filter tasks by folder */ folderId?: number; /** * Optional flag to fetch tasks using admin permissions * When true, fetches tasks across folders * where the user has at least Task.View, Task.Edit and TaskAssignment.Create permissions * When false or omitted, fetches tasks across folders * where the user has at least Task.View and Task.Edit permissions */ asTaskAdmin?: boolean; }; /** * Query options for getting a task by ID */ interface TaskGetByIdOptions extends BaseOptions { /** * Optional task type. When not provided, method will automatically identify the * task type and resolve accordingly, but it will be slower. * When provided, it will skip the step to identify the task type, so it will be faster. */ taskType?: TaskType; } /** * Options for getting users with task permissions */ type TaskGetUsersOptions = RequestOptions & PaginationOptions; /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Tasks } from '@uipath/uipath-typescript/tasks'; * * const tasks = new Tasks(sdk); * const allTasks = await tasks.getAll(); * ``` */ interface TaskServiceModel { /** * Gets all tasks across folders with optional filtering * * @param options - Query options including optional folderId, asTaskAdmin flag and pagination options * @returns Promise resolving to either an array of tasks NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link TaskGetResponse} * @example * ```typescript * // 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 * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a task by ID * @param id - The ID of the task to retrieve * @param options - Optional query parameters including taskType for faster retrieval {@link TaskGetByIdOptions} * @param folderId - Optional folder ID (REQUIRED when options.taskType is provided) * @returns Promise resolving to the task * {@link TaskGetResponse} * @example * ```typescript * // 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 }, ); * ``` */ getById(id: number, options?: TaskGetByIdOptions, folderId?: number): Promise; /** * Creates a new task * * @param options - The task to be created * @param folderId - Required folder ID * @returns Promise resolving to the created task * {@link TaskCreateResponse} * @example * ```typescript * import { TaskPriority } from '@uipath/uipath-typescript'; * const task = await tasks.create({ * title: "My Task", * priority: TaskPriority.Medium * }, ); // folderId is required * ``` */ create(options: TaskCreateOptions, folderId: number): Promise; /** * Assigns tasks to users * * @param options - Single task assignment or array of task assignments * @returns Promise resolving to array of task assignment results * {@link TaskAssignmentResponse} * @example * ```typescript * // 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" } * ]); * ``` * * @example Group assignment * ```typescript * 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 * }); * ``` */ assign(options: TaskAssignmentOptions | TaskAssignmentOptions[]): Promise>; /** * Reassigns tasks to new users * * @param options - Single task assignment or array of task assignments * @returns Promise resolving to array of task assignment results * {@link TaskAssignmentResponse} * @example * ```typescript * // 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" } * ]); * ``` * * @example Group reassignment * ```typescript * 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 * }); * ``` */ reassign(options: TaskAssignmentOptions | TaskAssignmentOptions[]): Promise>; /** * Unassigns tasks (removes current assignees) * * @param taskId - Single task ID or array of task IDs to unassign * @returns Promise resolving to array of task assignment results * {@link TaskAssignmentResponse} * @example * ```typescript * // 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([, , ]); * ``` */ unassign(taskId: number | number[]): Promise>; /** * Completes a task with the specified type and data * * @param options - The completion options including task type, taskId, data, and action * @param folderId - Required folder ID * @returns Promise resolving to completion result * {@link TaskCompleteOptions} * @example * ```typescript * // 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 * ``` */ complete(options: TaskCompletionOptions, folderId: number): Promise>; /** * 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 * * @param folderId - The folder ID to get task users from * @param options - Optional query and pagination parameters * @returns Promise resolving to either an array of task users NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link UserLoginInfo} * @example * ```typescript * // 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); * ``` */ getUsers(folderId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; } interface TaskMethods { /** * Assigns this task to a user or users * * @param options - Assignment options (requires at least one of: userId, userNameOrEmail) * @returns Promise resolving to task assignment results */ assign(options: TaskAssignOptions): Promise>; /** * Reassigns this task to a new user * * @param options - Assignment options (requires at least one of: userId, userNameOrEmail) * @returns Promise resolving to task assignment results */ reassign(options: TaskAssignOptions): Promise>; /** * Unassigns this task (removes current assignee) * * @returns Promise resolving to task assignment results */ unassign(): Promise>; /** * Completes this task with optional data and action * * @param options - Completion options * @returns Promise resolving to completion result */ complete(options: TaskCompleteOptions): Promise>; } type TaskGetResponse = RawTaskGetResponse & TaskMethods; type TaskCreateResponse = RawTaskCreateResponse & TaskMethods; /** * Creates an actionable task by combining API task data with operational methods. * * @param taskData - The task data from API * @param service - The task service instance * @returns A task object with added methods */ declare function createTaskWithMethods(taskData: RawTaskGetResponse | RawTaskCreateResponse, service: TaskServiceModel): TaskGetResponse | TaskCreateResponse; /** * Service model for managing Maestro Case Instances * * Maestro case instances are the running instances of Maestro cases. * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * 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. */ interface CaseInstancesServiceModel { /** * Get all case instances with optional filtering and pagination * * @param options Query parameters for filtering instances and pagination * @returns Promise resolving to either an array of case instances NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link CaseInstanceGetResponse} * @example * ```typescript * // 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 }); * } * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Get a specific case instance by ID * @param instanceId - The case instance ID * @param folderKey - Required folder key * @returns Promise resolving to case instance with methods * {@link CaseInstanceGetResponse} * @example * ```typescript * // Get a specific case instance * const instance = await caseInstances.getById( * , * * ); * * // Access instance properties * console.log(`Status: ${instance.latestRunStatus}`); * ``` */ getById(instanceId: string, folderKey: string): Promise; /** * Close/Cancel a case instance * @param instanceId - The ID of the instance to cancel * @param folderKey - Required folder key * @param options - Optional close options with comment * @returns Promise resolving to operation result with instance data * @example * ```typescript * // 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}`); * } * ``` */ close(instanceId: string, folderKey: string, options?: CaseInstanceOperationOptions): Promise>; /** * Pause a case instance * @param instanceId - The ID of the instance to pause * @param folderKey - Required folder key * @param options - Optional pause options with comment * @returns Promise resolving to operation result with instance data */ pause(instanceId: string, folderKey: string, options?: CaseInstanceOperationOptions): Promise>; /** * Reopen a case instance from a specified element * @param instanceId - The ID of the case instance * @param folderKey - Required folder key * @param options - Reopen options containing stageId (the stage ID to resume from) and an optional comment * @returns Promise resolving to operation result with instance data * {@link CaseInstanceOperationResponse} * @example * ```typescript * 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 }); * ``` */ reopen(instanceId: string, folderKey: string, options: CaseInstanceReopenOptions): Promise>; /** * Resume a case instance * @param instanceId - The ID of the instance to resume * @param folderKey - Required folder key * @param options - Optional resume options with comment * @returns Promise resolving to operation result with instance data */ resume(instanceId: string, folderKey: string, options?: CaseInstanceOperationOptions): Promise>; /** * 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. * * @param instanceId - The ID of the case instance to send the message to * @param folderKey - Required folder key * @param name - The message name — a well-known `CaseInstanceMessageName` or a custom message name defined in the case model * @param options - Optional message options with itemData payload and reference override * @returns Promise that resolves when the message is accepted * @example * ```typescript * 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'] } } * ); * ``` */ sendMessage(instanceId: string, folderKey: string, name: string, options?: CaseInstanceSendMessageOptions): Promise; /** * Get execution history for a case instance * @param instanceId - The ID of the case instance * @param folderKey - Required folder key * @returns Promise resolving to instance execution history * {@link CaseInstanceExecutionHistoryResponse} * @example * ```typescript * // 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}`); * } * } * ``` */ getExecutionHistory(instanceId: string, folderKey: string): Promise; /** * Get stages and its associated tasks information for a case instance * @param caseInstanceId - The ID of the case instance * @param folderKey - Required folder key * @returns Promise resolving to an array of case stages with their tasks and status * @example * ```typescript * // 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}`); * } * } * } * ``` */ getStages(caseInstanceId: string, folderKey: string): Promise; /** * 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) * * @param caseInstanceId - The ID of the case instance * @param options - Optional filtering and pagination options * @returns Promise resolving to human in the loop tasks associated with the case instance * @example * ```typescript * // 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 * } * ); * ``` */ getActionTasks(caseInstanceId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * 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. * * @param options - Optional filtering and pagination options * @returns Promise resolving to {@link SlaSummaryResponse}, paginated or non-paginated based on options * @example * ```typescript * // 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 }); * ``` */ getSlaSummary(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * 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. * * @param options - Optional filtering options * @returns Promise resolving to an array of {@link CaseInstanceStageSLAResponse} * @example * ```typescript * // 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(); * ``` */ getStagesSlaSummary(options?: CaseInstanceStageSLAOptions): Promise; } interface CaseInstanceMethods { /** * Closes/cancels this case instance * * @param options - Optional close options with comment * @returns Promise resolving to operation result */ close(options?: CaseInstanceOperationOptions): Promise>; /** * Pauses this case instance * * @param options - Optional pause options with comment * @returns Promise resolving to operation result */ pause(options?: CaseInstanceOperationOptions): Promise>; /** * Reopens this case instance from a specified element * * @param options - Reopen options containing stageId (the stage ID to resume from) and an optional comment * @returns Promise resolving to operation result */ reopen(options: CaseInstanceReopenOptions): Promise>; /** * Resumes this case instance * * @param options - Optional resume options with comment * @returns Promise resolving to operation result */ resume(options?: CaseInstanceOperationOptions): Promise>; /** * Sends a message to this case instance * * @param name - The message name — a well-known `CaseInstanceMessageName` or a custom message name defined in the case model * @param options - Optional message options with itemData payload and reference override * @returns Promise that resolves when the message is accepted */ sendMessage(name: string, options?: CaseInstanceSendMessageOptions): Promise; /** * Gets execution history for this case instance * * @returns Promise resolving to instance execution history */ getExecutionHistory(): Promise; /** * Gets stages and their associated tasks for this case instance * * @returns Promise resolving to an array of case stages with their tasks and status */ getStages(): Promise; /** * Gets human in the loop tasks associated with this case instance * * @param options - Optional filtering and pagination options * @returns Promise resolving to human in the loop tasks associated with the case instance */ getActionTasks(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets the SLA summary for this case instance. * The default page size is 50, so only the top 50 items are returned when no pagination options are provided. * * @param options - Optional time range filtering and pagination options * @returns Promise resolving to SLA summary items for this case instance */ getSlaSummary = Omit>(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets the stages SLA summary for this case instance. * * @returns Promise resolving to an array of stage SLA summary items for this case instance */ getStagesSlaSummary(): Promise; } type CaseInstanceGetResponse = RawCaseInstanceGetResponse & CaseInstanceMethods; /** * Creates an actionable case instance by combining API case instance data with operational methods. * * @param instanceData - The case instance data from API * @param service - The case instance service instance * @returns A case instance object with added methods */ declare function createCaseInstanceWithMethods(instanceData: RawCaseInstanceGetResponse, service: CaseInstancesServiceModel): CaseInstanceGetResponse; /** * Service for interacting with Maestro Processes */ declare class MaestroProcessesService extends BaseService implements MaestroProcessesServiceModel { private processInstancesService; /** * Creates an instance of the Maestro Processes service. * * @param instance - UiPath SDK instance providing authentication and configuration */ constructor(instance: IUiPath); getAll(options?: MaestroProcessGetAllOptions): Promise; getIncidents(processKey: string, folderKey: string): Promise; getTopRunCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getTopElementFailedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getInstanceStatusTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; getIncidentsTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; getTopFaultedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getTopExecutionDuration(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getElementStats(request: MaestroProcessStatsRequest): Promise; getInstanceStats(request: MaestroProcessStatsRequest): Promise; } declare class ProcessInstancesService extends BaseService implements ProcessInstancesServiceModel { getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getById(id: string, folderKey: string): Promise; getExecutionHistory(instanceId: string, folderKey: string): Promise; private mapSpanToHistory; getBpmn(instanceId: string, folderKey: string): Promise; cancel(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; pause(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; resume(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; retry(instanceId: string, folderKey: string, options?: ProcessInstanceOperationOptions): Promise>; /** * Parses BPMN XML to extract variable metadata from uipath:inputOutput elements * @private * @param bpmnXml The BPMN XML string * @returns Map of variable ID to metadata */ private parseBpmnVariables; /** * Extracts element names from BPMN XML and maps them to their element IDs * @private * @param bpmnXml The BPMN XML string * @returns Map of elementId to element name */ private getVariableSource; /** * Enriches global variables with metadata from BPMN * @private * @param globals The raw globals object from API response * @param variableMetadata The parsed BPMN variable metadata * @returns Array of global variables */ private transformGlobalVariables; getVariables(instanceId: string, folderKey: string, options?: ProcessInstanceGetVariablesOptions): Promise; getIncidents(instanceId: string, folderKey: string): Promise; } /** * Service class for Maestro Process Incidents */ declare class ProcessIncidentsService extends BaseService implements ProcessIncidentsServiceModel { getAll(): Promise; } /** * Service for interacting with UiPath Maestro Cases */ declare class CasesService extends BaseService implements CasesServiceModel { getAll(options?: CaseGetAllOptions): Promise; getTopRunCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getTopElementFailedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getInstanceStatusTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; getIncidentsTimeline(startTime: Date, endTime: Date, options?: TimelineOptions): Promise; getTopFaultedCount(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getTopExecutionDuration(startTime: Date, endTime: Date, options?: TopQueryOptions): Promise; getElementStats(request: MaestroProcessStatsRequest): Promise; getInstanceStats(request: MaestroProcessStatsRequest): Promise; /** * Extract a readable case name from the packageId * @param packageId - The full package identifier * @returns A human-readable case name * @private */ private extractCaseName; } declare class CaseInstancesService extends BaseService implements CaseInstancesServiceModel { private taskService; /** * Creates an instance of the Case Instances service. * * @param instance - UiPath SDK instance providing authentication and configuration */ constructor(instance: IUiPath); getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getById(instanceId: string, folderKey: string): Promise; /** * Enhance a single case instance with case JSON data * @param instance - The case instance to enhance * @returns Promise resolving to enhanced instance * @private */ private enhanceInstanceWithCaseJson; /** * Enhance multiple case instances with case JSON data * @param instances - Array of case instances to enhance * @returns Promise resolving to array of enhanced instances * @private */ private enhanceInstancesWithCaseJson; /** * Get case JSON for a specific instance * @param instanceId - The case instance ID * @param folderKey - Required folder key * @returns Promise resolving to case JSON data * @private */ private getCaseJson; close(instanceId: string, folderKey: string, options?: CaseInstanceOperationOptions): Promise>; pause(instanceId: string, folderKey: string, options?: CaseInstanceOperationOptions): Promise>; reopen(instanceId: string, folderKey: string, options: CaseInstanceReopenOptions): Promise>; resume(instanceId: string, folderKey: string, options?: CaseInstanceOperationOptions): Promise>; sendMessage(instanceId: string, folderKey: string, name: string, options?: CaseInstanceSendMessageOptions): Promise; getExecutionHistory(instanceId: string, folderKey: string): Promise; getStages(caseInstanceId: string, folderKey: string): Promise; /** * Create a map of element ID to execution data * @param executionHistory - The execution history response * @returns Map of elementId to execution metadata * @private */ private createExecutionMap; /** * Create a map of binding IDs to their values * @param caseJsonResponse - The case JSON response * @returns Map of binding ID to binding object * @private */ private createBindingsMap; /** * Resolve binding values from binding expressions * @param value - The value that may contain binding references * @param bindingsMap - Map of binding IDs to binding objects * @returns Resolved value * @private */ private resolveBinding; /** * Process tasks for a stage node * @param node - The stage node containing tasks * @param executionMap - Map of element IDs to execution data * @param bindingsMap - Map of binding IDs to binding objects * @returns Processed tasks array * @private */ private processTasks; /** * Create a stage from a case node * @param node - The case node to process * @param executionMap - Map of element IDs to execution data * @param bindingsMap - Map of binding IDs to binding objects * @returns CaseGetStageResponse object * @private */ private createStageFromNode; getActionTasks(caseInstanceId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getSlaSummary(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getStagesSlaSummary(options?: CaseInstanceStageSLAOptions): Promise; } /** * Type for field mapping configuration * Maps source field names to target field names */ type FieldMapping = { [sourceField: string]: string; }; /** * Base service for services that need folder-specific functionality. * * Extends BaseService with additional methods for working with folder-scoped resources * in UiPath Orchestrator. Services that work with folders (Assets, Queues) extend this class. * * @remarks * This class provides helper methods for making folder-scoped API calls, handling folder IDs * in request headers, and managing cross-folder queries. */ declare class FolderScopedService extends BaseService { /** * Gets resources in a folder with optional query parameters * * @param endpoint - API endpoint to call * @param folderId - required folder ID * @param options - Query options * @param transformFn - Optional function to transform the response data * @returns Promise resolving to an array of resources */ protected _getByFolder(endpoint: string, folderId: number, options?: Record, transformFn?: (item: T) => R): Promise; /** * Look up a single resource by name on a folder-scoped OData collection. * * Shared by `getByName` implementations across services (Assets, Processes, etc). * Handles: * - Name validation via `validateName` * - Folder header resolution via `resolveFolderHeaders` (folderId → ID/key * header by type, folderPath → encoded path header, falls back to * init-time `config.folderKey` from the `uipath:folder-key` meta tag) * - OData `$filter=Name eq '…'` with single-quote escaping + `$top=1` * - Empty-result → `NotFoundError` with folder context in the message * * The transform step is caller-provided because each resource has its own * PascalCase → camelCase field mapping. * * @param resourceType - Resource label used in validation + error messages (e.g. 'Asset', 'Process') * @param endpoint - Folder-scoped OData collection endpoint * @param name - Resource name to search for * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) + OData query options (`expand`, `select`) * @param transform - Maps a raw OData item to the typed response (e.g. PascalCase → camelCase via field map) * @param responseFieldMap - Optional response field map (API → SDK), reversed internally by * `transformOptions` to rewrite SDK field names back to API names in user-supplied * `expand` / `select` (symmetric counterpart to `transform`) * @throws ValidationError when inputs are malformed; NotFoundError when no match */ protected getByNameLookup(resourceType: string, endpoint: string, name: string, options: FolderScopedOptions, transform: (raw: TRaw) => T, responseFieldMap?: FieldMapping): Promise; } /** * Enum for Asset Value Scope */ declare enum AssetValueScope { Global = "Global", PerRobot = "PerRobot" } /** * Enum for Asset Value Type */ declare enum AssetValueType { Text = "Text", Bool = "Bool", Integer = "Integer", Credential = "Credential", Secret = "Secret" } /** * Interface for key-value pair used in assets */ interface CustomKeyValuePair { key?: string; value?: string; } /** * Interface for asset response */ interface AssetGetResponse { key: string; name: string; id: number; canBeDeleted: boolean; valueScope: AssetValueScope; valueType: AssetValueType; value: string | null; credentialStoreId: number | null; keyValueList: CustomKeyValuePair[]; hasDefaultValue: boolean; description: string | null; foldersCount: number; lastModifiedTime: string | null; lastModifierUserId: number | null; createdTime: string; creatorUserId: number; } /** * Options for getting assets across folders */ type AssetGetAllOptions = RequestOptions & PaginationOptions & { /** * Optional folder ID to filter assets by folder */ folderId?: number; }; /** * Options for getting a single asset by ID */ interface AssetGetByIdOptions extends BaseOptions { } /** * Options for getting a single asset by name */ interface AssetGetByNameOptions extends FolderScopedOptions { } /** * New value accepted by {@link AssetServiceModel.updateValueById}. * * The runtime type must match the asset's `valueType`: * - `Text` → `string` * - `Integer` → `number` * - `Bool` → `boolean` */ type AssetNewValue = string | number | boolean; /** * Options for updating an asset value by ID */ interface AssetUpdateValueByIdOptions extends FolderScopedOptions { } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Assets } from '@uipath/uipath-typescript/assets'; * * const assets = new Assets(sdk); * const allAssets = await assets.getAll(); * ``` */ interface AssetServiceModel { /** * Gets all assets across folders with optional filtering * * @param options Query options including optional folderId and pagination options * @returns Promise resolving to either an array of assets NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link AssetGetResponse} * @example * ```typescript * // 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 * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single asset by ID * * @param id - Asset ID * @param folderId - Required folder ID * @param options - Optional query parameters (expand, select) * @returns Promise resolving to a single asset * {@link AssetGetResponse} * @example * ```typescript * // Get asset by ID * const asset = await assets.getById(, ); * ``` */ getById(id: number, folderId: number, options?: AssetGetByIdOptions): Promise; /** * Retrieves a single asset by name. * * @param name - Asset name to search for * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`) * @returns Promise resolving to a single asset * {@link AssetGetResponse} * @example * ```typescript * // 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' }); * ``` */ getByName(name: string, options?: AssetGetByNameOptions): Promise; /** * 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` * * @param id - Asset ID * @param newValue - New value to apply (string for `Text`, number for `Integer`, boolean for `Bool`) * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) * @returns Promise resolving when the asset has been updated * * @example * ```typescript * // 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' }); * ``` */ updateValueById(id: number, newValue: AssetNewValue, options?: AssetUpdateValueByIdOptions): Promise; } /** * Service for interacting with UiPath Orchestrator Assets API */ declare class AssetService extends FolderScopedService implements AssetServiceModel { getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getById(id: number, folderId: number, options?: AssetGetByIdOptions): Promise; getByName(name: string, options?: AssetGetByNameOptions): Promise; updateValueById(id: number, newValue: AssetNewValue, options?: AssetUpdateValueByIdOptions): Promise; } declare enum BucketOptions { None = "None", ReadOnly = "ReadOnly", AuditReadAccess = "AuditReadAccess", AccessDataThroughOrchestrator = "AccessDataThroughOrchestrator" } interface BucketGetResponse { id: number; name: string; description: string | null; identifier: string; storageProvider: string | null; storageParameters: string | null; storageContainer: string | null; options: BucketOptions; credentialStoreId: number | null; externalName: string | null; password: string | null; foldersCount: number; } type BucketGetAllOptions = RequestOptions & PaginationOptions & { folderId?: number; }; interface BucketGetByIdOptions extends BaseOptions { } /** * Options for getting a single bucket by name */ interface BucketGetByNameOptions extends FolderScopedOptions { } /** * Maps header names to their values * * @example * ```typescript * { * "x-ms-blob-type": "BlockBlob" * } * ``` */ type ResponseDictionary = Record; /** * Response from the GetReadUri API */ interface BucketGetUriResponse { /** * The URI for accessing the blob file */ uri: string; /** * HTTP method to use with the URI */ httpMethod: string; /** * Whether authentication is required to access the URI */ requiresAuth: boolean; /** * Headers to be included in the request */ headers: ResponseDictionary; } interface BucketGetUriOptions extends BaseOptions { /** * The ID of the bucket */ bucketId: number; /** * The full path to the BlobFile */ path: string; /** * URL expiration time in minutes (0 for default) */ expiryInMinutes?: number; } /** * Optional parameters for the preferred `getReadUri(bucketId, path, options?)` form. * Contains folder scoping (`folderId` / `folderKey` / `folderPath`), * `expiryInMinutes`, and standard query options (`expand`, `select`). */ interface BucketGetReadUriRequestOptions extends BaseOptions, FolderScopedOptions { /** * URL expiration time in minutes (0 for default) */ expiryInMinutes?: number; } /** * @deprecated Use the positional form: `getReadUri(bucketId, path, options?)`. * See {@link BucketGetReadUriRequestOptions} for the supported options. * * Request options for getting a read URI for a file in a bucket. */ interface BucketGetReadUriOptions extends BucketGetUriOptions, FolderScopedOptions { } /** * Request options for getting files in a bucket */ interface BucketGetFileMetaDataOptions { /** * The path prefix to filter files by */ prefix?: string; } /** * Request options for getting files in a bucket with pagination support */ type BucketGetFileMetaDataWithPaginationOptions = BucketGetFileMetaDataOptions & PaginationOptions & FolderScopedOptions; /** * Response from the GetFiles API */ interface BucketGetFileMetaDataResponse { /** * Array of blob items in the bucket */ blobItems: BlobItem[]; /** * Token for retrieving the next set of results */ continuationToken: string | null; } /** * Represents a file or blob in a bucket */ interface BlobItem { /** * Full path to the blob */ path: string; /** * Content type of the blob */ contentType: string; /** * Size of the blob in bytes */ size: number; /** * Last modified timestamp */ lastModified: string | null; } /** * Represents a file or directory entry in a bucket */ interface BucketFile { /** * Full path to the file or directory */ path: string; /** * Content type of the file (empty for directories) */ contentType: string; /** * Size of the file in bytes */ size: number; /** * Whether the entry is a directory */ isDirectory: boolean; /** * Identifier of the file, when available */ id: string | null; } /** * Options for listing files in a bucket directory */ type BucketGetFilesOptions = RequestOptions & PaginationOptions & FolderScopedOptions & { /** * Regex pattern to filter file names (e.g., '.*\\.pdf$') */ fileNameRegex?: string; }; /** * Options for deleting a file from a bucket */ interface BucketDeleteFileOptions extends FolderScopedOptions { } /** * Optional parameters for the preferred * `uploadFile(bucketId, path, content, options?)` form. Contains folder * scoping (`folderId` / `folderKey` / `folderPath`). */ interface BucketUploadFileRequestOptions extends FolderScopedOptions { } /** * @deprecated Use the positional form: `uploadFile(bucketId, path, content, options?)`. * See {@link BucketUploadFileRequestOptions} for the supported options. * * Options for uploading files to a bucket. */ interface BucketUploadFileOptions extends FolderScopedOptions { /** * The ID of the bucket to upload to */ bucketId: number; /** * Path where the file should be stored in the bucket */ path: string; /** * File content to upload */ content: Blob | Uint8Array | File; } /** * Response from file upload operations */ interface BucketUploadResponse { /** * Whether the upload was successful */ success: boolean; /** * HTTP status code from the upload operation */ statusCode: number; } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Buckets } from '@uipath/uipath-typescript/buckets'; * * const buckets = new Buckets(sdk); * const allBuckets = await buckets.getAll(); * ``` */ interface BucketServiceModel { /** * 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) * * @param options - Query options including optional folderId and pagination options * @returns Promise resolving to either an array of buckets NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link BucketGetResponse} * @example * ```typescript * // 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 * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single bucket by ID * * @param bucketId - Bucket ID * @param folderId - Required folder ID * @param options - Optional query parameters * @returns Promise resolving to a bucket definition * {@link BucketGetResponse} * @example * ```typescript * // Get bucket by ID * const bucket = await buckets.getById(, ); * ``` */ getById(bucketId: number, folderId: number, options?: BucketGetByIdOptions): Promise; /** * Retrieves a single orchestrator storage bucket by name. * * @param name - Bucket name to search for * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`) * @returns Promise resolving to a single bucket * {@link BucketGetResponse} * @example * ```typescript * // 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: '' }); * ``` */ getByName(name: string, options?: BucketGetByNameOptions): Promise; /** * 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) * * @param bucketId - The ID of the bucket to get file metadata from * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional parameters for filtering and pagination * @returns Promise resolving to either an array of files metadata NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link BlobItem} * @example * ```typescript * // 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 }); * } * ``` */ getFileMetaData(bucketId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets metadata for files in a bucket — positional `folderId` form. * * @deprecated Use the options-object form: `getFileMetaData(bucketId, { folderId })`. See {@link BucketGetFileMetaDataWithPaginationOptions} for the supported options. * * @param bucketId - The ID of the bucket to get file metadata from * @param folderId - Required folder ID (numeric) * @param options - Optional parameters for filtering and pagination * @returns Promise resolving to either an array of files metadata NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link BlobItem} */ getFileMetaData(bucketId: number, folderId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a direct download URL for a file in the bucket. * * Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` * in the options. * * @param bucketId - The ID of the bucket * @param path - The full path to the file * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional `expiryInMinutes` * @returns Promise resolving to blob file access information * {@link BucketGetUriResponse} * @example * ```typescript * // 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' }); * ``` */ getReadUri(bucketId: number, path: string, options?: BucketGetReadUriRequestOptions): Promise; /** * Gets a direct download URL for a file in the bucket — options-only form. * * @deprecated Use the positional form: `getReadUri(bucketId, path, options?)`. See {@link BucketGetReadUriRequestOptions} for the supported options. * * @param options - Contains bucketId, folder scoping (`folderId` / `folderKey` / `folderPath`), file path and optional expiry time * @returns Promise resolving to blob file access information * {@link BucketGetUriResponse} */ getReadUri(options: BucketGetReadUriOptions): Promise; /** * Uploads a file to a bucket. * * Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` * in the options. * * @param bucketId - The ID of the bucket to upload to * @param path - Path where the file should be stored in the bucket * @param content - File content to upload * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) * @returns Promise resolving bucket upload response * {@link BucketUploadResponse} * @example * ```typescript * // 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: }); * ``` */ uploadFile(bucketId: number, path: string, content: Blob | Uint8Array | File, options?: BucketUploadFileRequestOptions): Promise; /** * Uploads a file to a bucket — options-only form. * * @deprecated Use the positional form: `uploadFile(bucketId, path, content, options?)`. See {@link BucketUploadFileRequestOptions} for the supported options. * * @param options - Options for file upload including bucket ID, folder scoping (`folderId` / `folderKey` / `folderPath`), path, and content * @returns Promise resolving bucket upload response * {@link BucketUploadResponse} */ uploadFile(options: BucketUploadFileOptions): Promise; /** * Deletes a file from a bucket * * @param bucketId - The ID of the bucket * @param path - The full path to the file to delete * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) * @returns Promise resolving when the file is deleted * @example * ```typescript * // Delete a file from a bucket * await buckets.deleteFile(, '/folder/file.pdf', { folderId: }); * ``` */ deleteFile(bucketId: number, path: string, options?: BucketDeleteFileOptions): Promise; /** * 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. {@link 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) * * @param bucketId - The ID of the bucket * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional parameters for regex filtering, query options, and pagination * {@link BucketGetFilesOptions} * @returns Promise resolving to either an array of files NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link BucketFile} * @example * ```typescript * // 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 * }); * ``` */ getFiles(bucketId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; } declare class BucketService extends FolderScopedService implements BucketServiceModel { getById(id: number, folderId: number, options?: BucketGetByIdOptions): Promise; getByName(name: string, options?: BucketGetByNameOptions): Promise; getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getFileMetaData(bucketId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getFileMetaData(bucketId: number, folderId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; uploadFile(bucketId: number, path: string, content: Blob | Uint8Array | File, options?: BucketUploadFileRequestOptions): Promise; uploadFile(options: BucketUploadFileOptions): Promise; getReadUri(bucketId: number, path: string, options?: BucketGetReadUriRequestOptions): Promise; getReadUri(options: BucketGetReadUriOptions): Promise; /** * Uploads content to the provided URI * @param uriResponse - Response from getWriteUri containing URL and headers * @param content - The content to upload * @returns The response from the upload request with status info */ private _uploadToUri; /** * Private method to handle common URI request logic * @param endpoint - The API endpoint to call * @param bucketId - The bucket ID * @param path - The file path * @param headers - Pre-built folder-context headers (built via `resolveFolderHeaders`) * @param queryOptions - Additional query parameters * @returns Promise resolving to blob file access information */ private _getUri; getFiles(bucketId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; deleteFile(bucketId: number, path: string, options?: BucketDeleteFileOptions): Promise; /** * Gets a direct upload URL for a file in the bucket * * @param options - Contains bucketId, file path, optional expiry time, and pre-built folder-context headers * @returns Promise resolving to blob file access information */ private _getWriteUri; } /** * Enum for package types */ declare enum PackageType { Undefined = "Undefined", Process = "Process", ProcessOrchestration = "ProcessOrchestration", WebApp = "WebApp", Agent = "Agent", TestAutomationProcess = "TestAutomationProcess", Api = "Api", MCPServer = "MCPServer", BusinessRules = "BusinessRules", CaseManagement = "CaseManagement", Flow = "Flow", Function = "Function" } /** * Enum for job priority */ declare enum JobPriority { Low = "Low", Normal = "Normal", High = "High" } /** * Enum for target framework */ declare enum TargetFramework { Legacy = "Legacy", Windows = "Windows", Portable = "Portable" } /** * Enum for robot size */ declare enum RobotSize { Small = "Small", Standard = "Standard", Medium = "Medium", Large = "Large" } /** * Enum for remote control access */ declare enum RemoteControlAccess { None = "None", ReadOnly = "ReadOnly", Full = "Full" } /** * Enum for process start strategy */ declare enum StartStrategy { All = "All", Specific = "Specific", RobotCount = "RobotCount", JobsCount = "JobsCount", ModernJobsCount = "ModernJobsCount" } /** * Enum for package source type */ declare enum PackageSourceType { Manual = "Manual", Schedule = "Schedule", Queue = "Queue", StudioWeb = "StudioWeb", IntegrationTrigger = "IntegrationTrigger", StudioDesktop = "StudioDesktop", AutomationOpsPipelines = "AutomationOpsPipelines", Apps = "Apps", SAP = "SAP", HttpTrigger = "HttpTrigger", HttpTriggerWithCallback = "HttpTriggerWithCallback", RobotAPI = "RobotAPI", Assistant = "Assistant", CommandLine = "CommandLine", RobotNetAPI = "RobotNetAPI", Autopilot = "Autopilot", TestManager = "TestManager", AgentService = "AgentService", ProcessOrchestration = "ProcessOrchestration", PluginEcosystem = "PluginEcosystem", PerformanceTesting = "PerformanceTesting", AgentHub = "AgentHub", ApiWorkflow = "ApiWorkflow" } /** * Enum for job source type */ declare enum JobSourceType { Manual = "Manual", Schedule = "Schedule", Agent = "Agent", Queue = "Queue", StudioWeb = "StudioWeb", IntegrationTrigger = "IntegrationTrigger", StudioDesktop = "StudioDesktop", AutomationOpsPipelines = "AutomationOpsPipelines", Apps = "Apps", SAP = "SAP", HttpTrigger = "HttpTrigger", HttpTriggerCallback = "HttpTriggerCallback", RobotAPI = "RobotAPI", CommandLine = "CommandLine", RobotNetAPI = "RobotNetAPI", Autopilot = "Autopilot", TestManager = "TestManager", AgentService = "AgentService", ProcessOrchestration = "ProcessOrchestration", PluginEcosystem = "PluginEcosystem", PerformanceTesting = "PerformanceTesting", AgentHub = "AgentHub", ApiWorkflow = "ApiWorkflow", CaseManagement = "CaseManagement" } /** * Enum for stop strategy */ declare enum StopStrategy { SoftStop = "SoftStop", Kill = "Kill" } /** * Enum for runtime type */ declare enum RuntimeType { NonProduction = "NonProduction", Attended = "Attended", Unattended = "Unattended", Development = "Development", Studio = "Studio", RpaDeveloper = "RpaDeveloper", StudioX = "StudioX", CitizenDeveloper = "CitizenDeveloper", Headless = "Headless", StudioPro = "StudioPro", RpaDeveloperPro = "RpaDeveloperPro", TestAutomation = "TestAutomation", AutomationCloud = "AutomationCloud", Serverless = "Serverless", AutomationKit = "AutomationKit", ServerlessTestAutomation = "ServerlessTestAutomation", AutomationCloudTestAutomation = "AutomationCloudTestAutomation", AttendedStudioWeb = "AttendedStudioWeb", Hosting = "Hosting", AssistantWeb = "AssistantWeb", ProcessOrchestration = "ProcessOrchestration", AgentService = "AgentService", AppTest = "AppTest", PerformanceTest = "PerformanceTest", BusinessRule = "BusinessRule", CaseManagement = "CaseManagement", Flow = "Flow" } /** * Interface for Job Attachment */ interface JobAttachment { attachmentId: string; jobKey?: string; category?: string; attachmentName?: string; } /** * Interface for common process properties shared across multiple interfaces */ interface ProcessProperties { jobPriority?: JobPriority | null; specificPriorityValue?: number | null; inputArguments?: string | null; environmentVariables?: string | null; entryPointPath?: string | null; remoteControlAccess?: RemoteControlAccess | null; requiresUserInteraction?: boolean | null; } /** * Interface for common folder properties */ interface FolderProperties { folderId: number; folderName: string | null; } /** * Base interface for process start request */ interface BaseProcessStartRequest extends ProcessProperties { strategy?: StartStrategy; robotIds?: number[]; machineSessionIds?: number[]; noOfRobots?: number; jobsCount?: number; source?: PackageSourceType; runtimeType?: RuntimeType; inputFile?: string; reference?: string; attachments?: JobAttachment[]; targetFramework?: TargetFramework; resumeOnSameContext?: boolean; batchExecutionKey?: string; stopProcessExpression?: string; stopStrategy?: StopStrategy; killProcessExpression?: string; alertPendingExpression?: string; alertRunningExpression?: string; runAsMe?: boolean; parentOperationId?: string; } /** * Interface for start process request with processKey */ interface ProcessStartRequestWithKey extends BaseProcessStartRequest { processKey: string; processName?: string; } /** * Interface for start process request with processName */ interface ProcessStartRequestWithName extends BaseProcessStartRequest { processKey?: string; processName: string; } /** * Interface for start process request * Either processKey or processName must be provided */ type ProcessStartRequest = ProcessStartRequestWithKey | ProcessStartRequestWithName; /** * Interface for robot metadata */ interface RobotMetadata { id: number; name?: string; username?: string; } /** * Interface for machine */ interface Machine { id: number; name?: string; } /** * Interface for job error */ interface JobError { code?: string; title?: string; detail?: string; category?: string; status?: number; timestamp?: string; } /** * Enum for job type */ declare enum JobType { Unattended = "Unattended", Attended = "Attended", ServerlessGeneric = "ServerlessGeneric" } /** * Interface for argument metadata */ interface ArgumentMetadata { input?: string; output?: string; } /** * Interface for job response */ interface ProcessStartResponse extends ProcessProperties, FolderProperties { key: string; startTime: string | null; endTime: string | null; state: JobState; source: string; sourceType: JobSourceType; batchExecutionKey: string; info: string | null; createdTime: string; startingScheduleId: number | null; processName: string; /** Key of the process this job was started from. */ processKey: string; type: JobType; inputFile: string | null; outputArguments: string | null; outputFile: string | null; hostMachineName: string | null; persistenceId: string | null; resumeVersion: number | null; stopStrategy: StopStrategy | null; runtimeType: RuntimeType; processVersionId: number | null; reference: string; packageType: PackageType; machine?: Machine; resumeOnSameContext: boolean; localSystemAccount: string; orchestratorUserIdentity: string | null; startingTriggerId: string | null; maxExpectedRunningTimeSeconds: number | null; parentJobKey: string | null; resumeTime: string | null; lastModifiedTime: string | null; jobError: JobError | null; errorCode: string | null; robot?: RobotMetadata; id: number; } /** * Interface for process response */ interface ProcessGetResponse extends ProcessProperties, FolderProperties { key: string; packageKey: string; packageVersion: string; isLatestVersion: boolean; isPackageDeleted: boolean; description: string; name: string; entryPointId: number; packageType: PackageType; supportsMultipleEntryPoints: boolean; isConversational: boolean | null; minRequiredRobotVersion: string | null; isCompiled: boolean; arguments: ArgumentMetadata; autoUpdate: boolean; hiddenForAttendedUser: boolean; feedId: string; folderKey: string; targetFramework: TargetFramework; robotSize: RobotSize | null; lastModifiedTime: string | null; lastModifierUserId: number | null; createdTime: string; creatorUserId: number; id: number; } /** * Options for getting processes across folders */ type ProcessGetAllOptions = RequestOptions & PaginationOptions & { /** * Optional folder ID to filter processes by folder */ folderId?: number; }; /** * Options for getting a single process by ID */ interface ProcessGetByIdOptions extends BaseOptions { } /** * Options for getting a single process by name */ interface ProcessGetByNameOptions extends FolderScopedOptions { } /** * Options for starting a process. Combines folder scoping * (`folderId` / `folderKey` / `folderPath`) with the OData query options * (`expand`, `select`, `filter`, `orderby`) accepted by the start endpoint. * * Folder scoping is optional in the type — the SDK falls back to the * init-time folderKey (e.g. `` in coded-app * deployments). A `ValidationError` is raised when neither is provided. */ interface ProcessStartOptions extends FolderScopedOptions, RequestOptions { } /** * Enum for job sub-state */ declare enum JobSubState { WithFaults = "WITH_FAULTS", Manually = "MANUALLY" } /** * Enum for serverless job type */ declare enum ServerlessJobType { RobotJob = "RobotJob", WebApp = "WebApp", LoadTest = "LoadTest", StudioWebDesigner = "StudioWebDesigner", PublishStudioProject = "PublishStudioProject", JsApi = "JsApi", PythonCodedAgent = "PythonCodedAgent", MCPServer = "MCPServer", PythonCodedSystemAgent = "PythonCodedSystemAgent", PythonAgent = "PythonAgent" } /** * Interface for process metadata associated with a job. * Represents a lightweight summary of the process (release) linked to a job. * Available when using 'expand: "release"' in the query. */ interface ProcessMetadata { /** The unique key of the release */ key?: string; /** The process key identifying the package */ processKey?: string; /** The version of the process package */ processVersion?: string; /** Whether this is the latest version of the process */ isLatestVersion?: boolean; /** The display name of the process */ name?: string; /** The numeric ID of the release */ id?: number; } /** * Raw job response from the API before method attachment */ interface RawJobGetResponse extends FolderProperties { /** The unique numeric identifier of the job */ id: number; /** The unique job identifier (GUID) */ key: string; /** The current execution state of the job */ state: JobState; /** The date and time when the job was created */ createdTime: string; /** The date and time when the job execution started, or null if the job hasn't started yet */ startTime: string | null; /** The date and time when the job execution ended, or null if the job hasn't ended yet */ endTime: string | null; /** The date and time when the job was last modified */ lastModifiedTime: string | null; /** The date and time when the job was resumed after suspension */ resumeTime: string | null; /** The name of the process (release) associated with the job */ processName: string | null; /** Path to the entry point workflow (XAML) that will be executed by the robot */ entryPointPath: string | null; /** The name of the machine where the robot ran the job */ hostMachineName: string | null; /** Input parameters as a JSON string passed to job execution */ inputArguments: string | null; /** Output parameters as a JSON string resulted from job execution */ outputArguments: string | null; /** Attachment key for file-based output when output is too large for inline arguments */ outputFile: string | null; /** Environment variables as a JSON string passed to the job execution */ environmentVariables: string | null; /** Additional information about the current job */ info: string | null; /** The source name of the job, describing how the job was triggered */ source: string | null; /** Reference identifier for the job, used for external correlation */ reference: string | null; /** The execution priority of the job */ jobPriority: JobPriority | null; /** Value for more granular control over execution priority (1-100) */ specificPriorityValue: number | null; /** The type of the job - Attended if started via the robot, Unattended otherwise */ type: JobType; /** The package type of the process associated with the job */ packageType: PackageType; /** The runtime type of the robot which can pick up the job */ runtimeType: RuntimeType | null; /** The source type indicating how the job was triggered */ sourceType: JobSourceType; /** The type of the serverless job, or null for non-serverless jobs */ serverlessJobType: ServerlessJobType | null; /** The stop strategy for the job */ stopStrategy: StopStrategy | null; /** The remote control access level for the job */ remoteControlAccess: RemoteControlAccess; /** The folder key (GUID) of the folder this job is part of */ folderKey: string | null; /** The unique identifier grouping multiple jobs, usually generated when started by a schedule */ batchExecutionKey: string; /** The parent job key (GUID), set when the job was started by another job */ parentJobKey: string | null; /** The ID of the schedule that started the job, or null if started by the user */ startingScheduleId: number | null; /** The starting trigger ID, can be ApiTriggerId or HttpTriggerId */ startingTriggerId: string | null; /** The process version ID */ processVersionId: number | null; /** Expected maximum running time in seconds before the job is flagged */ maxExpectedRunningTimeSeconds: number | null; /** Whether the job requires user interaction */ requiresUserInteraction: boolean; /** If set, the job will resume on the same robot-machine pair on which it initially ran */ resumeOnSameContext: boolean; /** Distinguishes between multiple job suspend/resume cycles */ resumeVersion: number | null; /** The sub-state in which the job is, providing more granular status information */ subState: JobSubState | null; /** The target runtime for the job */ targetRuntime: string | null; /** The trace ID for distributed tracing */ traceId: string | null; /** The parent span ID for distributed tracing */ parentSpanId: string | null; /** The error code associated with a failed job */ errorCode: string | null; /** The machine associated with the job (available when using expand=machine) */ machine?: Machine; /** The robot associated with the job (available when using expand=robot) */ robot?: RobotMetadata; /** The process metadata associated with the job */ process?: ProcessMetadata | null; /** Error details for the job, or null if the job has no errors */ jobError: JobError | null; } /** * Options for resuming a suspended job */ interface JobResumeOptions { /** Input arguments to pass to the resumed job */ inputArguments?: Record; } /** * Options for getting all jobs */ type JobGetAllOptions = RequestOptions & PaginationOptions & { /** * Optional folder ID to filter jobs by folder */ folderId?: number; }; /** * Options for getting a job by ID */ interface JobGetByIdOptions extends BaseOptions { } /** * Options for stopping jobs */ interface JobStopOptions { /** * The stop strategy to use. * - `SoftStop` — requests graceful cancellation; the job completes its current activity before stopping * - `Kill` — requests immediate termination of the job * @default StopStrategy.SoftStop */ strategy?: StopStrategy; } /** Combined response type for job data with bound methods. */ type JobGetResponse = RawJobGetResponse & JobMethods; /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Jobs } from '@uipath/uipath-typescript/jobs'; * * const jobs = new Jobs(sdk); * const allJobs = await jobs.getAll(); * ``` */ interface JobServiceModel { /** * 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. * * !!! info "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 {@link getOutput} method with the job's `key` and `folderId`. * * @param options - Query options including optional folderId, filtering, and pagination options * @returns Promise resolving to either an array of jobs {@link NonPaginatedResponse}<{@link JobGetResponse}> or a {@link PaginatedResponse}<{@link JobGetResponse}> when pagination options are used. * {@link JobGetResponse} * @example * ```typescript * // 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 * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * 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`. * * @param id - The unique key (GUID) of the job to retrieve * @param folderId - The folder ID where the job resides * @param options - Optional query options for expanding or selecting fields * @returns Promise resolving to a {@link JobGetResponse} with full job details and bound methods * * @example * ```typescript * // Get a job by key * const job = await jobs.getById(, ); * console.log(job.state, job.processName); * ``` * * @example * ```typescript * // With expanded related entities * const job = await jobs.getById(, , { * expand: 'robot,machine' * }); * console.log(job.robot?.name, job.machine?.name); * ``` */ getById(id: string, folderId: number, options?: JobGetByIdOptions): Promise; /** * 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. * * @param jobKey - The unique key (GUID) of the job to retrieve output from * @param folderId - The folder ID where the job resides * @returns Promise resolving to the parsed output as `Record`, or `null` if no output exists * * @example * ```typescript * // Get output from a completed job * const output = await jobs.getOutput(, ); * * if (output) { * console.log('Job output:', output); * } * ``` * * @example * ```typescript * // 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(); * } * ``` */ getOutput(jobKey: string, folderId: number): Promise | null>; /** * 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. * * @param jobKeys - Array of job UUID keys to stop (e.g., from {@link JobGetResponse}.key) * @param folderId - The folder ID where the jobs reside (required) * @param options - Optional {@link JobStopOptions} including stop strategy * @returns Promise that resolves when the jobs are stopped successfully, or rejects on failure * * @example * ```typescript * // Stop a single job with default soft stop * await jobs.stop([], ); * ``` * * @example * ```typescript * import { StopStrategy } from '@uipath/uipath-typescript/jobs'; * * // Force-kill multiple jobs * await jobs.stop( * [, ], * , * { strategy: StopStrategy.Kill } * ); * ``` */ stop(jobKeys: string[], folderId: number, options?: JobStopOptions): Promise; /** * 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. * * @param jobKey - The unique key (GUID) of the suspended job to resume * @param folderId - The folder ID where the job resides * @param options - Optional parameters including input arguments * @returns Promise that resolves when the job is resumed successfully, or rejects on failure * * @example * ```typescript * // Resume a suspended job * await jobs.resume(, ); * ``` * * @example * ```typescript * // Resume with input arguments * await jobs.resume(, , { * inputArguments: { approved: true } * }); * ``` */ resume(jobKey: string, folderId: number, options?: JobResumeOptions): Promise; /** * 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 {@link getById} * using the returned job's key until the state reaches a final value. * * @param jobKey - The unique key (GUID) of the job to restart * @param folderId - The folder ID where the job resides * @returns Promise resolving to the new {@link JobGetResponse} with full job details * * @example * ```typescript * // Restart a faulted job * const newJob = await jobs.restart(, ); * console.log(newJob.state); // 'Pending' * console.log(newJob.key); // new job key (different from original) * ``` */ restart(jobKey: string, folderId: number): Promise; } /** * Methods available on job response objects. * These are bound to the job data and delegate to the service. */ interface JobMethods { /** * Gets the output of this 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. * * @returns Promise resolving to the parsed output as `Record`, or `null` if no output exists * * @example * ```typescript * const allJobs = await jobs.getAll(); * const completedJob = allJobs.items.find(j => j.state === JobState.Successful); * * if (completedJob) { * const output = await completedJob.getOutput(); * } * ``` */ getOutput(): Promise | null>; /** * Stops this job. * * Sends a stop request for this job to the Orchestrator. * * @param options - Optional {@link JobStopOptions} including stop strategy (defaults to SoftStop) * @returns Promise that resolves when the jobs are stopped successfully, or rejects on failure * * @example * ```typescript * const allJobs = await jobs.getAll({ folderId: }); * const runningJob = allJobs.items.find(j => j.state === JobState.Running); * * if (runningJob) { * await runningJob.stop(); * } * ``` */ stop(options?: JobStopOptions): Promise; /** * Resumes this suspended job. * * @param options - Optional parameters including input arguments * @returns Promise that resolves when the job is resumed successfully, or rejects on failure */ resume(options?: JobResumeOptions): Promise; /** * Restarts this job, creating a new execution with a new key. * * @returns Promise resolving to the new {@link JobGetResponse} with full job details */ restart(): Promise; } /** * Creates a job response with bound methods. * * @param jobData - The raw job data from API * @param service - The job service instance * @returns A job object with added methods */ declare function createJobWithMethods(jobData: RawJobGetResponse, service: JobServiceModel): JobGetResponse; /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Processes } from '@uipath/uipath-typescript/processes'; * * const processes = new Processes(sdk); * const allProcesses = await processes.getAll(); * ``` */ interface ProcessServiceModel { /** * 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 * * @param options - Query options including optional folderId and pagination options * @returns Promise resolving to either an array of processes NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link ProcessGetResponse} * @example * ```typescript * // 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 * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single process by ID * * @param id - Process ID * @param folderId - Required folder ID * @param options - Optional query parameters * @returns Promise resolving to a single process * {@link ProcessGetResponse} * @example * ```typescript * // Get process by ID * const process = await processes.getById(, ); * ``` */ getById(id: number, folderId: number, options?: ProcessGetByIdOptions): Promise; /** * Retrieves a single process by name. * * @param name - Process name to search for * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`) * @returns Promise resolving to a single process * {@link ProcessGetResponse} * @example * ```typescript * // 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' }); * ``` */ getByName(name: string, options?: ProcessGetByNameOptions): Promise; /** * Starts a process with the specified configuration. * * Folder context can be supplied as `folderId`, `folderKey`, or `folderPath` * inside the options. * * @param request - Process start configuration * @param options - Folder scoping (`folderId` / `folderKey` / `folderPath`) and optional query parameters (`expand`, `select`, `filter`, `orderby`) * @returns Promise resolving to array of started process instances * {@link ProcessStartResponse} * @example * ```typescript * // 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' }); * ``` */ start(request: ProcessStartRequest, options?: ProcessStartOptions): Promise; /** * Starts a process — positional `folderId` form. * * @deprecated Use the options-object form: `start(request, { folderId })`. See {@link ProcessStartOptions} for the supported options. * * @param request - Process start configuration * @param folderId - Required folder ID (numeric) * @param options - Optional request options * @returns Promise resolving to array of started process instances * {@link ProcessStartResponse} */ start(request: ProcessStartRequest, folderId: number, options?: RequestOptions): Promise; } /** * Service for interacting with UiPath Orchestrator Processes API */ declare class ProcessService extends FolderScopedService implements ProcessServiceModel { getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; start(request: ProcessStartRequest, options?: ProcessStartOptions): Promise; start(request: ProcessStartRequest, folderId: number, options?: RequestOptions): Promise; getById(id: number, folderId: number, options?: ProcessGetByIdOptions): Promise; getByName(name: string, options?: ProcessGetByNameOptions): Promise; } /** * Interface for queue response */ interface QueueGetResponse { key: string; name: string; id: number; description: string; maxNumberOfRetries: number; acceptAutomaticallyRetry: boolean; retryAbandonedItems: boolean; enforceUniqueReference: boolean; encrypted: boolean; specificDataJsonSchema: string | null; outputDataJsonSchema: string | null; analyticsDataJsonSchema: string | null; createdTime: string; processScheduleId: number | null; slaInMinutes: number; riskSlaInMinutes: number; releaseId: number | null; isProcessInCurrentFolder: boolean | null; foldersCount: number; folderId: number; folderName: string; } /** * Options for getting queues across folders */ type QueueGetAllOptions = RequestOptions & PaginationOptions & { /** * Optional folder ID to filter queues by folder */ folderId?: number; }; interface QueueGetByIdOptions extends BaseOptions { } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Queues } from '@uipath/uipath-typescript/queues'; * * const queues = new Queues(sdk); * const allQueues = await queues.getAll(); * ``` */ interface QueueServiceModel { /** * Gets all queues across folders with optional filtering and folder scoping * * @signature getAll(options?) → Promise<QueueGetResponse[]> * @param options Query options including optional folderId and pagination options * @returns Promise resolving to either an array of queues NonPaginatedResponse or a PaginatedResponse when pagination options are used. * {@link QueueGetResponse} * @example * ```typescript * // 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 * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single queue by ID * * @param id - Queue ID * @param folderId - Required folder ID * @returns Promise resolving to a queue definition * @example * ```typescript * // Get queue by ID * const queue = await queues.getById(, ); * ``` */ getById(id: number, folderId: number, options?: QueueGetByIdOptions): Promise; } /** * Service for interacting with UiPath Orchestrator Queues API */ declare class QueueService extends FolderScopedService implements QueueServiceModel { getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getById(id: number, folderId: number, options?: QueueGetByIdOptions): Promise; } /** * Attachment response from the API */ interface AttachmentResponse { /** * UUID of the attachment */ id: string; /** * Name of the attachment */ name: string; /** * Optional job key to link the attachment to a job when creating it. */ jobKey?: string; /** * Optional category for the attachment when linking to a job. */ attachmentCategory?: string; /** * When the attachment was last modified */ lastModifiedTime?: string; /** * User ID who last modified the attachment */ lastModifierUserId?: number; /** * When the attachment was created */ createdTime?: string; /** * User ID who created the attachment */ creatorUserId?: number; blobFileAccess: BucketGetUriResponse; } /** * Options for getting an attachment by ID */ interface AttachmentGetByIdOptions extends BaseOptions { } /** * Service for managing UiPath Orchestrator Attachments. * * Attachments are files that can be associated with Orchestrator jobs. */ interface AttachmentServiceModel { /** * Gets an attachment by ID * * @param id - The UUID of the attachment to retrieve * @param options - Optional query parameters (expand, select) * @returns Promise resolving to the attachment * {@link AttachmentResponse} * @example * ```typescript * import { Attachments } from '@uipath/uipath-typescript/attachments'; * * const attachments = new Attachments(sdk); * const attachment = await attachments.getById('12345678-1234-1234-1234-123456789abc'); * ``` */ getById(id: string, options?: AttachmentGetByIdOptions): Promise; } /** * Service for interacting with UiPath Tasks API */ declare class TaskService extends BaseService implements TaskServiceModel { create(task: TaskCreateOptions, folderId: number): Promise; getUsers(folderId: number, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; getById(id: number, options?: TaskGetByIdOptions, folderId?: number): Promise; assign(taskAssignments: TaskAssignmentOptions | TaskAssignmentOptions[]): Promise>; reassign(taskAssignments: TaskAssignmentOptions | TaskAssignmentOptions[]): Promise>; unassign(taskIds: number | number[]): Promise>; complete(options: TaskCompletionOptions, folderId: number): Promise>; /** * Routes to the type-specific endpoint based on task type. */ private getByTaskType; /** * Fetches a task from a type-specific endpoint. * * @param id - The task ID * @param folderId - Required folder ID * @param endpoint - The type-specific endpoint to call * @param extraParams - Additional query parameters (e.g. form options) * @returns Promise resolving to the task */ private getTaskByTypeEndpoint; /** * Process parameters for task queries with folder filtering * @param options - The REST API options to process * @param folderId - Optional folder ID to filter by * @returns Processed options with folder filtering applied if needed * @private */ private processTaskParameters; /** * Adds default expand parameters to options * @param options - The options object to add default expand to * @returns Options with default expand parameters added * @private */ private addDefaultExpand; } /** * UiPath SDK - Legacy class providing all services through property getters. * * Extends core UiPath. For modular usage, import from specific service modules. * * @deprecated This class is provided for backward compatibility only. * Use the modular pattern with `@uipath/uipath-typescript/core` instead. * * @example * ```typescript * // Legacy pattern (deprecated) * import { UiPath } from '@uipath/uipath-typescript'; * * const sdk = new UiPath(config); * await sdk.initialize(); * const data = await sdk.entities.getAll(); * ``` * * @example * ```typescript * // New modular pattern (recommended) * import { UiPath } from '@uipath/uipath-typescript/core'; * import { Entities } from '@uipath/uipath-typescript/entities'; * * const sdk = new UiPath(config); * await sdk.initialize(); * const entitiesService = new Entities(sdk); * const data = await entitiesService.getAll(); * ``` */ declare class UiPath extends UiPath$1 { private readonly _services; private getService; /** * Access to Maestro services */ get maestro(): { /** * Access to Maestro Processes service */ processes: MaestroProcessesService & { /** * Access to Process Instances service */ instances: ProcessInstancesService; /** * Access to Process Incidents service */ incidents: ProcessIncidentsService; }; /** * Access to Maestro Cases service */ cases: CasesService & { /** * Access to Case Instances service */ instances: CaseInstancesService; }; }; /** * Access to Entity service */ get entities(): EntityService & { /** * Access to ChoiceSet service for managing choice sets */ choicesets: ChoiceSetService; /** * Access to Data Fabric roles for manage-access flows * * @internal */ roles: DataFabricRoleService; /** * Access to Data Fabric directory principals and role assignments * * @internal */ directory: DataFabricDirectoryService; }; /** * Access to Tasks service */ get tasks(): TaskService; /** * Access to Orchestrator Processes service */ get processes(): ProcessService; /** * Access to Orchestrator Buckets service */ get buckets(): BucketService; /** * Access to Orchestrator Queues service */ get queues(): QueueService; /** * Access to Orchestrator Assets service */ get assets(): AssetService; } /** * Meta-tag-derived config. Extends {@link PartialUiPathConfig} with * `folderKey`, which is sourced only from `` * (not accepted via the public SDK constructor). */ type MetaTagConfig = PartialUiPathConfig & { folderKey?: string; }; /** * Load configuration from HTML meta tags injected at runtime. * These meta tags are injected by @uipath/coded-apps during build * or by the Apps service during deployment. * * Returns partial config with values found, or null if no meta tags present. */ declare function loadFromMetaTags(): MetaTagConfig | null; declare enum ComparisonOperator { Equals = "Equals", NotEquals = "NotEquals", Greater = "Greater", Less = "Less", GreaterOrEqual = "GreaterOrEqual", LessOrEqual = "LessOrEqual" } declare enum Criticality { Must = "Must", Should = "Should" } declare enum FieldType { Text = "Text", Number = "Number", Date = "Date", Name = "Name", Address = "Address", Keyword = "Keyword", Set = "Set", Boolean = "Boolean", Table = "Table", Internal = "Internal", FieldGroup = "FieldGroup", MonetaryQuantity = "MonetaryQuantity" } declare enum LogicalOperator { AND = "AND", OR = "OR" } declare enum RuleType { Mandatory = "Mandatory", PossibleValues = "PossibleValues", Regex = "Regex", StartsWith = "StartsWith", EndsWith = "EndsWith", FixedLength = "FixedLength", IsNumeric = "IsNumeric", IsDate = "IsDate", IsEmail = "IsEmail", Contains = "Contains", Expression = "Expression", TableExpression = "TableExpression", IsEmpty = "IsEmpty" } interface DataSource { ResourceId?: string | null; ElementFieldId?: string | null; } interface DocumentGroup { Name?: string | null; Categories?: string[] | null; } interface DocumentTaxonomy { DataContractVersion?: string | null; DocumentTypes?: DocumentTypeEntity[] | null; Groups?: DocumentGroup[] | null; SupportedLanguages?: LanguageInfo[] | null; ReportAsExceptionSettings?: ReportAsExceptionSettings; } interface DocumentTypeEntity { DocumentTypeId?: string | null; Group?: string | null; Category?: string | null; Name?: string | null; OptionalUniqueIdentifier?: string | null; TypeField?: TypeField; Fields?: Field[] | null; Metadata?: MetadataEntry[] | null; } interface ExceptionReasonOption { ExceptionReason?: string | null; } interface Field { FieldId?: string | null; FieldName?: string | null; IsMultiValue?: boolean; Type?: FieldType; DeriveFieldsFormat?: string | null; Components?: Field[] | null; SetValues?: string[] | null; Metadata?: MetadataEntry[] | null; RuleSet?: RuleSet; DefaultValue?: string | null; DataSource?: DataSource; } interface LanguageInfo { Name?: string | null; Code?: string | null; } interface MetadataEntry { Key?: string | null; Value?: string | null; } interface ReportAsExceptionSettings { ExceptionReasonOptions?: ExceptionReasonOption[] | null; } interface Rule { Name?: string | null; Type?: RuleType; LogicalOperator?: LogicalOperator; ComparisonOperator?: ComparisonOperator; Expression?: string | null; SetValues?: string[] | null; } interface RuleSet { Criticality?: Criticality; Rules?: Rule[] | null; } interface TypeField { FieldId?: string | null; FieldName?: string | null; } interface FieldValue { Value?: string | null; DerivedValue?: string | null; } interface FieldValueResult { Value?: FieldValue; IsValid?: boolean; Rules?: RuleResult[] | null; } interface RuleResult { Rule?: Rule; IsValid?: boolean; } interface RuleSetResult { FieldId?: string | null; FieldType?: FieldType; Criticality?: Criticality; IsValid?: boolean; Results?: FieldValueResult[] | null; BrokenRules?: Rule[] | null; RowIndex?: number | null; TableFieldId?: string | null; } declare enum MarkupType { Unknown = "Unknown", Circled = "Circled", Underlined = "Underlined", Strikethrough = "Strikethrough" } declare enum ProcessingSource { Unknown = "Unknown", Ocr = "Ocr", Pdf = "Pdf", PlainText = "PlainText", PdfAndOcr = "PdfAndOcr" } declare enum Rotation { None = "None", Rotated90 = "Rotated90", Rotated180 = "Rotated180", Rotated270 = "Rotated270", Other = "Other" } declare enum SectionType { Vertical = "Vertical", Paragraph = "Paragraph", Header = "Header", Footer = "Footer", Table = "Table" } declare enum TextType { Unknown = "Unknown", Text = "Text", Checkbox = "Checkbox", Handwriting = "Handwriting", Barcode = "Barcode", QRcode = "QRcode", Stamp = "Stamp", Logo = "Logo", Circle = "Circle", Underline = "Underline", Cut = "Cut" } declare enum WordGroupType { Sentence = "Sentence", TableCell = "TableCell", TableRowEnd = "TableRowEnd", Heading = "Heading", Other = "Other" } interface DocumentEntity { DocumentId?: string | null; ContentType?: string | null; Length?: number; Pages?: Page[] | null; DocumentMetadata?: Metadata[] | null; } interface Metadata { Key?: string | null; Value?: string | null; } interface Page { PageIndex?: number; Size?: number[]; Sections?: PageSection[] | null; PageMarkups?: PageMarkup[] | null; ProcessingSource?: ProcessingSource; IndexInText?: number; TextLength?: number; SkewAngle?: number; Rotation?: Rotation; PageMetadata?: Metadata[] | null; } interface PageMarkup { Box?: number[]; Polygon?: number[] | null; OcrConfidence?: number; Text?: string | null; MarkupType?: MarkupType; } interface PageSection { IndexInText?: number; Language?: string | null; Length?: number; Rotation?: Rotation; SkewAngle?: number; Type?: SectionType; WordGroups?: WordGroup[] | null; } interface Word { Box?: number[]; Polygon?: number[] | null; IndexInText?: number; OcrConfidence?: number; Text?: string | null; VisualLineNumber?: number; TextType?: TextType; MarkupType?: MarkupType[] | null; } interface WordGroup { IndexInText?: number; Length?: number; Type?: WordGroupType; Words?: Word[] | null; } declare enum ResultsDataSource { Automatic = "Automatic", Manual = "Manual", ManuallyChanged = "ManuallyChanged", Defaulted = "Defaulted", External = "External" } interface ClassificationResult { DocumentTypeId?: string | null; DocumentId?: string | null; Confidence?: number; OcrConfidence?: number; Reference?: ResultsContentReference; DocumentBounds?: ResultsDocumentBounds; ClassifierName?: string | null; } interface ExtractionResult { DocumentId?: string | null; ResultsVersion?: number; ResultsDocument?: ResultsDocument; ExtractorPayloads?: ExtractorPayload[] | null; BusinessRulesResults?: RuleSetResult[] | null; } interface ExtractorPayload { Id?: string | null; Payload?: string | null; SavedPayloadId?: string | null; TaxonomySchemaMapping?: string | null; } interface ResultsContentReference { TextStartIndex?: number; TextLength?: number; Tokens?: ResultsValueTokens[] | null; } interface ResultsDataPoint { FieldId?: string | null; FieldName?: string | null; FieldType?: FieldType; IsMissing?: boolean; DataSource?: ResultsDataSource; Values?: ResultsValue[] | null; DataVersion?: number; OperatorConfirmed?: boolean; ValidatorNotes?: string | null; ValidatorNotesInfo?: string | null; } interface ResultsDerivedField { FieldId?: string | null; Value?: string | null; } interface ResultsDocument { Bounds?: ResultsDocumentBounds; Language?: string | null; DocumentGroup?: string | null; DocumentCategory?: string | null; DocumentTypeId?: string | null; DocumentTypeName?: string | null; DocumentTypeDataVersion?: number; DataVersion?: number; DocumentTypeSource?: ResultsDataSource; DocumentTypeField?: ResultsValue; Fields?: ResultsDataPoint[] | null; Tables?: ResultsTable[] | null; } interface ResultsDocumentBounds { PageCount?: number; PageRange?: string | null; } interface ResultsTable { FieldId?: string | null; FieldName?: string | null; IsMissing?: boolean; DataSource?: ResultsDataSource; DataVersion?: number; OperatorConfirmed?: boolean; Values?: ResultsTableValue[] | null; ValidatorNotes?: string | null; ValidatorNotesInfo?: string | null; } interface ResultsTableCell { RowIndex?: number; ColumnIndex?: number; IsHeader?: boolean; IsMissing?: boolean; OperatorConfirmed?: boolean; DataSource?: ResultsDataSource; DataVersion?: number; Values?: ResultsValue[] | null; } interface ResultsTableColumnInfo { FieldId?: string | null; FieldName?: string | null; FieldType?: FieldType; } interface ResultsTableValue { OperatorConfirmed?: boolean; Confidence?: number; OcrConfidence?: number; Cells?: ResultsTableCell[] | null; ColumnInfo?: ResultsTableColumnInfo[] | null; NumberOfRows?: number; ValidatorNotes?: string | null; ValidatorNotesInfo?: string | null; } interface ResultsValue { Components?: ResultsDataPoint[] | null; Value?: string | null; UnformattedValue?: string | null; Reference?: ResultsContentReference; DerivedFields?: ResultsDerivedField[] | null; Confidence?: number; OperatorConfirmed?: boolean; OcrConfidence?: number; TextType?: TextType; ValidatorNotes?: string | null; ValidatorNotesInfo?: string | null; } interface ResultsValueTokens { TextStartIndex?: number; TextLength?: number; Page?: number; PageWidth?: number; PageHeight?: number; Boxes?: number[][] | null; } /** * Echoed payload returned alongside an exception-report submission. */ interface ExceptionReportSubmitResult { /** Document identifier the exception was reported against. */ DocumentId: string | null; /** Reason captured for the exception. */ Reason: string | null; } /** * Response returned by `submitExceptionReport()`. */ interface SubmitExceptionReportResponse { /** Echo of the submitted exception report. */ SubmitResult?: ExceptionReportSubmitResult; /** Whether the submission was accepted by the server. */ IsSuccessful: boolean; /** Server-supplied error message when {@link SubmitExceptionReportResponse.IsSuccessful} is `false`; empty string on success. */ ErrorMessage: string | null; } /** * Options for `submitExceptionReport()`. */ interface SubmitExceptionReportOptions extends FolderScopedOptions { } /** * Request body for processing extracted document data against a taxonomy. * * Combines the automatic extraction output with any validator-supplied edits so the * server can compute the merged extraction result. */ interface ProcessExtractedDataRequest { /** Extraction result produced by the automatic extractor. */ AutomaticExtractedResults: ExtractionResult; /** Extraction result after human validation/edits. */ ValidatedExtractedResults: ExtractionResult; /** Document taxonomy describing the schema both results conform to. */ Taxonomy: DocumentTaxonomy; } /** * Options for `processExtractedData()`. */ interface ProcessExtractedDataOptions extends FolderScopedOptions { } /** * Service for the Orchestrator Document Understanding module. * * Exposes the validation-flow endpoints used by Document Understanding apps to * submit exception reports against a task and to process extracted data against * a taxonomy. [UiPath Document Understanding Guide](https://docs.uipath.com/document-understanding/automation-cloud/latest) * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { OrchestratorDuModule } from '@uipath/uipath-typescript/orchestrator-du-module'; * * const orchestratorDuModule = new OrchestratorDuModule(sdk); * ``` */ interface OrchestratorDuModuleServiceModel { /** * Submits an exception report for a Document Understanding validation task. * * Records that the document under validation cannot be processed normally and captures * a reason. The server echoes the submitted payload and signals acceptance via * {@link SubmitExceptionReportResponse.IsSuccessful}. * * @param taskId - Identifier of the validation task the exception applies to. * @param documentId - Identifier of the document the exception applies to. * @param reason - Free-text reason the document is being reported as an exception. * @returns Promise resolving to a {@link SubmitExceptionReportResponse} containing the echoed payload and success status. * * @example * ```typescript * import { Tasks, TaskType } from '@uipath/uipath-typescript/tasks'; * * const tasks = new Tasks(sdk); * * // Fetch the Document Validation task to get its documentId * const dvTask = await tasks.getById(, { taskType: TaskType.DocumentValidation }, ); * const documentId = dvTask.data?.documentId as string; * * // Submit an exception report for the validation task * const result = await orchestratorDuModule.submitExceptionReport(, documentId, ''); * * if (result.IsSuccessful) { * console.log('Exception recorded for', result.SubmitResult?.DocumentId); * } * ``` * @internal */ submitExceptionReport(taskId: number, documentId: string, reason: string, options: SubmitExceptionReportOptions): Promise; /** * Processes automatically extracted data against validator-edited data and a taxonomy. * * Sends the automatic extraction result, the validated extraction result, and the * document taxonomy to the server, which merges and normalizes the inputs and returns * the resulting {@link ExtractionResult}. * * @param request - Automatic and validated extraction results plus the document taxonomy. * @returns Promise resolving to the merged {@link ExtractionResult}. * * @example * ```typescript * // Merge automatic and validator-edited extraction results against a taxonomy * const result = await orchestratorDuModule.processExtractedData({ * AutomaticExtractedResults: , * ValidatedExtractedResults: , * Taxonomy: , * }); * * console.log(result.DocumentId, result.ResultsDocument?.DocumentTypeName); * ``` * @internal */ processExtractedData(request: ProcessExtractedDataRequest, options: ProcessExtractedDataOptions): Promise; } /** * Constants for Conversational Agent */ /** * Maps API response fields to SDK field names (API → SDK) * Used when transforming API responses for SDK consumers. * For request transformation (SDK → API), use `transformRequest(data, ConversationMap)`. */ declare const ConversationMap: { [key: string]: string; }; /** * Maps API filter param names (left) to SDK-facing names (right) for the conversation list endpoint. * Used by `getAll` to translate SDK filters to the field names the backend expects. Kept separate * from `ConversationMap` because `label`/`search` would otherwise collide with the `label` field * on create/update payloads. */ declare const ConversationGetAllFilterMap: { [key: string]: string; }; /** * Maps fields for Exchange entity to ensure consistent SDK naming */ declare const ExchangeMap: { [key: string]: string; }; /** * Maps fields for Message entity to ensure consistent SDK naming */ declare const MessageMap: { [key: string]: string; }; /** * Common types for Conversational Agent * Contains IDs, primitives, and utility types used across conversation types. */ /** * Identifies the origin of a message in the conversation. */ declare enum MessageRole { System = "system", User = "user", Assistant = "assistant" } /** * Identifies the type of an interrupt. */ declare enum InterruptType { ToolCallConfirmation = "uipath_cas_tool_call_confirmation" } /** * Base interface for citation sources. */ interface CitationSourceBase { /** * Title for the citation source, suitable for display to users. */ title: string; /** * Label number for the citation source, suitable for display to users * (e.g. [1] for the first unique source, [2] for the second, etc.). */ number: number; } /** * Used when the citation can be rendered as a link. */ interface CitationSourceUrl extends CitationSourceBase { /** * Citation url. */ url: string; } /** * Used when the citation references media, such as a PDF document. */ interface CitationSourceMedia extends CitationSourceBase { /** The mime type of the media. If non-specified, should be discovered through the downloadUrl. */ mimeType?: string; /** Download URL for the media */ downloadUrl?: string; /** The page number for the media, if applicable (e.g. for application/pdf documents) */ pageNumber?: string; } /** * Citation sources can target either an Url or a media (e.g. a pdf document). * Repeated citation sources within a content part are identified by the same title and number. */ type CitationSource = CitationSourceUrl | CitationSourceMedia; /** * JSON compatible primitive type. */ type JSONPrimitive = string | number | boolean | null; /** * JSON compatible value type. */ type JSONValue = JSONPrimitive | Record | any[]; /** * JSON compatible object type. */ type JSONObject = Record; /** * JSON compatible array type. */ type JSONArray = JSONValue[]; /** * An arbitrary JSON serializable object. */ type MetaData = JSONObject; /** * Produces the provided object type with specified properties changed to optional. */ type MakeOptional = Omit & Partial>; /** * Produces the provided object type with specified properties changed to required. */ type MakeRequired = Omit & Required>; /** * Causes typescript to simplify the display of object types created using MakeOptional, MakeRequired, and other utility * types. This doesn't change the effective type, but makes popups in the ide and compile error messages cleaner. */ type Simplify = T extends any[] | Date ? T : { [K in keyof T]: T[K]; } & {}; /** * Inline value - used when a value is small enough to be returned inline with an API result. */ interface InlineValue { inline: T; } /** * External value - used when a value is too large to be returned inline with an API result. */ interface ExternalValue { uri: string; byteCount?: number; } /** * Inline or external value - used when a value can be too large to include inline in input or output data. * If the inline property is set, it contains the full value, otherwise the uri property is set and it contains an uri * from which the data can be downloaded. */ type InlineOrExternalValue = InlineValue | ExternalValue; /** * Input arguments passed in to the execution of the agent on each exchange. The input arguments are * expected to match the input-schema defined in the Agent definition. Currently, only inline values * are supported and the total serialized JSON payload must be less than 4,000 characters. */ type AgentInput = InlineValue; /** * Tool call input value type. */ type ToolCallInputValue = JSONObject; /** * Tool call output value type. */ type ToolCallOutputValue = JSONValue; /** * Core data model types for Conversational Agent REST endpoints * Contains: Conversation, Exchange, Message, ContentPart, ToolCall, etc. */ /** * Represents the order in which items should be sorted. */ declare enum SortOrder { Ascending = "ascending", Descending = "descending" } /** * Represents a citation or reference to an external source within a content part. */ interface Citation { /** * Unique identifier for the citation. */ id: string; /** * Unique identifier for the citation within its content part. */ citationId: string; /** * The offset of the start of the citation target in the content part data. */ offset: number; /** * The length of the citation target in the content part data. */ length: number; /** * The source being referenced by this citation. */ sources: CitationSource[]; /** * Timestamp indicating when the citation was created. */ createdTime: string; /** * Timestamp indicating when the citation was last updated. */ updatedTime: string; } /** * Citation options for input operations (without timestamps). */ interface CitationOptions { citationId: string; offset: number; length: number; sources: CitationSource[]; } /** * Content part data type - can be inline or external. */ type ContentPartData = Simplify>; /** * Represents a single part of message content. */ interface ContentPart { /** * Unique identifier for the content part. */ id: string; /** * Unique identifier for the content part within the message. */ contentPartId: string; /** * The MIME type of the content. */ mimeType: string; /** * The actual content data. */ data: ContentPartData; /** * Array of citations referenced in this content part. */ citations: Citation[]; /** * Indicates whether this content part is a transcript produced by the LLM. */ isTranscript?: boolean; /** * Indicates whether this content part may be incomplete. */ isIncomplete?: boolean; /** * Optional name for the content part. */ name?: string; /** * Timestamp indicating when the content part was created. */ createdTime: string; /** * Timestamp indicating when the content part was last updated. */ updatedTime: string; } /** * Represents the result of a tool call execution. */ interface ToolCallResult { /** * Timestamp indicating when the result was generated. */ timestamp?: string; /** * The value returned by the tool. */ output?: ToolCallOutputValue; /** * field for the tool call output value. */ value?: InlineOrExternalValue; /** * Indicates whether the tool call resulted in an error. */ isError?: boolean; /** * Indicates whether the tool call was cancelled. */ cancelled?: boolean; } /** * Represents a call to an external tool or function within a message. */ interface ToolCall { /** * Unique identifier for the tool call. */ id: string; /** * Unique identifier for the tool call within the message. */ toolCallId: string; /** * The name of the tool being called. */ name: string; /** * Optional input value provided to the tool. */ input?: ToolCallInputValue; /** * Legacy field for tool call input arguments. */ arguments?: InlineOrExternalValue; /** * Timestamp indicating when the tool call was initiated. */ timestamp?: string; /** * Optional output value returned by the tool's execution. */ result?: ToolCallResult; /** * Timestamp indicating when the tool call was created. */ createdTime: string; /** * Timestamp indicating when the tool call was last updated. */ updatedTime: string; } /** * Represents an interrupt within a message. */ interface Interrupt { /** * Unique identifier for the interrupt. */ id: string; /** * Unique identifier for the interrupt within the message. */ interruptId: string; /** * The type of interrupt. */ type: InterruptType; /** * The value associated with the interrupt start event. */ interruptValue: unknown; /** * The value provided to end/resolve the interrupt. */ endValue?: unknown; /** * Timestamp indicating when the interrupt was created. */ createdTime: string; /** * Timestamp indicating when the interrupt was last updated. */ updatedTime: string; } /** * Represents a single message within a conversation exchange. */ interface Message { /** * Unique identifier for the message. */ id: string; /** * Unique identifier for the message within its exchange. */ messageId: string; /** * The role of the message sender. */ role: MessageRole; /** * Contains the message's content parts. */ contentParts: ContentPart[]; /** * Array of tool calls made within this message. */ toolCalls: ToolCall[]; /** * Array of interrupts within this message. */ interrupts: Interrupt[]; /** * Timestamp indicating when the message was created. */ createdTime: string; /** * Timestamp indicating when the message was last updated. */ updatedTime: string; /** * Span identifier for distributed tracing. */ spanId?: string; } /** * Feedback rating type. */ declare enum FeedbackRating { Positive = "positive", Negative = "negative" } /** * Represents a group of related messages (exchange). */ interface Exchange { /** * Unique identifier for the exchange. */ id: string; /** * Identifies the exchange. */ exchangeId: string; /** * Messages in the exchange. */ messages: Message[]; /** * Timestamp indicating when the exchange was created. */ createdTime: string; /** * Timestamp indicating when the exchange was last updated. */ updatedTime: string; /** * Span identifier for distributed tracing. */ spanId?: string; /** * The optional feedback rating given by the user. */ feedbackRating?: FeedbackRating; } /** * Optional configuration options for when the service automatically starts agent job(s) to serve the conversation. * When not provided, service uses recommended default configurations. */ interface ConversationJobStartOverrides { /** * Whether the job(s) should run with the user's identity (RunAsMe). When not provided, service * uses recommended default based on authentication-state and process-runtime. */ runAsMe?: boolean; } /** * Raw response type for conversation operations (without methods). * Represents a conversation between users and AI agents. */ interface RawConversationGetResponse { /** * A globally unique identifier for the conversation. */ id: string; /** * Timestamp indicating when the conversation was created. */ createdTime: string; /** * Timestamp indicating when any conversation field(s) are updated. */ updatedTime: string; /** * Timestamp indicating when the conversation last had activity. */ lastActivityTime: string; /** * The human-readable label or title for the conversation. */ label: string; /** * Whether the conversation label was automatically generated. */ autogenerateLabel: boolean; /** * Identifier of the user who owns or initiated the conversation. */ userId: string; /** * Identifier of the organization. */ orgId: string; /** * Identifier of the tenant within the organization. */ tenantId: string; /** * Identifier of the folder where the conversation is stored. */ folderId: number; /** * Identifier of the agent used for this conversation */ agentId?: number; /** * Trace identifier for distributed tracing. */ traceId: string; /** * Span identifier for distributed tracing. */ spanId?: string; /** * Optional configuration options for when the service automatically starts agent job(s). */ jobStartOverrides?: ConversationJobStartOverrides; /** * Optional job key for conversations that are part of a larger job. */ jobKey?: string; /** * Whether the conversation's job is running locally. */ isLocalJobExecution?: boolean; /** * Optional agent input arguments for the conversation. */ agentInput?: AgentInput; } /** * Event types for Conversational Agent WebSocket protocol */ /** * Identifies how sensitive the LLM should be when detecting the start or end of speech. * * * UNSPECIFIED - the default is HIGH * * HIGH - Will detect the start/end of speech more often. * * LOW - Will detect the start/end of speech less often. */ declare enum InputStreamSpeechSensitivity { Unspecified = "UNSPECIFIED", High = "HIGH", Low = "LOW" } /** * Signals that a content stream was interrupted. */ interface ContentPartInterrupted { } /** * Describes the capabilities of the sender. This type allows custom properties, in addition to the ones defined. */ interface SessionCapabilities { /** * Indicates that a client is prepared to handle events for exchanges initiated by service-role messages. * When set to true, the client will receive events for the service-role message and any assistant-role messages * sent in response to it within the exchange. */ serviceMessageClient?: boolean; /** Allow custom properties */ [key: string]: unknown; } /** * Signals the start of a session. */ interface SessionStartEvent { /** * Indicates the capabilities of the end point that sent the session start event. */ capabilities?: SessionCapabilities; /** * Optional metadata that can be used for any data pertaining to the starting event stream. */ metaData?: MetaData; } /** * Signals the acceptance of the start of a session. */ interface SessionStartedEvent { /** * Indicates the capabilities of the end point that received the session start event. */ capabilities?: SessionCapabilities; } /** * Indicates the end of a session. */ interface SessionEndEvent { /** * Optional metadata that can be used for any data having to do with the completion of the session. */ metaData?: MetaData; } /** * Indicates the service wants the client to end the current session. */ interface SessionEndingEvent { /** * Number of milliseconds before the websocket is closed by the service to force the session to end. */ timeToLiveMS: number; } /** * A client-side tool that the client supports, declared during exchange start * so the server knows which tools to route client-side. * @internal */ interface ClientSideTool { name: string; inputSchema?: JSONValue; outputSchema?: JSONValue; } /** * Signals the start of an exchange of messages within a conversation. */ interface ExchangeStartEvent { /** * Optional value specifying the sequence number of the exchange within the conversation. */ conversationSequence?: number; /** * Optional metadata that can be used for any data pertaining to the starting event stream. */ metadata?: MetaData; /** * The time the exchange started. */ timestamp?: string; /** * Optional list of client-side tools the client supports. The server validates these against the agent's * design-time definitions and forwards them to the runtime so it knows which tools to route client-side. * @internal */ clientSideTools?: ClientSideTool[]; } /** * Signals the end of an exchange of messages within a conversation. */ interface ExchangeEndEvent { /** * Optional metadata that can be used for any data having to do with the completion of the event stream. */ metaData?: MetaData; } /** * Signals the start of a message. */ interface MessageStartEvent { /** * Optional value that provides the sequence of the message within the exchange. */ exchangeSequence?: number; /** * Message timestamp. */ timestamp?: string; /** * Required value that identifies the origin of the message (system, user, or agent). */ role: MessageRole; /** * Optional metadata that can be used for any data pertaining to the starting event stream. */ metaData?: MetaData; } /** * Signals the end of a message. */ interface MessageEndEvent { /** * Optional metadata that can be used for any data having to do with the completion of the event stream. */ metaData?: MetaData; } /** * Content part start event metadata with transcript indicator. */ type ContentPartStartMetaData = MetaData & { /** * Indicates that the content part is transcript produced by the LLM from user voice input. */ isTranscript?: boolean; }; /** * Signals the start of a message content part. */ interface ContentPartStartEvent { /** * Describes the type and format of a content part. */ mimeType: string; /** * Optional metadata that can be used for any data pertaining to the starting event stream. */ metaData?: ContentPartStartMetaData; /** * If present, indicates that the content part's data is stored externally. */ externalValue?: ExternalValue; /** * Optional name for the content part. Typically used for file attachment names. */ name?: string; /** * The time the content part was created. */ timestamp?: string; } /** * Signals the end of a message content part. */ interface ContentPartEndEvent { /** * Optional value that provides the contentPartSequence sent in the last content part chunk sent. */ lastChunkContentPartSequence?: number; /** * Indicates if the content part stream was interrupted. */ interrupted?: ContentPartInterrupted; /** * Optional metadata that can be used for any data having to do with the completion of the event stream. */ metaData?: MetaData; } /** * Represents the start of an error condition. */ interface ErrorStartEvent { /** * A message that can be displayed to the user. */ message: string; /** * An optional property that contains error related details. */ details?: JSONValue; } /** * Represents the end of an error condition. */ interface ErrorEndEvent { } /** * Encapsulates sub-events that represent the start and end of an error condition. */ interface ErrorEvent { /** * An identifier for the error. */ errorId: string; /** * If present, indicates the start of an error condition. */ startError?: ErrorStartEvent; /** * If present, indicates the end of an error condition. */ endError?: ErrorEndEvent; } /** * Indicates the start of a citation target in the stream of content part chunks. */ interface CitationStartEvent { } /** * Indicates the end of a citation target in the stream of content part chunks. */ interface CitationEndEvent { /** * Provides data concerning the citation sources. */ sources: CitationSource[]; } /** * Encapsulates sub-events related to citations. */ interface CitationEvent { /** * Identifies a set of citation sources. */ citationId: string; /** * Indicates the start of a citation target. */ startCitation?: CitationStartEvent; /** * Indicates the end of a citation target. */ endCitation?: CitationEndEvent; /** * Sent by the service to indicate an error condition impacting a citation. */ citationError?: ErrorEvent; } /** * Contains a chunk of a message content part. */ interface ContentPartChunkEvent { /** * Content part data. */ data?: string; /** * Sub-event for attaching citations to content chunks. */ citation?: CitationEvent; } /** * Signals the start of an input stream. */ interface AsyncInputStreamStartEvent { /** * Describes the type of data sent over the input stream. */ mimeType: string; /** * Determines how sensitive the LLM should be in detecting the start of speech. */ startOfSpeechSensitivity?: InputStreamSpeechSensitivity; /** * Determines how sensitive the LLM should be in detecting the end of speech. */ endOfSpeechSensitivity?: InputStreamSpeechSensitivity; /** * The required duration of detected speech before start-of-speech is committed. */ prefixPaddingMs?: number; /** * The required duration of detected non-speech before end-of-speech is committed. */ silenceDurationMs?: number; /** * Optional metadata that can be used for any data pertaining to the starting event stream. */ metaData?: MetaData; } /** * Signals the end of a cross exchange input stream. */ interface AsyncInputStreamEndEvent { /** * Optional metadata that can be used for any data having to do with the completion of the event stream. */ metaData?: MetaData; /** * Optional value that provides the contentPartSequence value in the last content part chunk sent. */ lastChunkContentPartSequence?: number; } /** * Async input stream chunk event. */ interface AsyncInputStreamChunkEvent { data: string; } /** * Signals the start of a tool call. */ interface ToolCallStartEvent { /** * Identifies the tool that is to be called. */ toolName: string; /** * The time the tool call was made. */ timestamp?: string; /** * Optional input value provided to the tool when executed. */ input?: ToolCallInputValue; /** * Optional metadata pertaining to the tool call. */ metaData?: MetaData; /** * Indicates that the tool call requires user confirmation before execution. * When true, the client should render a confirmation UI and respond with a * `confirmToolCall` event on the same tool call. */ requireConfirmation?: boolean; /** * JSON schema describing the tool's input parameters. Present when * `requireConfirmation` is true so the client can render an editable form. */ inputSchema?: JSONValue; /** * Output schema — used by the client to render the result form for client-side tools. * @internal */ outputSchema?: JSONValue; /** * Indicates this tool call should be executed client-side rather than server-side. * @internal */ isClientSideTool?: boolean; } /** * Sent by the client to approve or reject a tool call that was emitted with * `requireConfirmation: true`. Carries the user's decision and, when approved, * the (possibly edited) input the tool should execute with. * * `input` is required when `approved` is `true` and optional when `approved` * is `false`. The discriminated union enforces this at compile time so * `{ approved: true }` (no `input`) is a type error. */ type ToolCallConfirmationEvent = { approved: true; input: JSONValue; } | { approved: false; input?: JSONValue; }; /** * Signals the end of a tool call. */ interface ToolCallEndEvent { /** * The time the result was generated. */ timestamp?: string; /** * Optional output value returned by the tool's execution. */ output?: ToolCallOutputValue; /** * Indicates if the tool call resulted in an error. */ isError?: boolean; /** * Indicates if the tool call was canceled before the result was generated. */ cancelled?: boolean; /** * Metadata pertaining to the tool call's execution or result. */ metaData?: MetaData; } /** * Signals to the client that the tool is about to be executed. Emitted in all scenarios * (server-side and client-side tools). For client-side tools, the client should begin * executing its registered handler upon receiving this event. * @internal */ interface ExecutingToolCallEvent { /** * The time the tool call began executing. */ timestamp?: string; /** The final tool input, reflecting any modifications made during tool-call confirmation. */ input?: ToolCallInputValue; } /** * Allows additional events to be sent in the context of the enclosing event stream. */ interface MetaEvent { [key: string]: unknown; } /** * Indicates the update of the conversation label. */ interface LabelUpdatedEvent { /** * The new label for the conversation. */ label: string; /** * Whether the label was autogenerated by the system, or manually updated through the API. */ autogenerated: boolean; } /** * Encapsulates the data related to a tool call event. */ interface ToolCallEvent { /** * Identifies the tool call. */ toolCallId: string; /** * Signals the start of a tool call. */ startToolCall?: ToolCallStartEvent; /** * Signals the end of a tool call. */ endToolCall?: ToolCallEndEvent; /** * Signals the user's approve/reject decision for a tool call that was * emitted with `requireConfirmation: true`. */ confirmToolCall?: ToolCallConfirmationEvent; /** * Signals that the tool is about to be executed. For client-side tools, * the client should begin executing its handler upon receiving this event. * @internal */ executingToolCall?: ExecutingToolCallEvent; /** * Allows additional events to be sent in the context of the enclosing event stream. */ metaEvent?: MetaEvent; /** * Sent by the service to indicate an error condition impacting a tool call. */ toolCallError?: ErrorEvent; } /** * Schema for tool call confirmation interrupt value. * * @deprecated Tool call confirmation now travels on {@link ToolCallStartEvent} via * `requireConfirmation: true` / `inputSchema` and is responded to with * {@link ToolCallConfirmationEvent}. This shape is retained for agents on the legacy * runtime that still emit confirmations as interrupts. */ interface ToolCallConfirmationValue { /** * The ID of the tool call being confirmed. */ toolCallId: string; /** * The name of the tool to be called. */ toolName: string; /** * The input schema for the tool call. */ inputSchema: JSONValue; /** * The input value for the tool call. */ inputValue?: JSONValue; } /** * Schema for tool call confirmation end value. * * @deprecated Confirmation responses now use {@link ToolCallConfirmationEvent} (sent via * {@link ToolCallStream.sendToolCallConfirm}). This shape is retained for agents on the * legacy runtime that consume confirmations through the interrupt-end channel. */ interface ToolCallConfirmationEndValue { /** * Whether the tool call was approved. */ approved: boolean; /** * Modified input parameters for the tool call. */ input?: JSONValue; } /** * Known interrupt start event for tool call confirmation. * * @deprecated Emitted only by agents on the legacy runtime. Agents on the current runtime * express confirmation as `requireConfirmation: true` on {@link ToolCallStartEvent}, with * the client responding via {@link ToolCallConfirmationEvent} (`confirmToolCall` on * {@link ToolCallEvent}). */ interface ToolCallConfirmationInterruptStartEvent { /** * Tool call confirmation interrupt type. */ type: typeof InterruptType.ToolCallConfirmation; /** * The tool call confirmation data. */ value: ToolCallConfirmationValue; } /** * Generic interrupt start event for custom interrupts. */ interface GenericInterruptStartEvent { /** * The type of the interrupt. */ type: string; /** * The value of the interrupt. */ value: unknown; } /** * Signals the start of an interrupt - a pause point where the agent needs external input. */ type InterruptStartEvent = ToolCallConfirmationInterruptStartEvent | GenericInterruptStartEvent; /** * Signals the interrupt end event with the provided value. */ type InterruptEndEvent = Record; /** * Encapsulates interrupt-related events within a message. */ interface InterruptEvent { /** * Identifies the interrupt. */ interruptId: string; /** * Signals the start of an interrupt. */ startInterrupt?: InterruptStartEvent; /** * Signals the end of an interrupt. */ endInterrupt?: InterruptEndEvent; } /** * Encapsulates sub-events related to message content parts. */ interface ContentPartEvent { /** * Identifies the content part. */ contentPartId: string; /** * Optional value that signals the start of message content. */ startContentPart?: ContentPartStartEvent; /** * Optional value that signals the end of message content. */ endContentPart?: ContentPartEndEvent; /** * Optional content part chunk sub-event. */ chunk?: ContentPartChunkEvent; /** * Allows additional events to be sent in the context of the enclosing event stream. */ metaEvent?: MetaEvent; /** * Sent by the service to indicate an error condition impacting a content part. */ contentPartError?: ErrorEvent; } /** * Encapsulates sub-events related to a message within an exchange. */ interface MessageEvent { /** * Identifies a message. */ messageId: string; /** * Optional value that signals that start of a message. */ startMessage?: MessageStartEvent; /** * Optional value that signals the end of a message. */ endMessage?: MessageEndEvent; /** * Optional content part sub-event. */ contentPart?: ContentPartEvent; /** * Optional tool call sub-event. */ toolCall?: ToolCallEvent; /** * Optional interrupt sub-event for human-in-the-loop patterns. */ interrupt?: InterruptEvent; /** * Allows additional events to be sent in the context of the enclosing event stream. */ metaEvent?: MetaEvent; /** * Sent by the service to indicate an error condition impacting a message. */ messageError?: ErrorEvent; } /** * Encapsulates events related to a cross exchange input stream for the conversation. */ interface AsyncInputStreamEvent { /** * Identifies the input stream. */ streamId: string; /** * Optional value that signals the start of an input stream. */ startAsyncInputStream?: AsyncInputStreamStartEvent; /** * Optional value that signals the end of an input stream. */ endAsyncInputStream?: AsyncInputStreamEndEvent; /** * Optional input stream chunk sub-event. */ chunk?: AsyncInputStreamChunkEvent; /** * Allows additional events to be sent in the context of the enclosing event stream. */ metaEvent?: MetaEvent; /** * Sent by the service to indicate an error condition impacting an async input stream. */ asyncInputStreamError?: ErrorEvent; } /** * An event that applies to a single exchange of messages within a conversation. */ interface ExchangeEvent { /** * Identifies the exchange. */ exchangeId: string; /** * Optional value that signals the start of an exchange. */ startExchange?: ExchangeStartEvent; /** * Optional value that signals the end of an exchange. */ endExchange?: ExchangeEndEvent; /** * Optional message sub-events related to the exchange. */ message?: MessageEvent; /** * Allows additional events to be sent in the context of the enclosing event stream. */ metaEvent?: MetaEvent; /** * Sent by the service to indicate an error condition impacting an exchange. */ exchangeError?: ErrorEvent; } /** * The ConversationEvent type represents an event in a conversation with an LLM. */ interface ConversationEvent { /** * A globally unique identifier for conversation to which the other sub-event and data properties apply. */ conversationId: string; /** * Signals the start of session for a conversation. */ startSession?: SessionStartEvent; /** * Sent in response to a SessionStartEvent to signal the acceptance of the session. */ sessionStarted?: SessionStartedEvent; /** * Sent by the service when the client needs to end the current session. */ sessionEnding?: SessionEndingEvent; /** * Signals the end of a session for a conversation. */ endSession?: SessionEndEvent; /** * Optional exchange sub-event. */ exchange?: ExchangeEvent; /** * Optional input stream sub-events. */ asyncInputStream?: AsyncInputStreamEvent; /** * Optional async tool call sub-event. */ asyncToolCall?: ToolCallEvent; /** * Indicates that the conversation's label has been updated. */ labelUpdated?: LabelUpdatedEvent; /** * Allows additional events to be sent in the context of the enclosing event stream. */ metaEvent?: MetaEvent; /** * Sent by the service to indicate an error condition impacting a conversation. */ conversationError?: ErrorEvent; } /** * Content Part Stream Types * * Defines the public API for interacting with streaming content parts * within a message. Content parts represent text, audio, images, etc. */ /** * Error encountered during citation processing */ type CitationError = { citationId: string; errorType: CitationErrorType; }; /** * Types of citation processing errors */ declare enum CitationErrorType { CitationNotEnded = "CitationNotEnded", CitationNotStarted = "CitationNotStarted" } /** * Aggregated data for a completed content part * * Contains the full buffered text, citations, and metadata * available after a content part stream has ended. */ type CompletedContentPart = ContentPartStartEvent & ContentPartEndEvent & { contentPartId: string; data: string; citations: CitationOptions[]; citationErrors: CitationError[]; }; /** * 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. * * @example Streaming markdown content * ```typescript * message.onContentPartStart((part) => { * if (part.isMarkdown) { * part.onChunk((chunk) => { * process.stdout.write(chunk.data ?? ''); * }); * } * }); * ``` * * @example Handling different content types * ```typescript * 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 ?? '')); * } * }); * ``` * * @example Getting complete content with citations (buffered) * ```typescript * 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); * } * }); * }); * ``` * * @example Using the content part completed handler at the message level * ```typescript * message.onContentPartCompleted((completed) => { * console.log(`[${completed.mimeType}] ${completed.data}`); * }); * ``` */ interface ContentPartStream { /** Unique identifier for this content part */ readonly contentPartId: string; /** The MIME type of this content part, or undefined if start event not yet received */ readonly mimeType: string | undefined; /** Whether this content part is plain text. Matches `text/plain`. */ readonly isText: boolean; /** Whether this content part is markdown. Matches `text/markdown`. */ readonly isMarkdown: boolean; /** Whether this content part is HTML. Matches `text/html`. */ readonly isHtml: boolean; /** Whether this content part is audio content */ readonly isAudio: boolean; /** Whether this content part is an image */ readonly isImage: boolean; /** Whether this content part is a transcript (from speech-to-text) */ readonly isTranscript: boolean; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: ContentPartStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: MakeRequired; /** Whether this content part has ended */ readonly ended: boolean; /** * Registers a handler for error start events * * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler * * @example Content part error handling * ```typescript * part.onErrorStart((error) => { * console.error(`Content part error: ${error.message}`); * }); * ``` */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => 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.). * * @param cb - Callback receiving each chunk * @returns Cleanup function to remove the handler * * @example Streaming text output * ```typescript * part.onChunk((chunk) => { * process.stdout.write(chunk.data ?? ''); * }); * ``` */ onChunk(cb: (chunk: ContentPartChunkEvent) => void): () => void; /** * Registers a handler for content part end events * * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler * * @example Tracking content part lifecycle * ```typescript * part.onContentPartEnd((endEvent) => { * console.log('Content part finished'); * }); * ``` */ onContentPartEnd(cb: (endContentPart: ContentPartEndEvent) => 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. * * @param cb - Callback receiving the completed content part data * * @example Getting buffered content with citation data * ```typescript * 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); * } * }); * ``` */ onCompleted(cb: (completedContentPart: CompletedContentPart) => void): void; /** * Sends a content part chunk * * @param chunk - Chunk data to send * * @example Sending text chunks * ```typescript * part.sendChunk({ data: 'Hello ' }); * part.sendChunk({ data: 'world!' }); * ``` */ sendChunk(chunk: ContentPartChunkEvent): void; /** * Ends the content part stream * * @param endContentPart - Optional end event data * * @example Ending a content part * ```typescript * part.sendContentPartEnd(); * ``` */ sendContentPartEnd(endContentPart?: ContentPartEndEvent): void; /** * Sends an error start event for this content part * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this content part * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this content part * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Sends a chunk that starts a citation range * * Marks the beginning of a cited passage. All subsequent chunks * until `sendChunkWithCitationEnd` are considered part of this citation. * * @param chunk - Chunk data with citation ID * @internal */ sendChunkWithCitationStart(chunk: Omit & { citationId: string; }): void; /** * Sends a chunk that ends a citation range * * Marks the end of a cited passage and provides the citation sources. * * @param chunk - Chunk data with citation ID and sources * @internal */ sendChunkWithCitationEnd(chunk: Omit & { citationId: string; sources: CitationSource[]; }): void; /** * Sends a chunk that is a complete citation (start and end in one) * * Use this for inline citations where the entire cited text is in a single chunk. * * @param chunk - Chunk data with citation ID and sources * @internal */ sendChunkWithCitation(chunk: Omit & { citationId: string; sources: CitationSource[]; }): void; /** * Emits a raw content part event * @param contentPartEvent - The event to emit (contentPartId is added automatically) * @internal */ emit(contentPartEvent: Omit): void; /** * Returns a string representation of this content part * @internal */ toString(): string; } /** * Consumer-facing interface for ToolCallEventHelper * * Defines the public API for interacting with tool call events * within a message. Tool calls represent external tool invocations * made by the assistant during a conversation. */ /** * Aggregated data for a completed tool call * * Contains the merged start and end event data * available after a tool call has ended. */ type CompletedToolCall = ToolCallStartEvent & ToolCallEndEvent & { toolCallId: string; }; /** * 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). * * @example Listening for tool call results * ```typescript * message.onToolCallStart((toolCall) => { * console.log(`Tool: ${toolCall.startEvent.toolName}`); * toolCall.onToolCallEnd((endEvent) => { * console.log('Tool call completed:', endEvent.output); * }); * }); * ``` * * @example Parsing tool call input and output * ```typescript * 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); * }); * }); * ``` * * @example Responding to a tool call (agent-side) * ```typescript * 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) * }); * }); * ``` * * @example Migrating from legacy interrupt-based confirmation * ```typescript * // 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 }); * } * }); * ``` * * @example Handling client-side tool execution * ```typescript * 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 }); * }); * }); * ``` */ interface ToolCallStream { /** Unique identifier for this tool call */ readonly toolCallId: string; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: ToolCallStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: MakeRequired; /** Whether this tool call has ended */ readonly ended: boolean; /** * Registers a handler for error start events * * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler * * @example Tool call error handling * ```typescript * toolCall.onErrorStart((error) => { * console.error(`Tool call error: ${error.message}`); * }); * ``` */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => void): () => void; /** * Registers a handler for tool call end events * * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler * * @example Handling tool call completion * ```typescript * toolCall.onToolCallEnd((endEvent) => { * console.log('Output:', endEvent.output); * }); * ``` */ onToolCallEnd(cb: (endToolCall: ToolCallEndEvent) => 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. * * @param callback - Callback receiving the confirmation event * @returns Cleanup function to remove the handler * * @example Handling a confirmation response (agent-side) * ```typescript * toolCall.onToolCallConfirm(({ approved, input }) => { * if (approved) executeTool(toolCall.startEvent.toolName, input); * else cancelToolCall(); * }); * ``` */ onToolCallConfirm(callback: (confirmToolCall: ToolCallConfirmationEvent) => void): () => void; /** * Registers a handler for executingToolCall events. Fired when the tool is about * to be executed. For client-side tools, the client should begin executing its * handler upon receiving this event. * * @param cb - Callback receiving the executing event * @returns Cleanup function to remove the handler * * @example Handling client-side tool execution * ```typescript * toolCall.onExecutingToolCall(async (event) => { * const result = await executeLocally(toolCall.startEvent.toolName, event.input); * toolCall.sendToolCallEnd({ output: result }); * }); * ``` * @internal */ onExecutingToolCall(cb: (event: ExecutingToolCallEvent) => void): () => void; /** * Ends the tool call * * @param endToolCall - Optional end event data * * @example Completing a tool call with output * ```typescript * toolCall.sendToolCallEnd({ * output: JSON.stringify({ temperature: 18, condition: 'cloudy' }) * }); * ``` */ sendToolCallEnd(endToolCall?: ToolCallEndEvent): 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. * * @param confirmToolCall - The user's decision and (when approved) the * possibly-edited input the tool should execute with * * @example Approving a tool call * ```typescript * toolCall.sendToolCallConfirm({ approved: true, input: editedInput }); * ``` * * @example Rejecting a tool call * ```typescript * toolCall.sendToolCallConfirm({ approved: false }); * ``` */ sendToolCallConfirm(confirmToolCall: ToolCallConfirmationEvent): void; /** * Sends an error start event for this tool call * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this tool call * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this tool call * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Emits a raw tool call event * @param toolCallEvent - The event to emit (toolCallId is added automatically) * @internal */ emit(toolCallEvent: Omit): void; /** * Returns a string representation of this tool call * @internal */ toString(): string; } /** * Consumer-facing model for async tool call event helpers. * * Async tool calls operate at the session level (not within a single message) * and can span across multiple exchanges. They are used for long-running * tool invocations that need to persist beyond a single request-response cycle. * * Unlike regular {@link ToolCallStream} which live inside a message, * async tool calls are managed directly on the {@link SessionStream}. * * @example Listening for async tool call completion * ```typescript * session.onAsyncToolCallStart((toolCall) => { * console.log(`Async tool started: ${toolCall.startEvent.toolName}`); * toolCall.onToolCallEnd((endEvent) => { * console.log('Async tool completed:', endEvent.output); * }); * }); * ``` * * @example Starting and completing an async tool call * ```typescript * // Start a long-running analysis * const toolCall = session.startAsyncToolCall({ * toolName: 'document-analysis', * input: JSON.stringify({ documentId: 'doc-123' }) * }); * * // ... perform the analysis across multiple exchanges ... * * // Complete when done * toolCall.sendToolCallEnd({ * output: JSON.stringify({ summary: 'Analysis complete', pages: 42 }) * }); * ``` * * @example Handling errors on async tool calls * ```typescript * session.onAsyncToolCallStart((toolCall) => { * toolCall.onErrorStart((error) => { * console.error(`Async tool error: ${error.message}`); * }); * }); * ``` */ interface AsyncToolCallStream { /** Unique identifier for this async tool call */ readonly toolCallId: string; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: ToolCallStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: MakeRequired; /** Whether this async tool call has ended */ readonly ended: boolean; /** * Registers a handler for error start events * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => void): () => void; /** * Registers a handler for tool call end events * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler */ onToolCallEnd(cb: (endToolCall: ToolCallEndEvent) => void): () => void; /** * Ends the async tool call * @param endToolCall - Optional end event data including output */ sendToolCallEnd(endToolCall?: ToolCallEndEvent): void; /** * Sends an error start event for this async tool call * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this async tool call * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this async tool call * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Emits a raw tool call event * @param toolCallEvent - The event to emit (toolCallId is added automatically) * @internal */ emit(toolCallEvent: Omit): void; /** * Returns a string representation of this async tool call * @internal */ toString(): string; } /** * Consumer-facing interface for AsyncInputStreamEventHelper * * Defines the public API for interacting with async input streams * at the session level. Async input streams are used for streaming * audio or other media data to the agent. */ /** * Consumer-facing model for async input stream event helpers. * * Async input streams operate at the session level and are used for * streaming audio or other media data to the agent in real-time. * They persist across exchanges, making them ideal for continuous * audio input from a microphone. * * Unlike content parts (which carry agent output), async input streams * carry user input to the agent via the {@link SessionStream}. * * @example Streaming microphone audio * ```typescript * const stream = session.startAsyncInputStream({ * mimeType: 'audio/pcm;rate=24000' * }); * * // Stream microphone PCM data * microphone.on('data', (pcmData: string) => { * stream.sendChunk({ data: pcmData }); * }); * * // End when user stops speaking * microphone.on('end', () => { * stream.sendAsyncInputStreamEnd(); * }); * ``` * * @example Receiving audio input (agent-side) * ```typescript * session.onInputStreamStart((inputStream) => { * console.log(`Receiving audio: ${inputStream.startEvent.mimeType}`); * * inputStream.onChunk((chunk) => { * // Process incoming audio data * audioProcessor.process(chunk.data); * }); * * inputStream.onAsyncInputStreamEnd(() => { * console.log('Audio stream ended'); * }); * }); * ``` * * @example Handling stream errors * ```typescript * const stream = session.startAsyncInputStream({ * mimeType: 'audio/pcm;rate=24000' * }); * * stream.onErrorStart((error) => { * console.error(`Stream error: ${error.message}`); * // Clean up microphone resources * microphone.stop(); * }); * ``` */ interface AsyncInputStream { /** Unique identifier for this input stream */ readonly streamId: string; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: AsyncInputStreamStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: AsyncInputStreamStartEvent; /** Whether this input stream has ended */ readonly ended: boolean; /** * Registers a handler for error start events * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => void): () => void; /** * Sends a stream chunk * @param chunk - Chunk data to send (e.g., audio data) */ sendChunk(chunk: AsyncInputStreamChunkEvent): void; /** * Registers a handler for stream chunks * @param cb - Callback receiving each chunk * @returns Cleanup function to remove the handler */ onChunk(cb: (chunk: AsyncInputStreamChunkEvent) => void): () => void; /** * Ends the input stream * @param endAsyncInputStream - Optional end event data */ sendAsyncInputStreamEnd(endAsyncInputStream?: AsyncInputStreamEndEvent): void; /** * Registers a handler for stream end events * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler */ onAsyncInputStreamEnd(cb: (endAsyncInputStream: AsyncInputStreamEndEvent) => void): () => void; /** * Sends an error start event for this stream * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this stream * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this stream * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Emits a raw async input stream event * @param streamEvent - The event to emit (streamId is added automatically) * @internal */ emit(streamEvent: Omit): void; /** * Returns a string representation of this input stream * @internal */ toString(): string; } /** * Consumer-facing interface for MessageEventHelper * * Defines the public API for interacting with message events * within an exchange. Messages represent individual turns from * users, assistants, or the system. */ /** * Aggregated data for a completed message * * Contains all content parts, tool calls, and metadata * available after a message stream has ended. */ type CompletedMessage = Simplify<{ messageId: string; contentParts: Array; toolCalls: Array; } & Partial & MessageEndEvent>; /** * 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. * * @example Streaming text with real-time output * ```typescript * exchange.onMessageStart((message) => { * if (message.isAssistant) { * message.onContentPartStart((part) => { * if (part.isMarkdown) { * part.onChunk((chunk) => { * process.stdout.write(chunk.data ?? ''); * }); * } * }); * } * }); * ``` * * @example Handling tool calls with confirmation interrupts * ```typescript * 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 }); * } * }); * } * }); * ``` * * @example Getting the complete message at once (buffered) * ```typescript * 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}`); * } * }); * } * }); * ``` * * @example Sending a content part with convenience method * ```typescript * const message = exchange.startMessage({ role: MessageRole.User }); * await message.sendContentPart({ data: 'Hello!', mimeType: 'text/plain' }); * message.sendMessageEnd(); * ``` */ interface MessageStream { /** Unique identifier for this message */ readonly messageId: string; /** The role of this message sender, or undefined if start event not yet received */ readonly role: MessageRole | undefined; /** Whether this message is from the user */ readonly isUser: boolean; /** Whether this message is from the assistant */ readonly isAssistant: boolean; /** Whether this message is a system message */ readonly isSystem: boolean; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: MessageStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: MakeRequired; /** Whether this message has ended */ readonly ended: boolean; /** * Registers a handler for error start events * * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler * * @example Message-level error handling * ```typescript * message.onErrorStart((error) => { * console.error(`Message error [${error.errorId}]: ${error.message}`); * }); * ``` */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => 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. * * @param cb - Callback receiving each new content part * @returns Cleanup function to remove the handler * * @example Streaming text and handling different content types * ```typescript * 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 ?? '')); * } * }); * ``` */ onContentPartStart(cb: (contentPart: ContentPartStream) => 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. * * @param cb - Callback receiving each new tool call * @returns Cleanup function to remove the handler * * @example Streaming tool call events * ```typescript * 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 ?? '{}')); * }); * }); * ``` */ onToolCallStart(cb: (toolCall: ToolCallStream) => void): () => void; /** * Registers a handler for message end events * * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler * * @example Tracking message lifecycle * ```typescript * message.onMessageEnd((endEvent) => { * console.log('Message ended'); * }); * ``` */ onMessageEnd(cb: (endMessage: MessageEndEvent) => 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. * * @param cb - Callback receiving the completed content part data * * @example Getting completed content parts with citations * ```typescript * 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}`); * } * }); * ``` */ onContentPartCompleted(cb: (completedContentPart: CompletedContentPart) => 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. * * @param cb - Callback receiving the completed tool call data * * @example Getting completed tool calls * ```typescript * message.onToolCallCompleted((toolCall) => { * console.log(`Tool: ${toolCall.toolName}`); * console.log(`Input: ${toolCall.input}`); * console.log(`Output: ${toolCall.output}`); * }); * ``` */ onToolCallCompleted(cb: (completedToolCall: 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. * * @param cb - Callback receiving the completed message data * * @example Getting the full buffered message * ```typescript * 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); * }); * ``` */ onCompleted(cb: (completedMessage: CompletedMessage) => 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. * * @param cb - Callback receiving the interrupt ID and start event * @returns Cleanup function to remove the handler * * @example Handling tool call confirmation * ```typescript * message.onInterruptStart(({ interruptId, startEvent }) => { * if (startEvent.type === 'uipath_cas_tool_call_confirmation') { * // Show confirmation UI, then respond * message.sendInterruptEnd(interruptId, { approved: true }); * } * }); * ``` */ onInterruptStart(cb: (interrupt: { interruptId: string; startEvent: InterruptStartEvent; }) => void): () => void; /** * Registers a handler for interrupt end events * * @param cb - Callback receiving the interrupt ID and end event * @returns Cleanup function to remove the handler * * @example Tracking interrupt resolution * ```typescript * message.onInterruptEnd(({ interruptId, endEvent }) => { * console.log(`Interrupt ${interruptId} resolved`); * }); * ``` */ onInterruptEnd(cb: (interrupt: { interruptId: string; endEvent: InterruptEndEvent; }) => void): () => void; /** * Sends an interrupt end event to resolve a pending interrupt * * Call this to respond to an interrupt received via onInterruptStart. * * @param interruptId - The interrupt ID to respond to * @param endInterrupt - The response data (e.g., approval for tool call confirmation) * * @example Approving a tool call confirmation * ```typescript * message.sendInterruptEnd(interruptId, { approved: true }); * ``` */ sendInterruptEnd(interruptId: string, endInterrupt: InterruptEndEvent): 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`. * * @param callback - Callback receiving the toolCallId and the confirmation event * @returns Cleanup function to remove the handler * * @example Handling a tool-call confirmation response * ```typescript * message.onToolCallConfirm(({ toolCallId, confirmEvent }) => { * if (confirmEvent.approved) executeTool(toolCallId, confirmEvent.input); * else cancelToolCall(toolCallId); * }); * ``` */ onToolCallConfirm(callback: (args: { toolCallId: string; confirmEvent: ToolCallConfirmationEvent; }) => void): () => void; /** * Starts a new content part stream in this message * * Use this for streaming content in chunks. For sending * complete content in one call, prefer {@link sendContentPart}. * * @param args - Content part start options including mime type * @returns The content part stream for sending chunks * * @example Streaming text content in chunks * ```typescript * const part = message.startContentPart({ mimeType: 'text/markdown' }); * part.sendChunk({ data: '# Hello\n' }); * part.sendChunk({ data: 'This is **markdown** content.' }); * part.sendContentPartEnd(); * ``` */ startContentPart(args: { contentPartId?: string; } & ContentPartStartEvent): ContentPartStream; /** * 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". * * @param args - Content part data and optional mime type * * @example Sending a text content part * ```typescript * await message.sendContentPart({ data: 'Hello world!' }); * ``` * * @example Sending with explicit mime type * ```typescript * await message.sendContentPart({ * data: 'Plain text content', * mimeType: 'text/plain' * }); * ``` */ sendContentPart(args: { data?: string; mimeType?: string; }): Promise; /** * Iterator over all active content parts in this message */ readonly contentParts: Iterable; /** * Retrieves a content part by ID * @param contentPartId - The content part ID to look up * @returns The content part stream, or undefined if not found */ getContentPart(contentPartId: string): ContentPartStream | undefined; /** * Starts a new tool call in this message * * @param args - Tool call start options including tool name * @returns The tool call stream for managing the tool call lifecycle * * @example Creating and completing a tool call * ```typescript * const toolCall = message.startToolCall({ * toolName: 'get-weather', * input: JSON.stringify({ city: 'London' }) * }); * toolCall.sendToolCallEnd({ * output: JSON.stringify({ temperature: 18, condition: 'cloudy' }) * }); * ``` */ startToolCall(args: { toolCallId?: string; } & ToolCallStartEvent): ToolCallStream; /** * Iterator over all active tool calls in this message */ readonly toolCalls: Iterable; /** * Retrieves a tool call by ID * @param toolCallId - The tool call ID to look up * @returns The tool call stream, or undefined if not found */ getToolCall(toolCallId: string): ToolCallStream | undefined; /** * Ends the message * * @param endMessage - Optional end event data * * @example Ending a message * ```typescript * message.sendMessageEnd(); * ``` */ sendMessageEnd(endMessage?: MessageEndEvent): void; /** * Sends an error start event for this message * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this message * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this message * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Emits a raw message event * @param messageEvent - The event to emit (messageId is added automatically) * @internal */ emit(messageEvent: Omit): void; /** * Sends an interrupt start event * @param interruptId - The interrupt ID * @param startInterrupt - The interrupt start event data * @internal */ sendInterrupt(interruptId: string, startInterrupt: InterruptStartEvent): void; /** * Returns a string representation of this message * @internal */ toString(): string; } /** * Consumer-facing interface for ExchangeEventHelper * * Defines the public API for interacting with exchange events * within a session. Exchanges represent request-response pairs * containing user and assistant messages. */ /** * 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. * * @example Streaming assistant response * ```typescript * session.onExchangeStart((exchange) => { * exchange.onMessageStart((message) => { * if (message.isAssistant) { * message.onContentPartStart((part) => { * if (part.isMarkdown) { * part.onChunk((chunk) => { * process.stdout.write(chunk.data ?? ''); * }); * } * }); * } * }); * }); * ``` * * @example Getting the completed message at once (no streaming) * ```typescript * 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}`); * } * }); * }); * ``` * * @example Sending a user message with convenience method * ```typescript * // 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 * }); * }); * ``` * * @example Sending a user message with streaming parts * ```typescript * // 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(); * }); * ``` */ interface ExchangeStream { /** Unique identifier for this exchange */ readonly exchangeId: string; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: ExchangeStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: MakeRequired; /** Whether this exchange has ended */ readonly ended: boolean; /** * Registers a handler for error start events * * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler * * @example Exchange-level error handling * ```typescript * exchange.onErrorStart((error) => { * console.error(`Exchange error [${error.errorId}]: ${error.message}`); * }); * ``` */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => 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. * * @param cb - Callback receiving each new message * @returns Cleanup function to remove the handler * * @example Filtering by message role * ```typescript * exchange.onMessageStart((message) => { * if (message.isAssistant) { * message.onContentPartStart((part) => { * if (part.isMarkdown) { * part.onChunk((chunk) => process.stdout.write(chunk.data ?? '')); * } * }); * } * }); * ``` */ onMessageStart(cb: (message: MessageStream) => void): () => void; /** * Registers a handler for exchange end events * * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler * * @example Tracking exchange lifecycle * ```typescript * exchange.onExchangeEnd((endEvent) => { * console.log('Exchange completed'); * }); * ``` */ onExchangeEnd(cb: (endExchange: ExchangeEndEvent) => 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. * * @param cb - Callback receiving the completed message data * * @example Getting buffered message with all content and tool calls * ```typescript * 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}`); * }); * ``` */ onMessageCompleted(cb: (completedMessage: CompletedMessage) => void): void; /** * Starts a new message in this exchange * * Use this for fine-grained control over message construction. * For simple text messages, prefer {@link sendMessageWithContentPart}. * * @param args - Optional message start options including role * @returns The message stream for sending content * * @example Building a message with multiple content parts * ```typescript * const message = exchange.startMessage({ role: MessageRole.User }); * const part = message.startContentPart({ mimeType: 'text/plain' }); * part.sendChunk({ data: 'Analyze this image: ' }); * part.sendContentPartEnd(); * message.sendMessageEnd(); * ``` */ startMessage(args?: { messageId?: string; } & Partial): MessageStream; /** * 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. * * @param options - Message content options * * @example Sending a user message * ```typescript * await exchange.sendMessageWithContentPart({ * data: 'What is the weather today?', * role: MessageRole.User * }); * ``` */ sendMessageWithContentPart(options: { data: string; role?: MessageRole; mimeType?: string; }): Promise; /** * Iterator over all active messages in this exchange */ readonly messages: Iterable; /** * Retrieves a message by ID * @param messageId - The message ID to look up * @returns The message stream, or undefined if not found */ getMessage(messageId: string): MessageStream | undefined; /** * 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. * * @param endExchange - Optional end event data * * @example Manually ending an exchange and stopping a response mid-stream * ```typescript * session.onExchangeStart((exchange) => { * stopButton.addEventListener('click', () => exchange.sendExchangeEnd()); * }); * ``` * * @example End an exchange after sending a message * ```typescript * const exchange = session.startExchange(); * exchange.sendMessageWithContentPart({ data: 'Hello!' }); * // Later, stop the response * exchange.sendExchangeEnd(); * ``` */ sendExchangeEnd(endExchange?: ExchangeEndEvent): void; /** * Sends an error start event for this exchange * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this exchange * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this exchange * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Emits a raw exchange event * @param exchangeEvent - The event to emit (exchangeId is added automatically) * @internal */ emit(exchangeEvent: Omit): void; /** * Returns a string representation of this exchange * @internal */ toString(): string; } /** * Consumer-facing interface for SessionEventHelper * * Defines the public API for interacting with a real-time * conversation session. Sessions are the top-level container * for exchanges, messages, and streaming content. */ /** * Real-time WebSocket session for two-way communication within a {@link ConversationServiceModel | Conversation}. * * 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. * * ```typescript * 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 | * | --- | --- | * | {@link ExchangeStream} | A single request-response cycle within a session. Contains user and assistant messages. | * | {@link MessageStream} | A single message (user, assistant, or system). Contains content parts and tool calls. | * | {@link ContentPartStream} | A piece of streamed content (text, audio, image, transcript). Delivers data via `onChunk`. | * | {@link ToolCallStream} | An external tool invocation by the assistant. Has a start event (name, input) and end event (output). | */ interface SessionStream { /** The conversation ID this session belongs to */ readonly conversationId: string; /** * Whether echo mode is enabled (emitted events are also dispatched to handlers) * @internal */ readonly echo: boolean; /** * The start event, or undefined if not yet received * @internal */ readonly startEventMaybe: SessionStartEvent | undefined; /** * The start event (throws if not yet received) * @internal */ readonly startEvent: SessionStartEvent; /** Whether this session has ended */ readonly ended: boolean; /** * Whether event emitting is currently paused * @internal */ readonly isEmitPaused: boolean; /** * Pauses emitting events to the WebSocket * * Events are buffered internally and sent when `resumeEmits` is called. * Useful when you need to set up event handlers before events start flowing * (e.g., between starting a session and receiving the session started event). * @internal */ pauseEmits(): void; /** * Resumes emitting events and flushes any buffered events * * All events that were buffered while paused are sent in order. * @internal */ resumeEmits(): void; /** * Registers a handler for error start events at the session level * * @param cb - Callback receiving the error event * @returns Cleanup function to remove the handler * * @example * ```typescript * session.onErrorStart((error) => { * console.error(`Session error [${error.errorId}]: ${error.message}`); * }); * ``` */ onErrorStart(cb: (error: { errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events at the session level * * @param cb - Callback receiving the error end event * @returns Cleanup function to remove the handler * * @example * ```typescript * session.onErrorEnd((error) => { * console.log(`Error ${error.errorId} resolved`); * }); * ``` */ onErrorEnd(cb: (error: { errorId: string; } & ErrorEndEvent) => 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. * * @param cb - Callback receiving each new exchange * @returns Cleanup function to remove the handler * * @example Streaming text with content type handling * ```typescript * 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 ?? '')); * } * }); * } * }); * }); * ``` * * @example Getting the complete response at once (no streaming) * ```typescript * 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}`); * } * }); * }); * ``` * * @example Handling tool calls and confirmation interrupts * ```typescript * 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 }); * } * }); * } * }); * }); * ``` */ onExchangeStart(cb: (exchange: ExchangeStream) => 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. * * @param cb - Callback receiving the started event * @returns Cleanup function to remove the handler * * @example * ```typescript * session.onSessionStarted(() => { * console.log('Session is ready — now safe to start exchanges'); * * const exchange = session.startExchange(); * exchange.sendMessageWithContentPart({ * data: 'Hello!', * role: MessageRole.User * }); * }); * ``` */ onSessionStarted(cb: (event: SessionStartedEvent) => 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. * * @param cb - Callback receiving the ending event * @returns Cleanup function to remove the handler * * @example * ```typescript * session.onSessionEnding((event) => { * console.log('Session is ending, performing cleanup...'); * }); * ``` */ onSessionEnding(cb: (event: SessionEndingEvent) => void): () => void; /** * Registers a handler for session end events * * Fired when the session has fully closed. * * @param cb - Callback receiving the end event * @returns Cleanup function to remove the handler * * @example * ```typescript * session.onSessionEnd((event) => { * console.log('Session ended'); * }); * ``` */ onSessionEnd(cb: (event: SessionEndEvent) => 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. * * @param cb - Callback receiving the {@link LabelUpdatedEvent} with the new label * @returns Cleanup function to remove the handler * * @example * ```typescript * session.onLabelUpdated((event) => { * console.log(`New label: ${event.label} (auto: ${event.autogenerated})`); * updateConversationTitle(event.label); * }); * ``` */ onLabelUpdated(cb: (event: LabelUpdatedEvent) => void): () => void; /** * Sends a session started event * @param sessionStarted - Optional started event data * @internal */ sendSessionStarted(sessionStarted?: SessionStartedEvent): void; /** * Sends a session end event and closes the session * * Prefer using `conversation.endSession()` instead of calling this directly. * * @param endSession - Optional end event data * @internal */ sendSessionEnd(endSession?: SessionEndEvent): void; /** * Sends an error start event for this session * @param args - Error details including optional error ID and message * @internal */ sendErrorStart(args: { errorId?: string; } & ErrorStartEvent): void; /** * Sends an error end event for this session * @param args - Error end details including the error ID * @internal */ sendErrorEnd(args: { errorId: string; } & ErrorEndEvent): void; /** * Sends a metadata event for this session * @param metaEvent - Metadata to send * @internal */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Starts a new exchange in this session * * Each exchange is a request-response cycle. Use `sendMessageWithContentPart` * on the returned {@link ExchangeStream} to send a user message, or * `startMessage` for fine-grained control. * * @param args - Optional exchange start options * @returns The exchange stream for sending messages * * @example Multi-exchange conversation * ```typescript * 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 * }); * }); * ``` */ startExchange(args?: { exchangeId?: string; } & ExchangeStartEvent): ExchangeStream; /** * Iterator over all active exchanges in this session */ readonly exchanges: Iterable; /** * Retrieves an exchange by ID * @param exchangeId - The exchange ID to look up * @returns The exchange stream, or undefined if not found */ getExchange(exchangeId: string): ExchangeStream | undefined; /** * Starts an async tool call at the session level * @param args - Tool call start options including tool name * @returns The async tool call stream for managing the lifecycle * @internal */ startAsyncToolCall(args: { toolCallId?: string; } & ToolCallStartEvent): AsyncToolCallStream; /** * Registers a handler for async tool call start events * @param cb - Callback receiving each new async tool call * @returns Cleanup function to remove the handler * @internal */ onAsyncToolCallStart(cb: (asyncToolCall: AsyncToolCallStream) => void): () => void; /** * Iterator over all active async tool calls in this session * @internal */ readonly asyncToolCalls: Iterable; /** * Retrieves an async tool call by ID * @param toolCallId - The tool call ID to look up * @returns The async tool call stream, or undefined if not found * @internal */ getAsyncToolCall(toolCallId: string): AsyncToolCallStream | undefined; /** * Starts an async input stream at the session level * @param args - Stream start options including MIME type * @returns The async input stream for sending data * @internal */ startAsyncInputStream(args: { streamId?: string; } & AsyncInputStreamStartEvent): AsyncInputStream; /** * Registers a handler for async input stream start events * @param cb - Callback receiving each new input stream * @returns Cleanup function to remove the handler * @internal */ onInputStreamStart(cb: (inputStream: AsyncInputStream) => void): () => void; /** * Iterator over all active async input streams in this session * @internal */ readonly asyncInputStreams: Iterable; /** * Retrieves an async input stream by ID * @param streamId - The stream ID to look up * @returns The async input stream, or undefined if not found * @internal */ getAsyncInputStream(streamId: string): AsyncInputStream | undefined; /** * Emits a raw conversation event * @param conversationEvent - The event to emit (conversationId is added automatically) * @internal */ emit(conversationEvent: Omit): void; /** * Registers a handler for error start events from any nested helper * * Unlike `onErrorStart` which only catches errors at the session level, * this handler receives errors from all nested helpers (exchanges, messages, * content parts, tool calls, etc.). * * @param cb - Callback receiving the error event with its source * @returns Cleanup function to remove the handler * @internal */ onAnyErrorStart(cb: (errorStart: { source: unknown; errorId: string; } & ErrorStartEvent) => void): () => void; /** * Registers a handler for error end events from any nested helper * * Unlike `onErrorEnd` which only catches errors at the session level, * this handler receives error end events from all nested helpers. * * @param cb - Callback receiving the error end event with its source * @returns Cleanup function to remove the handler * @internal */ onAnyErrorEnd(cb: (errorEnd: { source: unknown; errorId: string; } & ErrorEndEvent) => void): () => void; /** * Replays persisted exchanges into this session * * Used to restore session state from previously saved exchange data. * * @param exchanges - The exchange data to replay * @internal */ replay(exchanges: Exchange[]): void; /** * Returns a string representation of this session * @internal */ toString(): string; } /** * Types for Exchange Service */ /** * Response type for Exchange with MessageGetResponse instead of raw Message */ interface ExchangeGetResponse extends Omit { messages: MessageGetResponse[]; } /** * Response type for Message with ContentPartGetResponse */ interface MessageGetResponse extends Omit { contentParts?: ContentPartGetResponse[]; } /** * Response interface for ContentPart with convenience methods for accessing data. * * Provides helper properties and methods to determine if content is stored * inline or externally, and to retrieve the data accordingly. * * @example * ```typescript * const contentPart = message.contentParts[0]; * * // Check storage type * if (contentPart.isDataInline) { * const data = await contentPart.getData(); // Returns string * } else if (contentPart.isDataExternal) { * const response = await contentPart.getData(); // Returns fetch Response * } * ``` */ interface ContentPartGetResponse extends ContentPart { /** Returns true if data is stored inline (as a string value) */ readonly isDataInline: boolean; /** Returns true if data is stored externally (as a URI reference) */ readonly isDataExternal: boolean; /** * Retrieves the content data. * @returns For inline data: the string content. For external data: a fetch Response. */ getData(): Promise; } type ExchangeGetAllOptions = PaginationOptions & { /** Sort order for exchanges */ exchangeSort?: SortOrder; /** Sort order for messages within each exchange */ messageSort?: SortOrder; }; interface ExchangeGetByIdOptions { /** Sort order for messages within the exchange */ messageSort?: SortOrder; } interface CreateFeedbackOptions { /** Rating for the exchange ('positive' or 'negative') */ rating: FeedbackRating; /** Optional text comment for the feedback */ comment?: string; } interface FeedbackCreateResponse { } /** * Exchange Service Model */ /** * Service for retrieving exchanges and managing feedback within a {@link ConversationServiceModel | Conversation} * * An exchange represents a single request-response cycle — typically one user * question and the agent's reply. Each exchange response includes its * {@link MessageServiceModel | Messages}, making this the primary way to retrieve * conversation history. For real-time streaming of exchanges, see {@link ExchangeStream}. * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Exchanges } from '@uipath/uipath-typescript/conversational-agent'; * * const exchanges = new Exchanges(sdk); * const conversationExchanges = await exchanges.getAll(conversationId); * ``` */ interface ExchangeServiceModel { /** * 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. * * @param conversationId - The conversation ID to get exchanges for * @param options - Options for querying exchanges including optional pagination parameters * @returns Promise resolving to a {@link PaginatedResponse}<{@link ExchangeGetResponse}> * * @example Basic usage - default page size and sort order * ```typescript * // First page * const firstPage = await exchanges.getAll(conversationId); * * // Navigate using cursor * if (firstPage.hasNextPage) { * const nextPage = await exchanges.getAll(conversationId, { cursor: firstPage.nextCursor }); * } * ``` * * @example With explicit page size and exchange/message sort orders * ```typescript * 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 * }); * } * ``` */ getAll(conversationId: string, options?: ExchangeGetAllOptions): Promise>; /** * Gets an exchange by ID with its messages * * @param conversationId - The conversation containing the exchange * @param exchangeId - The exchange ID to retrieve * @param options - Optional parameters for message sorting * @returns Promise resolving to {@link ExchangeGetResponse} * @example * ```typescript * const exchange = await exchanges.getById(conversationId, exchangeId); * * // Access messages * for (const message of exchange.messages) { * console.log(message.role, message.contentParts); * } * ``` */ getById(conversationId: string, exchangeId: string, options?: ExchangeGetByIdOptions): Promise; /** * Creates feedback for an exchange * * @param conversationId - The conversation containing the exchange * @param exchangeId - The exchange to provide feedback for * @param options - Feedback data including rating and optional comment * @returns Promise resolving to the feedback creation response * {@link FeedbackCreateResponse} * @example * ```typescript * await exchanges.createFeedback( * conversationId, * exchangeId, * { rating: FeedbackRating.Positive, comment: 'Very helpful!' } * ); * ``` */ createFeedback(conversationId: string, exchangeId: string, options: CreateFeedbackOptions): Promise; } /** * Scoped exchange service for a specific conversation. * Auto-fills conversationId from the conversation. */ interface ConversationExchangeServiceModel { /** * Gets exchanges for this 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. * * @param options - Options for querying exchanges including optional pagination parameters * @returns Promise resolving to a {@link PaginatedResponse}<{@link ExchangeGetResponse}> * * @example Basic usage - default page size and sort order * ```typescript * const conversation = await conversationalAgent.conversations.getById(conversationId); * * // First page * const firstPage = await conversation.exchanges.getAll(); * * // Navigate using cursor * if (firstPage.hasNextPage) { * const nextPage = await conversation.exchanges.getAll({ cursor: firstPage.nextCursor }); * } * ``` * * @example With explicit page size and exchange/message sort orders * ```typescript * import { SortOrder } from '@uipath/uipath-typescript/conversational-agent'; * * const conversation = await conversationalAgent.conversations.getById(conversationId); * * // First page * const firstPage = await conversation.exchanges.getAll({ * pageSize: 10, * exchangeSort: SortOrder.Descending, * messageSort: SortOrder.Ascending * }); * * // Navigate using cursor and same parameters * if (firstPage.hasNextPage) { * const nextPage = await conversation.exchanges.getAll({ * pageSize: 10, * exchangeSort: SortOrder.Descending, * messageSort: SortOrder.Ascending, * cursor: firstPage.nextCursor * }); * } * ``` */ getAll(options?: ExchangeGetAllOptions): Promise>; /** * Gets an exchange by ID with its messages * * @param exchangeId - The exchange ID to retrieve * @param options - Optional parameters for message sorting * @returns Promise resolving to the exchange with messages * * @example * ```typescript * const exchange = await conversation.exchanges.getById(exchangeId); * for (const message of exchange.messages) { * console.log(message.role, message.contentParts); * } * ``` */ getById(exchangeId: string, options?: ExchangeGetByIdOptions): Promise; /** * Creates feedback for an exchange * * @param exchangeId - The exchange to provide feedback for * @param options - Feedback data including rating and optional comment * @returns Promise resolving to the feedback creation response * * @example * ```typescript * await conversation.exchanges.createFeedback(exchangeId, { * rating: FeedbackRating.Positive, * comment: 'Very helpful!' * }); * ``` */ createFeedback(exchangeId: string, options: CreateFeedbackOptions): Promise; } /** * WebSocket Types - Common types for WebSocket infrastructure */ /** * Connection status for WebSocket clients */ declare enum ConnectionStatus { Disconnected = "Disconnected", Connecting = "Connecting", Connected = "Connected" } /** * Handler for connection status changes */ type ConnectionStatusChangedHandler = (status: ConnectionStatus, error: Error | null) => void; /** * Log levels for WebSocket debugging */ declare enum LogLevel { Debug = "debug", Info = "info", Warn = "warn", Error = "error" } /** * Conversation Service Model * * This interface defines the HTTP CRUD operations for conversations * and real-time WebSocket session management. */ /** * Methods interface for session operations. * This allows the conversation object to access session methods without * depending on the full ConversationService implementation. */ interface ConversationSessionMethods { /** * Starts a real-time chat session for a conversation */ startSession(conversationId: string, options?: ConversationSessionOptions): SessionStream; /** * Gets an active session for a conversation */ getSession(conversationId: string): SessionStream | undefined; /** * Ends an active session for a conversation */ endSession(conversationId: string): void; } /** * 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 {@link ExchangeServiceModel | Exchanges} service. * For real-time chat, see {@link SessionStream | Session}. * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * 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' }); * ``` */ interface ConversationServiceModel { /** * Creates a new conversation * * The returned conversation has bound methods for lifecycle management: * `update()`, `delete()`, and `startSession()`. * * @param agentId - The agent ID to create the conversation for * @param folderId - The folder ID containing the agent * @param options - Optional settings for the conversation * @returns Promise resolving to {@link ConversationCreateResponse} with bound methods * * @example Basic usage * ```typescript * 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(); * ``` * * @example With agent input arguments * ```typescript * const conversation = await conversationalAgent.conversations.create( * agentId, * folderId, * { * agentInput: { * inline: { userId: 'user-123', language: 'en' } * } * } * ); * ``` */ create(agentId: number, folderId: number, options?: ConversationCreateOptions): Promise; /** * 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. * * @param options - Options for querying conversations * @returns Promise resolving to a {@link PaginatedResponse}<{@link ConversationGetResponse}> * * @example Basic usage - default sort, pagination, and without filtering * ```typescript * // 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 * }); * } * ``` * * @example With explicit page size and sort order (by last-activity timestamp) * ```typescript * 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 * }); * } * ``` * * @example With agent-filter and label-search * ```typescript * 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 * }); * } * ``` */ getAll(options?: ConversationGetAllOptions): Promise>; /** * Gets a conversation by ID * * The returned conversation has bound methods for lifecycle management: * `update()`, `delete()`, and `startSession()`. * * @param id - The conversation ID to retrieve * @returns Promise resolving to {@link ConversationGetResponse} with bound methods * * @example Resume with a real-time session * ```typescript * const conversation = await conversationalAgent.conversations.getById(conversationId); * const session = conversation.startSession(); * ``` * * @example * ```typescript * //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('')}`); * } * } * ``` */ getById(id: string): Promise; /** * Updates a conversation by ID * * @param id - The conversation ID to update * @param options - Fields to update * @returns Promise resolving to {@link ConversationGetResponse} with bound methods * @example * ```typescript * const updatedConversation = await conversationalAgent.conversations.updateById(conversationId, { * label: 'Updated Name' * }); * ``` */ updateById(id: string, options: ConversationUpdateOptions): Promise; /** * Deletes a conversation by ID * * @param id - The conversation ID to delete * @returns Promise resolving to {@link ConversationDeleteResponse} * @example * ```typescript * await conversationalAgent.conversations.deleteById(conversationId); * ``` */ deleteById(id: string): Promise; /** * Uploads a file attachment to a conversation * * @param id - The ID of the conversation to attach the file to * @param file - The file to upload * @returns Promise resolving to attachment metadata with URI * {@link ConversationAttachmentUploadResponse} * * @example * ```typescript * const attachment = await conversationalAgent.conversations.uploadAttachment(conversationId, file); * console.log(`Uploaded: ${attachment.uri}`); * ``` */ uploadAttachment(id: string, file: File): Promise; /** * 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. * * @param conversationId - The ID of the conversation to attach the file to * @param fileName - The name of the file to attach * @returns Promise resolving to {@link ConversationAttachmentCreateResponse} containing * the attachment `uri` and `fileUploadAccess` details needed to upload the file content * * @example Step 1 — Get the attachment URI and upload access * ```typescript * const { uri, fileUploadAccess } = await conversationalAgent.conversations.getAttachmentUploadUri(conversationId, 'report.pdf'); * console.log(`Attachment URI: ${uri}`); * ``` * * @example Step 2 — Upload the file content to the returned URL * ```typescript * 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}`); * ``` */ getAttachmentUploadUri(conversationId: string, fileName: string): Promise; /** * 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. * * @param conversationId - The conversation ID to start the session for * @param options - Optional session configuration * @returns SessionStream for managing the session * * @example * ```typescript * 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); * ``` */ startSession(conversationId: string, options?: ConversationSessionOptions): SessionStream; /** * Retrieves an active session by conversation ID * * @param conversationId - The conversation ID to get the session for * @returns The session helper if active, undefined otherwise * * @example * ```typescript * const session = conversationalAgent.conversations.getSession(conversationId); * if (session) { * // Session already started — safe to send exchanges directly * const exchange = session.startExchange(); * exchange.sendMessageWithContentPart({ data: 'Hello!' }); * } * ``` */ getSession(conversationId: string): SessionStream | undefined; /** * 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. * * @param conversationId - The conversation ID to end the session for * * @example * ```typescript * // End session for a specific conversation * conversationalAgent.conversations.endSession(conversationId); * ``` */ endSession(conversationId: string): void; /** * Iterator over all active sessions * @internal */ readonly sessions: Iterable; /** * Current connection status * @internal */ readonly connectionStatus: ConnectionStatus; /** * Whether WebSocket is connected * @internal */ readonly isConnected: boolean; /** * Current connection error, if any * @internal */ readonly connectionError: Error | null; /** * Registers a handler for connection status changes * @internal */ onConnectionStatusChanged(handler: ConnectionStatusChangedHandler): () => 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. * * @example * ```typescript * conversationalAgent.conversations.disconnect(); * ``` */ disconnect(): void; } /** * Methods interface that will be added to conversation objects */ interface ConversationMethods { /** Scoped exchange operations for this conversation */ readonly exchanges: ConversationExchangeServiceModel; /** * Updates this conversation * * @param options - Fields to update * @returns Promise resolving to the updated conversation */ update(options: ConversationUpdateOptions): Promise; /** * Deletes this conversation * * @returns Promise resolving to the deletion response */ delete(): Promise; /** * Starts a real-time chat session for this conversation * * Creates a WebSocket session and returns a SessionStream for sending * and receiving messages in real-time. * * @param options - Optional session options * @returns SessionStream for managing the session * * @example * ```typescript * const conversation = await conversationalAgent.conversations.create(agentId, folderId); * * // Start a real-time session * const session = conversation.startSession(); * * // Listen for responses using helper methods * session.onExchangeStart((exchange) => { * exchange.onMessageStart((message) => { * // Filter for assistant messages * if (message.isAssistant) { * message.onContentPartStart((part) => { * // 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!' }); * }); * ``` */ startSession(options?: ConversationSessionOptions): SessionStream; /** * Gets the active session for this conversation * * @returns The session helper if active, undefined otherwise * * @example * ```typescript * const session = conversation.getSession(); * if (session) { * // Session already started — safe to send exchanges directly * const exchange = session.startExchange(); * exchange.sendMessageWithContentPart({ data: 'Hello!' }); * } * ``` */ getSession(): SessionStream | undefined; /** * Ends the active session for this conversation * * Sends a session end event and cleans up the session resources. * * @example * ```typescript * // End the session when done * conversation.endSession(); * ``` */ endSession(): void; /** * Uploads a file attachment to this conversation * * @param file - The file to upload * @returns Promise resolving to attachment metadata with URI * {@link ConversationAttachmentUploadResponse} * * @example * ```typescript * const attachment = await conversation.uploadAttachment(file); * console.log(`Uploaded: ${attachment.uri}`); * ``` */ uploadAttachment(file: File): Promise; } /** * Conversation combining {@link RawConversationGetResponse} metadata with {@link ConversationMethods} for lifecycle management */ type ConversationGetResponse = RawConversationGetResponse & ConversationMethods; /** * Creates an actionable conversation by combining API conversation data with operational methods. * * @param conversationData - The conversation data from API * @param service - The conversation service instance * @param sessionMethods - Optional session methods for WebSocket session operations * @param exchangeService - Optional exchange service for scoped exchange methods * @returns A conversation object with added methods */ declare function createConversationWithMethods(conversationData: RawConversationGetResponse, service: ConversationServiceModel, sessionMethods?: ConversationSessionMethods, exchangeService?: ExchangeServiceModel): ConversationGetResponse; /** * Types for Conversation Service */ /** * Options for starting a session on a conversation object. * Unlike SessionStartEventOptions, conversationId is not needed since it's implicit from the conversation. */ interface ConversationSessionOptions { /** * When set, causes events emitted to also be dispatched to event handlers. * This option is useful when the event helper objects are bound to UI components * as it allows a single code path for rendering both user and assistant messages. */ echo?: boolean; /** * Sets the log level for WebSocket session debugging. * When set, enables logging at the specified level for the underlying WebSocket connection. * * @example * ```typescript * import { LogLevel } from '@uipath/uipath-typescript/conversational-agent'; * * const session = conversation.startSession({ logLevel: LogLevel.Debug }); * ``` */ logLevel?: LogLevel; /** * Optional capabilities of this client to advertise to the service when starting the session. * Generally not needed unless the client is accessing more advanced features. */ capabilities?: SessionCapabilities; } /** Response for creating a conversation (includes methods) */ interface ConversationCreateResponse extends ConversationGetResponse { } /** Response for updating a conversation (includes methods) */ interface ConversationUpdateResponse extends ConversationGetResponse { } /** Response for deleting a conversation (raw data, no methods needed) */ interface ConversationDeleteResponse extends RawConversationGetResponse { } interface ConversationCreateOptions { /** Human-readable label for the conversation (max 100 chars) */ label?: string; /** Whether the label should be auto-generated and updated after exchanges */ autogenerateLabel?: boolean; /** Trace identifier for distributed tracing */ traceId?: string; /** Optional configuration for job start behavior */ jobStartOverrides?: ConversationJobStartOverrides; /** Input arguments for the agent */ agentInput?: AgentInput; } interface ConversationUpdateOptions { /** Human-readable label for the conversation */ label?: string; /** Whether the label should be auto-generated and updated after exchanges */ autogenerateLabel?: boolean; /** The key of the current/latest job serving the conversation */ jobKey?: string; /** Whether the conversation's job is running locally */ isLocalJobExecution?: boolean; /** Input arguments for the agent */ agentInput?: AgentInput; } type ConversationGetAllOptions = PaginationOptions & { /** Sort order for conversations (by the last activity timestamp) */ sort?: SortOrder; /** GUID key of the agent to filter conversations by. */ agentKey?: string; /** Numeric ID of the agent to filter conversations by. */ agentId?: number; /** * Case-insensitive substring filter applied to conversation labels (1–100 chars). */ label?: string; }; /** * File upload access details for uploading file content to blob storage */ interface FileUploadAccess { /** URL to upload the file to */ url: string; /** HTTP verb to use (e.g., 'PUT') */ verb: string; /** Headers to include in the upload request */ headers: { keys: string[]; values: string[]; }; /** Whether authentication is required for the upload */ requiresAuth?: boolean; } /** * Response for creating a file attachment entry * * Contains the attachment URI and upload access details for uploading * the file content to blob storage. */ interface ConversationAttachmentCreateResponse { /** URI to reference this attachment in messages */ uri: string; /** File name */ name: string; /** Details for uploading the file content */ fileUploadAccess: FileUploadAccess; } /** * Response for uploading an attachment (after file content is uploaded) */ interface ConversationAttachmentUploadResponse { /** URI to reference this attachment in messages */ uri: string; /** File name */ name: string; /** MIME type of the uploaded file */ mimeType: string; } /** * Message Service Model */ /** * Service for retrieving individual messages within an {@link ExchangeServiceModel | Exchange} * * 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 {@link MessageStream}. * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Messages } from '@uipath/uipath-typescript/conversational-agent'; * * const message = new Messages(sdk); * const messageDetails = await message.getById(conversationId, exchangeId, messageId); * ``` */ interface MessageServiceModel { /** * Gets a message by ID * * Returns the message including its content parts, tool calls, and interrupts. * * @param conversationId - The conversation containing the message * @param exchangeId - The exchange containing the message * @param messageId - The message ID to retrieve * @returns Promise resolving to {@link MessageGetResponse} * @example * ```typescript * const message = await messages.getById(conversationId, exchangeId, messageId); * * console.log(message.role); * console.log(message.contentParts); * console.log(message.toolCalls); * ``` */ getById(conversationId: string, exchangeId: string, messageId: string): Promise; /** * Gets an external content part by ID * * @param conversationId - The conversation containing the content * @param exchangeId - The exchange containing the content * @param messageId - The message containing the content part * @param contentPartId - The content part ID to retrieve * @returns Promise resolving to {@link ContentPartGetResponse} * @example * ```typescript * const contentPart = await messages.getContentPartById( * conversationId, * exchangeId, * messageId, * contentPartId * ); * ``` */ getContentPartById(conversationId: string, exchangeId: string, messageId: string, contentPartId: string): Promise; } /** * Types for Agent Service */ /** * Starting prompt configuration for an agent */ interface AgentStartingPrompt { /** The prompt text displayed to the user */ displayPrompt: string; /** The actual prompt sent when selected */ actualPrompt: string; /** Unique identifier for the prompt */ id: string; } /** * Agent appearance configuration */ interface AgentAppearance { /** Welcome title displayed to users */ welcomeTitle?: string; /** Welcome description displayed to users */ welcomeDescription?: string; /** Starting prompts for users to choose from */ startingPrompts?: AgentStartingPrompt[]; } /** * Raw API response for getting all agents */ interface RawAgentGetResponse { /** Unique ID of the agent */ id: number; /** Display name of the agent */ name: string; /** Agent description */ description: string; /** Process version */ processVersion: string; /** Process key identifier (a dotted-path string like `Solution.Package.Agent`) */ processKey: string; /** GUID key of the agent release */ releaseKey?: string; /** Folder ID */ folderId: number; /** Feed ID */ feedId: string; /** Creation timestamp */ createdTime?: string; } /** * Raw API response for getting a single agent by ID - includes appearance configuration */ interface RawAgentGetByIdResponse extends RawAgentGetResponse { /** Agent appearance configuration */ appearance?: AgentAppearance; } /** * Agent Service Models * * Provides fluent API for agent objects returned from getAll() and getById(). */ /** * Options for creating a conversation from an agent */ interface AgentCreateConversationOptions extends ConversationCreateOptions { } /** * Scoped conversation service for a specific agent. * Auto-fills agentId and folderId from the agent. */ interface AgentConversationServiceModel { /** * Creates a conversation for this agent * * @param options - Optional conversation options (label, etc.) * @returns Promise resolving to the created conversation with methods * * @example * ```typescript * const agent = (await conversationalAgent.getAll())[0]; * const conversation = await agent.conversations.create({ label: 'My Chat' }); * const session = conversation.startSession(); * ``` */ create(options?: AgentCreateConversationOptions): Promise; } /** * Methods added to agent objects */ interface AgentMethods { /** Scoped conversation operations for this agent */ readonly conversations: AgentConversationServiceModel; /** Current WebSocket connection status */ get connectionStatus(): ConnectionStatus; /** Whether the WebSocket connection is currently active */ get isConnected(): boolean; /** Current connection error, or `null` if none */ get connectionError(): Error | null; } /** * Agent combining {@link RawAgentGetResponse} metadata with {@link AgentMethods} for conversation and connection management */ type AgentGetResponse = RawAgentGetResponse & AgentMethods; /** * Agent combining {@link RawAgentGetByIdResponse} metadata with {@link AgentMethods} for conversation and connection management */ type AgentGetByIdResponse = RawAgentGetByIdResponse & AgentMethods; declare function createAgentWithMethods(agentData: T, conversationService: ConversationServiceModel): T & AgentMethods; /** * Constants for Agent Service */ /** * Maps fields for Agent entities to ensure consistent SDK naming */ declare const AgentMap: { [key: string]: string; }; /** * Types for User Settings Service */ /** * Response for getting user settings * * Contains profile and context information that is passed to the agent * for all conversations to provide user context. * * @example * ```typescript * const userSettings = await conversationalAgentService.user.getSettings(); * console.log(userSettings.name, userSettings.email); * ``` */ interface UserSettingsGetResponse { /** Unique identifier of the user (UUID) */ userId: string; /** Name of the user (max 100 chars) */ name: string | null; /** Email address (max 255 chars, must be valid email) */ email: string | null; /** Role of the user (max 100 chars) */ role: string | null; /** Department (max 100 chars) */ department: string | null; /** Company (max 100 chars) */ company: string | null; /** Country (max 100 chars) */ country: string | null; /** Timezone (max 50 chars) */ timezone: string | null; /** UTC timestamp of creation */ createdTime: string; /** UTC timestamp of last update */ updatedTime: string; } /** Response for updating user settings */ interface UserSettingsUpdateResponse extends UserSettingsGetResponse { } /** * Options for updating user settings * * All fields are optional - only send the fields you want to change. * Set fields to `null` to explicitly clear them. * Omitting fields means no change. * * @example * ```typescript * // Update specific fields * await conversationalAgentService.user.updateSettings({ * name: 'John Doe', * timezone: 'America/New_York' * }); * * // Clear a field by setting to null * await conversationalAgentService.user.updateSettings({ * department: null * }); * ``` */ interface UserSettingsUpdateOptions { /** Name of the user (max 100 chars) */ name?: string | null; /** Email address (max 255 chars, must be valid email) */ email?: string | null; /** Role of the user (max 100 chars) */ role?: string | null; /** Department (max 100 chars) */ department?: string | null; /** Company (max 100 chars) */ company?: string | null; /** Country (max 100 chars) */ country?: string | null; /** Timezone (max 50 chars) */ timezone?: string | null; } /** * 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`. * * @example Read current settings * ```typescript * 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); * ``` * * @example Update specific fields (partial update) * ```typescript * await conversationalAgent.user.updateSettings({ * name: 'John Doe', * timezone: 'America/New_York' * }); * ``` * * @example Clear a field by setting it to null * ```typescript * await conversationalAgent.user.updateSettings({ * department: null * }); * ``` */ interface UserSettingsServiceModel { /** * 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 resolving to the current user's settings * {@link UserSettingsGetResponse} * * @example * ```typescript * 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 * ``` */ getSettings(): Promise; /** * 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. * * @param options - Fields to update; omit fields to leave them unchanged, set to `null` to clear * @returns Promise resolving to the updated user settings * {@link UserSettingsUpdateResponse} * * @example Partial update * ```typescript * const updated = await conversationalAgent.user.updateSettings({ * name: 'John Doe', * timezone: 'America/New_York' * }); * ``` * * @example Clear fields by setting to null * ```typescript * await conversationalAgent.user.updateSettings({ * role: null, * department: null * }); * ``` */ updateSettings(options: UserSettingsUpdateOptions): Promise; } /** * Constants for User Settings Service */ /** * Maps fields for User Settings entities to ensure consistent SDK naming */ declare const UserSettingsMap: { [key: string]: string; }; /** * Types for Feature Flags */ /** * Feature flags for conversational agent capabilities * * @internal */ type FeatureFlags = Record; /** * 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) * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ## How It Works * * ### Lifecycle * * ```mermaid * 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: * * ```mermaid * 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 * * ```typescript * 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(); * ``` */ interface ConversationalAgentServiceModel { /** * Gets all available conversational agents * * @param folderId - Optional folder ID to filter agents * @returns Promise resolving to an array of agents * {@link AgentGetResponse} * * @example Basic usage * ```typescript * 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' }); * ``` * * @example Filter agents by folder * ```typescript * const agents = await conversationalAgent.getAll(folderId); * ``` */ getAll(folderId?: number): Promise; /** * Gets a specific agent by ID * * @param id - ID of the agent release * @param folderId - ID of the folder containing the agent * @returns Promise resolving to the agent * {@link AgentGetByIdResponse} * * @example Basic usage * ```typescript * 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' }); * ``` */ getById(id: number, folderId: number): Promise; /** * Downloads the document behind a media citation as an authenticated `Blob`, * fetching the source's `downloadUrl` with the SDK's access token. Use * `source.title` as the file name. * * The `Blob` type is resolved from the source `mimeType`, falling back to the * response Content-Type then the title's file extension. HTML is returned as * `application/octet-stream` so previewing it inline can't execute citation * markup in your app's origin. The token is only sent to the tenant's * configured origin; a missing, unparseable, or off-origin `downloadUrl` is * rejected before any request is made. * * @param source - A media citation source (`CitationSourceMedia`) with a `downloadUrl` * @returns Promise resolving to the document as a `Blob` * * @example * ```typescript * import { isCitationSourceMedia } from '@uipath/uipath-typescript/conversational-agent'; * * if (isCitationSourceMedia(source)) { * const blob = await conversationalAgent.downloadCitationSource(source); * const url = URL.createObjectURL(blob); * window.open(url, '_blank'); * } * ``` */ downloadCitationSource(source: CitationSourceMedia): Promise; /** * Registers a handler that is called whenever the WebSocket connection status changes. * * @param handler - Callback receiving a {@link ConnectionStatus} (`'Disconnected'` | `'Connecting'` | `'Connected'`) and an optional `Error` * @returns Cleanup function to remove the handler * * @example * ```typescript * const cleanup = conversationalAgent.onConnectionStatusChanged((status, error) => { * console.log('Connection status:', status); * if (error) { * console.error('Connection error:', error.message); * } * }); * * // Later, remove the handler * cleanup(); * ``` */ onConnectionStatusChanged(handler: (status: ConnectionStatus, error: Error | null) => void): () => void; /** Service for creating and managing conversations. See {@link ConversationServiceModel}. */ readonly conversations: ConversationServiceModel; /** Service for reading and updating the current user's profile/context settings. See {@link UserSettingsServiceModel}. */ readonly user: UserSettingsServiceModel; /** * Gets feature flags for the current tenant * * @internal */ getFeatureFlags(): Promise; } /** * Options for ConversationalAgentService constructor */ interface ConversationalAgentOptions { /** * External user ID required when authenticating via an app-scoped external app * (client credential grant). Must be set when the access token was issued for an * external app client; omit for standard UiPath user tokens. */ externalUserId?: string; /** * Optional identifier used in UiPath logs to identify the implementing service * of requests. External consumers do not need to set it; the server logs * missing values as "unknown". * * @internal */ surfaceName?: string; /** * Optional version of the implementing service of requests. Paired with * `surfaceName` for internal telemetry. * * @internal */ surfaceVersion?: string; /** Log level for debugging */ logLevel?: LogLevel; } /** * Represents a category that can be associated with feedback. * Default categories (Output, Agent Error, Agent Plan Execution) are auto-created per tenant. * Used as nested objects inside {@link FeedbackResponse}. */ interface FeedbackCategory { /** Unique identifier of the feedback category */ id: string; /** Category name (max 256 characters, unique per tenant) */ category: string; /** Timestamp when the category was created */ createdAt: string; /** Whether this is a system default category (e.g., Output, Agent Error, Agent Plan Execution) */ isDefault: boolean; /** Whether this category applies to positive feedback */ isPositive: boolean; /** Whether this category applies to negative feedback */ isNegative: boolean; } /** * A feedback category returned by {@link FeedbackServiceModel.getCategories}, {@link FeedbackServiceModel.createCategory}. * Fields are transformed to camelCase SDK conventions (createdAt → createdTime). */ interface FeedbackCategoryResponse { /** Unique identifier of the feedback category */ id: string; /** Category name (max 256 characters, unique per tenant) */ category: string; /** Timestamp when the category was created */ createdTime: string; /** Whether this is a system default category (e.g., Output, Agent Error, Agent Plan Execution) */ isDefault: boolean; /** Whether this category applies to positive feedback */ isPositive: boolean; /** Whether this category applies to negative feedback */ isNegative: boolean; } /** * Status of a feedback entry in the review workflow */ declare enum FeedbackStatus { /** Feedback is awaiting review */ Pending = 0, /** Feedback has been approved and confirmed */ Approved = 1, /** Feedback has been dismissed */ Dismissed = 2 } /** * Complete feedback object returned from the API */ interface FeedbackResponse { /** Unique identifier of the feedback entry */ id: string; /** Trace identifier linking feedback to a specific agent execution */ traceId: string; /** Span identifier representing a specific operation within the trace */ spanId: string; /** Identifier of the agent that generated the response being reviewed */ agentId: string | null; /** Version of the agent at the time the feedback was given (max 100 characters) */ agentVersion?: string; /** Optional text comment provided by the user (max 4000 characters) */ comment?: string; /** Optional metadata string associated with the feedback (max 4000 characters) */ metadata?: string; /** Whether the feedback is positive (thumbs up) or negative (thumbs down) */ isPositive: boolean; /** Categories associated with this feedback entry */ feedbackCategories: FeedbackCategory[]; /** Folder key (GUID) of the folder the feedback belongs to */ folderKey?: string; /** Email address of the user who submitted the feedback */ userEmail?: string; /** Current status of the feedback in the review workflow */ status: FeedbackStatus; /** Timestamp when the feedback was created */ createdTime: string; /** Timestamp when the feedback was last updated */ updatedTime: string; } /** * Feedback object returned by getAll and getById. * Extends {@link FeedbackResponse} — use this type for getAll/getById return values. */ interface FeedbackGetResponse extends FeedbackResponse { } /** * Options shared across feedback operations */ interface FeedbackOptions { /** Folder key for authorization */ folderKey: string; } /** * A category reference used when creating or updating feedback */ interface FeedbackCategoryInput { /** Unique identifier of the category */ id: string; /** Category name (e.g., 'Output', 'Agent Error', 'Agent Plan Execution') */ category: string; } /** * Options for submitting a new feedback entry */ interface FeedbackSubmitOptions extends FeedbackOptions { /** Span identifier representing a specific operation within the trace */ spanId?: string; /** Identifier of the agent that generated the response being reviewed */ agentId?: string; /** Version of the agent at the time the feedback was given (max 100 characters) */ agentVersion?: string; /** Span type (e.g., 'agentRun', 'llm', 'tool', 'retriever') (max 100 characters) */ spanType?: string; /** Optional text comment provided by the user (max 4000 characters) */ comment?: string; /** Optional metadata string associated with the feedback (max 4000 characters) */ metadata?: string; /** Categories to associate with this feedback entry */ categories?: FeedbackCategoryInput[]; } /** * Options for updating an existing feedback entry */ interface FeedbackUpdateOptions extends FeedbackOptions { /** Optional text comment provided by the user (max 4000 characters) */ comment?: string; /** Optional metadata string associated with the feedback (max 4000 characters) */ metadata?: string; /** Categories to associate with this feedback entry */ categories?: FeedbackCategoryInput[]; } /** * Options for retrieving multiple feedback entries */ type FeedbackGetAllOptions = PaginationOptions & { /** Filter by agent identifier */ agentId?: string; /** Filter by agent version */ agentVersion?: string; /** Filter by feedback status */ status?: FeedbackStatus; /** Filter by OpenTelemetry trace identifier */ traceId?: string; /** Filter by OpenTelemetry span identifier */ spanId?: string; }; /** * Options for creating a new feedback category */ interface FeedbackCreateCategoryOptions { /** Whether the category applies to positive feedback (defaults to true) */ isPositive?: boolean; /** Whether the category applies to negative feedback (defaults to true) */ isNegative?: boolean; } /** * Options for deleting a feedback category. * Note: system default categories (Output, Agent Error, Agent Plan Execution) cannot be deleted — attempting to do so returns a 409 Conflict. */ interface FeedbackDeleteCategoryOptions { /** When true, deletes the category even if it has associated feedback entries */ forceDelete?: boolean; } /** * Options for retrieving feedback categories */ type FeedbackGetCategoriesOptions = PaginationOptions & { /** Filter by whether the category applies to positive feedback */ isPositive?: boolean; /** Filter by whether the category applies to negative feedback */ isNegative?: boolean; }; /** * Service for managing UiPath Agent Feedback. * * Feedback allows you to collect and manage user feedback on AI agent responses, * including positive/negative ratings, comments, and categorized feedback. * This is useful for monitoring agent quality, identifying areas for improvement, * and building datasets for fine-tuning. [Feedback on agent runs](https://docs.uipath.com/agents/automation-cloud/latest/user-guide/agent-traces#feedback-on-agent-runs) * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * const allFeedback = await feedback.getAll(); * ``` */ interface FeedbackServiceModel { /** * Gets all feedback across all agents in the tenant, with optional filters. * * Retrieves a list of feedback entries, optionally filtered by agent, trace, span, status, or agent version. * When no pagination options are provided, the SDK returns up to 100 items. When pagination options are provided without a pageSize, the SDK defaults to 50 items per page. * * @param options - Optional query parameters for filtering and pagination * @returns Promise resolving to {@link NonPaginatedResponse} of {@link FeedbackResponse} without pagination options, or {@link PaginatedResponse} of {@link FeedbackResponse} when pagination options are used. * @example * ```typescript * import { Feedback, FeedbackStatus } from '@uipath/uipath-typescript/feedback'; * * // Get all feedback (returns API default page size) * const allFeedback = await feedback.getAll(); * * // Get the agentId from a feedback entry * const agentId = allFeedback.items[0].agentId; * * // Get feedback for a specific agent * const agentFeedback = await feedback.getAll({ * agentId, * }); * * // First page with pagination * const page1 = await feedback.getAll({ pageSize: 10 }); * * // Navigate using cursor * if (page1.hasNextPage) { * const page2 = await feedback.getAll({ cursor: page1.nextCursor }); * } * * // Filter by status * const activeFeedback = await feedback.getAll({ * status: FeedbackStatus.Pending, * }); * ``` */ getAll(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets a single feedback entry by its feedback ID. * * @param id - Feedback ID (GUID) of the feedback entry * @param options - Required options including folderKey for folder-level authorization {@link FeedbackOptions} * @returns Promise resolving to {@link FeedbackResponse} * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * // First, get feedback entries to obtain the ID and folder key * const allFeedback = await feedback.getAll({ pageSize: 10 }); * const feedbackId = allFeedback.items[0].id; * const folderKey = allFeedback.items[0].folderKey; * * const item = await feedback.getById(feedbackId, { folderKey }); * console.log(item.isPositive, item.comment, item.status); * ``` */ getById(id: string, options: FeedbackOptions): Promise; /** * Submits a feedback entry. * * @param traceId - Trace identifier linking feedback to a specific agent execution * @param isPositive - Whether the feedback is positive (thumbs up) or negative (thumbs down) * @param options - Additional feedback data and folderKey for authorization {@link FeedbackSubmitOptions} * @returns Promise resolving to the submitted {@link FeedbackResponse} * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * // Obtain traceId and folderKey from an existing feedback entry * const allFeedback = await feedback.getAll({ pageSize: 1 }); * const traceId = allFeedback.items[0].traceId; * const folderKey = allFeedback.items[0].folderKey!; * * const item = await feedback.submit(traceId, true, { folderKey }); * console.log(item.id, item.status); * ``` */ submit(traceId: string, isPositive: boolean, options: FeedbackSubmitOptions): Promise; /** * Updates already submitted feedback. * * @param id - Feedback ID (GUID) of the entry to update * @param isPositive - Whether the feedback is positive (thumbs up) or negative (thumbs down) * @param options - Updated feedback data and folderKey for authorization {@link FeedbackUpdateOptions} * @returns Promise resolving to the updated {@link FeedbackResponse} * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * const allFeedback = await feedback.getAll({ pageSize: 1 }); * const feedbackId = allFeedback.items[0].id; * const folderKey = allFeedback.items[0].folderKey!; * * const updated = await feedback.updateById(feedbackId, false, { * comment: 'On reflection, not great.', * folderKey, * }); * console.log(updated.isPositive, updated.comment); * ``` */ updateById(id: string, isPositive: boolean, options: FeedbackUpdateOptions): Promise; /** * Deletes a feedback entry by its ID. * * @param id - Feedback ID (GUID) of the entry to delete * @param options - Required options including folderKey for folder-level authorization {@link FeedbackOptions} * @returns Promise resolving to void on success * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * const allFeedback = await feedback.getAll({ pageSize: 1 }); * const feedbackId = allFeedback.items[0].id; * const folderKey = allFeedback.items[0].folderKey!; * * await feedback.deleteById(feedbackId, { folderKey }); * ``` */ deleteById(id: string, options: FeedbackOptions): Promise; /** * Creates a new feedback category. * * Custom categories can be used to label feedback entries beyond the default system categories. * Once created, reference the category by its `id` when submitting or updating feedback. * If `isPositive` and `isNegative` are omitted, the backend defaults both to `true`. * * @param category - Name of the category to create (max 256 characters, unique per tenant) * @param options - Optional flags controlling whether the category applies to positive and/or negative feedback {@link FeedbackCreateCategoryOptions} * @returns Promise resolving to the created {@link FeedbackCategoryResponse} * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * // Minimum — applies to both positive and negative feedback by default * const category = await feedback.createCategory('Hallucination'); * console.log(category.id, category.category); * * // With explicit flags * const negativeOnly = await feedback.createCategory('Off-topic', { * isPositive: false, * isNegative: true, * }); * ``` */ createCategory(category: string, options?: FeedbackCreateCategoryOptions): Promise; /** * Gets all feedback categories for the tenant. * * Returns both system default categories (Output, Agent Error, Agent Plan Execution) * and any custom categories created for this tenant. * When no pagination options are provided, the SDK returns up to 100 items. When pagination options are provided without a pageSize, the SDK defaults to 50 items per page. * * @param options - Optional filters and pagination options {@link FeedbackGetCategoriesOptions} * @returns Promise resolving to {@link NonPaginatedResponse} of {@link FeedbackCategoryResponse} without pagination options, or {@link PaginatedResponse} of {@link FeedbackCategoryResponse} when pagination options are used. * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * // Get all categories * const categories = await feedback.getCategories(); * console.log(categories.items.map(c => c.category)); * * // Get only categories applicable to negative feedback * const negativeCategories = await feedback.getCategories({ isNegative: true }); * * // Paginated * const page1 = await feedback.getCategories({ pageSize: 10 }); * ``` */ getCategories(options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Deletes a feedback category by its ID. * * System default categories (Output, Agent Error, Agent Plan Execution) cannot be deleted — * attempting to do so throws a `409 Conflict` error. * Use `forceDelete` to delete a custom category that already has feedback entries associated with it. * * @param id - Category ID (GUID) of the category to delete * @param options - Optional deletion options {@link FeedbackDeleteCategoryOptions} * @returns Promise resolving to void on success * @example * ```typescript * import { Feedback } from '@uipath/uipath-typescript/feedback'; * * const feedback = new Feedback(sdk); * * // Only custom categories (isDefault: false) can be deleted * const categories = await feedback.getCategories(); * const customCategory = categories.items.find(c => !c.isDefault); * if (customCategory) { * await feedback.deleteCategory(customCategory.id); * } * ``` * @example * ```typescript * // Force-delete a custom category that has associated feedback entries * const categories = await feedback.getCategories(); * const customCategory = categories.items.find(c => !c.isDefault); * if (customCategory) { * await feedback.deleteCategory(customCategory.id, { forceDelete: true }); * } * ``` */ deleteCategory(id: string, options?: FeedbackDeleteCategoryOptions): Promise; } /** * Filter fields shared by agent endpoints that accept a * folder/agent/project scope (`/Agents/agents`, `/Agents/errors`, etc.). */ interface AgentFilterOptions { /** Optional folder keys to scope the lookup. Intersected with the user's accessible folders. */ folderKeys?: string[]; /** Filter to specific agent names. */ agentNames?: string[]; /** Filter to specific project keys. */ projectKeys?: string[]; /** Filter to a single agent by ID. */ agentId?: string; /** Filter to a specific process version. */ processVersion?: string; } /** * Columns available for ordering results. */ declare enum AgentListSortColumn { AgentName = "AgentName", ParentProcess = "ParentProcess", LastRun = "LastRun", HealthScore = "HealthScore", LastIncident = "LastIncident", FolderName = "FolderName", /** Quantity of Agent Units consumed */ QuantityAGU = "QuantityAGU", /** Quantity of Platform Units consumed */ QuantityPLTU = "QuantityPLTU", FolderPath = "FolderPath" } /** * Ordering directive for the agents list. */ interface AgentListOrderBy { /** Column to sort by */ column: AgentListSortColumn; /** * Sort descending. * @default false */ desc?: boolean; } /** * One row in the agents list - agent identity plus consumption and health metadata aggregated over the * requested time window. */ interface AgentListItem { /** Agent ID */ agentId: string; /** Agent display name */ agentName: string; /** Parent process name. May be `null` or `""` for jobs not bound to a parent process. */ parentProcess: string | null; /** Folder key of the folder the agent runs in. May be `null` or `""`. */ folderKey: string | null; /** Folder display name. May be `null` or `""`. */ folderName: string | null; /** Fully qualified folder path. May be `null` or `""`. */ folderPath: string | null; /** Last run timestamp */ lastRun: string; /** Process key. May be `null` or `""` for ad-hoc jobs. */ processKey: string | null; /** Process version. May be `null` or `""`. */ processVersion: string | null; /** Health score (0-100) */ healthScore: number; /** Last incident type label. May be `null` or `""`. */ lastIncidentType: string | null; /** Total units consumed by this agent in the window */ unitsQuantity: number; /** Display name of the units (if any). May be `null` or `""`. */ unitsName: string | null; /** Quantity of Agent Units consumed by this agent */ quantityAGU: number; /** Quantity of Platform Units consumed by this agent */ quantityPLTU: number; } /** * Options for getting the list of agents. * * Composes filter, pagination, and sort options. */ type AgentGetAllOptions = AgentFilterOptions & PaginationOptions & { /** Sort order for the result set. */ orderBy?: AgentListOrderBy; }; /** * Summary information about a single job execution — included on every * error entry to anchor the window. */ interface AgentJobInfo { /** Job key */ jobKey: string; /** Folder key the job ran in */ folderKey: string; /** Display name of the folder */ folderName: string; /** Fully qualified folder path */ folderPath: string; /** Job start time */ startTime: string; /** Job end time. `null` while the job is still running. */ endTime: string | null; /** Process key the job was launched from. `null` for ad-hoc jobs. */ processKey: string | null; } /** * Columns available for ordering / grouping the agent errors list. */ declare enum AgentErrorSortColumn { AgentId = "AgentId", AgentName = "AgentName", ParentProcessName = "ParentProcessName", ErrorTitle = "ErrorTitle", FirstSeenStartTime = "FirstSeenStartTime", ExecutionCount = "ExecutionCount", Type = "Type", FirstSeenFolderName = "FirstSeenFolderName", FirstSeenFolderPath = "FirstSeenFolderPath", LastSeenStartTime = "LastSeenStartTime", LastSeenFolderName = "LastSeenFolderName", LastSeenFolderPath = "LastSeenFolderPath" } /** * Ordering directive for the agent errors list. */ interface AgentErrorOrderBy { /** Column to sort by */ column: AgentErrorSortColumn; /** * Sort descending. * @default false */ desc?: boolean; } /** * One error in the agent errors list — an error/error-class observed * for an agent over the requested window. */ interface AgentError { /** Error type */ type: string; /** Error description */ description: string; /** Agent ID */ agentId: string; /** Agent display name. `null` if the agent has no display name set. */ agentName: string | null; /** Job key where the error was first seen */ jobKey: string; /** Parent process name. `null` for jobs not bound to a parent process. */ parentProcess: string | null; /** First-seen timestamp */ firstSeen: string; /** Folder key where the error was first observed */ folderKey: string; /** Folder display name */ folderName: string; /** Fully qualified folder path */ folderPath: string; /** Number of error executions counted for this error */ count: number; /** First job in the window where this error was observed */ firstSeenJob: AgentJobInfo; /** Last job in the window where this error was observed */ lastSeenJob: AgentJobInfo; } /** * Options for the agent errors list. * * Composes filter, pagination, and sort/group options. */ type AgentGetErrorsOptions = AgentFilterOptions & PaginationOptions & { /** Sort order for the result set. */ orderBy?: AgentErrorOrderBy; /** Group results by one or more columns. */ groupBy?: AgentErrorSortColumn[]; }; /** * A single point on the agent errors timeline */ interface AgentGetErrorsTimelineResponse { /** Agent name */ name: string; /** Error count in this time bucket */ value: number; /** Bucket timestamp (ISO 8601, UTC) */ date: string; } /** * Options for getting the agent errors timeline. */ interface AgentGetErrorsTimelineOptions extends AgentFilterOptions { /** * Max number of agents to return. * @default 10 */ limit?: number; } /** * A single point on the agent consumption timeline */ interface AgentGetConsumptionTimelineResponse { /** Bucket timestamp (ISO 8601, UTC) */ timeSlice: string; /** Agent Units quantity consumed in this time bucket */ aguConsumption: number; } /** * Options for getting the agent consumption timeline. */ interface AgentGetConsumptionTimelineOptions extends AgentFilterOptions { } /** * A single point on the agent latency timeline */ interface AgentGetLatencyTimelineResponse { /** * Percentile label for this point — observed values: `"P50"`, `"P95"`. */ name: string; /** Latency value in milliseconds. */ value: number; /** Bucket timestamp (ISO 8601, UTC) */ date: string; } /** * Options for getting the agent latency timeline. */ interface AgentGetLatencyTimelineOptions extends AgentFilterOptions { } /** * A single agent's error count over the requested window, with the first and * last jobs where errors were observed. */ interface AgentTopErrorCount { /** Agent name */ name: string; /** Error count for this agent over the requested window */ count: number; /** Agent ID (GUID) */ agentId: string; /** First job in the window where this agent reported errors */ firstSeenJob: AgentJobInfo; /** Last job in the window where this agent reported errors */ lastSeenJob: AgentJobInfo; } /** * Response from getting the top agents by error count. */ interface AgentGetTopErrorCountResponse { /** Total error count across all agents in the window. */ totalErrors: number; /** Top-N agents ranked by error count. */ data: AgentTopErrorCount[]; } /** * Options for getting the top agents by error count. */ interface AgentGetTopErrorCountOptions extends AgentFilterOptions { /** * Max number of agents to return. Defaults to 10 server-side. * @default 10 */ limit?: number; } /** * Agent type, used to filter consumption results. * * Wire format is the string name, per the API's `StringEnumConverter` serialization. */ declare enum AgentType { Autonomous = "Autonomous", Conversational = "Conversational", Coded = "Coded" } /** * A single agent's unit consumption over the requested window, with the first * and last jobs where consumption was recorded. */ interface AgentConsumption { /** Agent ID (GUID) */ agentId: string; /** Agent display name */ agentName: string; /** Total quantity consumed by this agent. `null` if no consumption is recorded. */ consumedQuantity: number | null; /** Agent Units quantity consumed. `null` if no consumption is recorded. */ consumedAGUQuantity: number | null; /** Platform Units quantity consumed. `null` if no consumption is recorded. */ consumedPLTUQuantity: number | null; /** First job in the window where this agent recorded consumption */ firstSeenJob: AgentJobInfo; /** Last job in the window where this agent recorded consumption */ lastSeenJob: AgentJobInfo; } /** * Response from getting the top agents by consumption. */ interface AgentGetTopConsumptionResponse { /** Window start date. */ startDate: string; /** Window end date. */ endDate: string; /** Total quantity consumed across all matching agents in the window. */ totalConsumed: number; /** Total Agent Units quantity consumed. */ totalAGUConsumed: number; /** Total Platform Units quantity consumed. */ totalPLTUConsumed: number; /** Limit applied (echoed from the request). */ limit: number; /** Top-N agents ranked by consumption. Empty array when no agents matched. */ agents: AgentConsumption[]; } /** * Options for getting the top agents by consumption. */ interface AgentGetTopConsumptionOptions extends AgentFilterOptions { /** * Max number of agents to return. Defaults to 10 server-side. * @default 10 */ limit?: number; /** * Health-based filter. `true` returns only healthy agents, `false` only * unhealthy. Omit to include both. */ healthy?: boolean; /** * Health-score cutoff used when `healthy` is set. Defaults to 75.0 * server-side. * @default 75.0 */ healthThreshold?: number; /** * Filter to specific agent types. Multiple types are combined with `OR` and * sent to the API as a comma-separated string. */ agentTypes?: AgentType[]; } /** * Distribution of incidents across types over the requested window. */ interface AgentGetIncidentDistributionResponse { /** Number of error-type incidents in the window */ errorCount: number; /** Number of escalation-type incidents in the window */ escalationCount: number; /** Number of policy-type incidents in the window */ policyCount: number; } /** * Options for getting the incident distribution. * * Currently identical to {@link AgentFilterOptions}; named distinctly so that * future per-method filters can be added without a breaking change. */ interface AgentGetIncidentDistributionOptions extends AgentFilterOptions { } /** * Per-agent (process + folder) stats within an {@link AgentSummaryPeriod}. */ interface AgentSummaryEntry { /** Process key (GUID) */ processKey: string; /** Folder key (GUID) the agent ran in */ folderKey: string; /** Process version */ processVersion: string; /** Total job runs in the period */ totalJobs: number; /** Number of successful runs in the period */ successfulJobs: number; /** Success rate as a percentage (0-100) */ successRate: number; /** Average run duration in seconds */ averageDurationSeconds: number; /** First job completion timestamp (ISO 8601, UTC) */ firstJobFinished: string; /** Last job completion timestamp (ISO 8601, UTC) */ lastJobFinished: string; /** * Status of the most recent run, normalized to {@link JobState}. The API's * `Success` label maps to {@link JobState.Successful}; any unrecognized value * becomes {@link JobState.Unknown}. */ lastJobStatus: JobState; } /** * Aggregate stats for a single period within an {@link AgentGetSummaryResponse} * — covers the requested window for either the current period or an optional * lookback period. */ interface AgentSummaryPeriod { /** Total job runs across all agents in the period */ totalJobs: number; /** Number of successful runs across all agents in the period */ successfulJobs: number; /** Overall success rate as a percentage (0-100) */ successRate: number; /** Average run duration in seconds across all agents in the period */ averageDurationSeconds: number; /** Period start time (ISO 8601, UTC) */ startTime: string; /** Period end time (ISO 8601, UTC) */ endTime: string; /** Per-agent breakdown */ agents: AgentSummaryEntry[]; } /** * Response from getting the agent summary. */ interface AgentGetSummaryResponse { /** Aggregate stats for the requested window. Always present. */ currentPeriodSummary: AgentSummaryPeriod; /** Aggregate stats for the prior window of equal length. Only present when `lookbackPeriodAnalysis: true` was sent. */ lookbackPeriodSummary?: AgentSummaryPeriod; } /** * Job execution mode filter accepted by the summary endpoints. * * Wire format is the string name (`"Debug"` / `"Runtime"`), per the API's * `StringEnumConverter` serialization. */ declare enum AgentExecutionType { /** Test runs */ Debug = "Debug", /** Production runs */ Runtime = "Runtime" } /** * Options for getting the agent summary. */ interface AgentGetSummaryOptions extends AgentFilterOptions { /** * When `true`, it also computes a `lookbackPeriodSummary` for the * prior window of equal length. Defaults to `false` server-side. * @default false */ lookbackPeriodAnalysis?: boolean; /** Filter to a specific process by key (GUID). */ processKey?: string; /** * Filter to a specific folder by key (GUID). * * The summary endpoint accepts both — `folderKey` selects a * single folder, `folderKeys` filters the lookup to a list of folders. */ folderKey?: string; /** * Filter to a specific execution type — `Debug` (test runs) or * `Runtime` (production runs). */ executionType?: AgentExecutionType; } /** * Job-type breakdown of unit consumption — completed jobs vs jobs still in * progress at query time. */ interface AgentJobConsumptionSummary { /** Units consumed by jobs that have completed in the period */ completeJobs: number; /** Units consumed by jobs still in progress at query time */ incompleteJobs: number; } /** * Per-agent (process + folder) unit consumption entry within an * {@link AgentUnitConsumptionPeriod}. */ interface AgentUnitConsumptionEntry { /** Folder key (GUID) the agent ran in */ folderKey: string; /** Process key (GUID) */ processKey: string; /** Process version */ processVersion: string; /** First job completion timestamp (ISO 8601). `"0001-01-01T00:00:00"` if no completion in the period. */ firstJobFinished: string; /** Last job completion timestamp (ISO 8601). `"0001-01-01T00:00:00"` if no completion in the period. */ lastJobFinished: string; /** Agent Units consumption for this agent, split by job completion status */ agentUnitConsumption: AgentJobConsumptionSummary; /** Platform Units consumption for this agent, split by job completion status */ platformUnitConsumption: AgentJobConsumptionSummary; } /** * Aggregate Agent Units and Platform Units consumption for a single period within an * {@link AgentGetUnitConsumptionSummaryResponse} — covers the requested window * for either the current period or an optional lookback period. */ interface AgentUnitConsumptionPeriod { /** Total Agent Units consumed across all agents in the period, split by job completion */ totalAgentUnitConsumption: AgentJobConsumptionSummary; /** Total Platform Units consumed across all agents in the period, split by job completion */ totalPlatformUnitConsumption: AgentJobConsumptionSummary; /** Period start time (ISO 8601, UTC) */ startTime: string; /** Period end time (ISO 8601, UTC) */ endTime: string; /** Per-agent consumption breakdown */ agentConsumption: AgentUnitConsumptionEntry[]; } /** * Response from getting the agent unit consumption summary. */ interface AgentGetUnitConsumptionSummaryResponse { /** Aggregate consumption for the requested window. Always present. */ currentPeriodSummary: AgentUnitConsumptionPeriod; /** Aggregate consumption for the prior window of equal length. Only present when `lookbackPeriodAnalysis: true` was sent. */ lookbackPeriodSummary?: AgentUnitConsumptionPeriod; } /** * Options for getting the agent unit consumption summary. * * Currently identical to {@link AgentGetSummaryOptions} (the API uses the same * `AgentsSummaryRequest` schema for both endpoints); named distinctly so that * future per-method filters can be added without a breaking change. */ interface AgentGetUnitConsumptionSummaryOptions extends AgentGetSummaryOptions { } /** * 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 * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * 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'), * ); * ``` */ interface AgentServiceModel { /** * Retrieves the list of agents on the tenant with consumption and health * metadata over the requested window. * * Returns a {@link PaginatedResponse} when pagination options (`pageSize`, * `cursor`, or `jumpToPage`) are provided, otherwise a * {@link NonPaginatedResponse}. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional pagination, sort, and filters * @returns Promise resolving to a paginated or non-paginated list of {@link AgentListItem} * @example * ```typescript * 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 }, * ); * } * ``` */ getAll(startTime: Date, endTime: Date, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Retrieves agent errors (error-classes observed for agents) over the * requested window. * * Returns a {@link PaginatedResponse} when pagination options (`pageSize`, * `cursor`, or `jumpToPage`) are provided, otherwise a * {@link NonPaginatedResponse}. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional pagination, sort/group, and filters * @returns Promise resolving to a paginated or non-paginated list of {@link AgentError} * @example * ```typescript * 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 }, * ); * } * ``` */ getErrors(startTime: Date, endTime: Date, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Retrieves a time-series of error counts grouped by agent over the requested window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to an array of {@link AgentGetErrorsTimelineResponse} * @example * ```typescript * 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`); * }); * ``` * @example * ```typescript * // 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, * }, * ); * ``` */ getErrorsTimeline(startTime: Date, endTime: Date, options?: AgentGetErrorsTimelineOptions): Promise; /** * Retrieves a time-series of Agent Units consumption over the requested window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to an array of {@link AgentGetConsumptionTimelineResponse} * @example * ```typescript * 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`); * }); * ``` * @example * ```typescript * // 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'], * }, * ); * ``` */ getConsumptionTimeline(startTime: Date, endTime: Date, options?: AgentGetConsumptionTimelineOptions): Promise; /** * Retrieves a time-series of agent latency (milliseconds) over the requested * window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to an array of {@link AgentGetLatencyTimelineResponse} * @example * ```typescript * 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`); * }); * ``` * @example * ```typescript * // 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: '', * }, * ); * ``` */ getLatencyTimeline(startTime: Date, endTime: Date, options?: AgentGetLatencyTimelineOptions): Promise; /** * Retrieves the top-N agents ranked by error count over the requested window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to {@link AgentGetTopErrorCountResponse} * @example * ```typescript * 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`); * }); * ``` * @example * ```typescript * // 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, * }, * ); * ``` */ getTopErrorCount(startTime: Date, endTime: Date, options?: AgentGetTopErrorCountOptions): Promise; /** * Retrieves the top-N agents ranked by unit consumption over the requested window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to {@link AgentGetTopConsumptionResponse} * @example * ```typescript * 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}`); * }); * ``` * @example * ```typescript * 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], * }, * ); * ``` */ getTopConsumption(startTime: Date, endTime: Date, options?: AgentGetTopConsumptionOptions): Promise; /** * Retrieves breakdown of agent incidents count — errors, escalations, * and policy violations over a requested window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to {@link AgentGetIncidentDistributionResponse} * @example * ```typescript * 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}`); * ``` * @example * ```typescript * // Scope to specific folders * const result = await agents.getIncidentDistribution( * new Date('2025-05-01T00:00:00Z'), * new Date('2025-06-01T00:00:00Z'), * { * folderKeys: [''], * }, * ); * ``` */ getIncidentDistribution(startTime: Date, endTime: Date, options?: AgentGetIncidentDistributionOptions): Promise; /** * 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. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to {@link AgentGetSummaryResponse} * @example * ```typescript * 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}%`); * ``` * @example * ```typescript * 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, * }, * ); * ``` */ getSummary(startTime: Date, endTime: Date, options?: AgentGetSummaryOptions): Promise; /** * Retrieves an aggregate Agent Units and Platform Units consumption summary per agent over the * requested window. * * @param startTime - Inclusive lower bound for the query window * @param endTime - Exclusive upper bound for the query window * @param options - Optional filters * @returns Promise resolving to {@link AgentGetUnitConsumptionSummaryResponse} * @example * ```typescript * 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}`); * ``` * @example * ```typescript * 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, * }, * ); * ``` */ getUnitConsumptionSummary(startTime: Date, endTime: Date, options?: AgentGetUnitConsumptionSummaryOptions): Promise; } /** * Types for the Agent Memory metrics service. */ /** * Execution kind to filter Agent Memory queries by. Omit to include both * Debug and Runtime executions. */ declare enum AgentMemoryExecutionType { /** Executions produced during agent debugging sessions. */ Debug = "Debug", /** Executions produced during production runtime. */ Runtime = "Runtime" } /** * Common time-window and scope filters shared by Agent Memory queries. * * All fields are optional. When `startTime`/`endTime` are omitted, the query * defaults to the last 24 hours, with `endTime` defaulting to now. */ interface AgentMemoryFilterOptions { /** Inclusive lower bound for the query window. Defaults to 24 hours before `endTime` when omitted. */ startTime?: Date; /** Exclusive upper bound for the query window. Defaults to now when omitted. */ endTime?: Date; /** Filter to a single agent by ID. Obtain an `agentId` from the Agents service. */ agentId?: string; /** Filter to a specific agent version. */ agentVersion?: string; /** Folder keys to scope the query. Results are limited to folders you can access. */ folderKeys?: string[]; /** Filter to a specific execution kind. Omit to include both Debug and Runtime. */ executionType?: AgentMemoryExecutionType; } /** * Options for retrieving the agent-memory state timeline. */ interface AgentMemoryGetTimelineOptions extends AgentMemoryFilterOptions { } /** * Options for retrieving the memory-calls timeline. */ interface AgentMemoryGetCallsTimelineOptions extends AgentMemoryFilterOptions { } /** * Options for retrieving the top memory spaces. */ interface AgentMemoryGetTopSpacesOptions extends AgentMemoryFilterOptions { /** * Maximum number of memory spaces to return, ranked by memory count. * @default 5 */ limit?: number; } /** * One point on the agent-memory state timeline — memory-state counts for a * single time bucket. */ interface AgentMemoryGetTimelineResponse { /** Bucket timestamp. */ timeSlice: string; /** Count of memory entries that were in-memory in this bucket. */ inMemoryCount: number; /** Count of memory entries that were not in-memory in this bucket. */ notInMemoryCount: number; /** Total memory entries in this bucket. */ totalCount: number; /** Count of enabled memory entries in this bucket. */ enabledMemoryCount: number; /** Count of disabled memory entries in this bucket. */ disabledMemoryCount: number; } /** * One point on the memory-calls timeline — the count of memory calls for a * single time bucket. */ interface AgentMemoryGetCallsTimelineResponse { /** Bucket timestamp. */ timeSlice: string; /** Number of memory calls in this bucket. */ memoryCallsCount: number; } /** * A single memory space with its enabled/disabled memory-entry breakdown. */ interface AgentMemoryGetTopSpacesResponse { /** Memory space identifier. */ memorySpaceId: string; /** Memory space display name. */ memorySpaceName: string; /** Total memory entries in this space over the requested window. */ memoryCount: number; /** Count of enabled memory entries in this space. */ enabledMemoryCount: number; /** Count of disabled memory entries in this space. */ disabledMemoryCount: number; } /** * * @experimental * * /// warning * Preview: This service is experimental and may change or be removed in future releases. * /// * * Service for managing UiPath Agent Memory. * * Agent Memory is a persistent store of information an agent * retains across runs to improve runtime reliability. * * @example * ```typescript * import { UiPath } from '@uipath/uipath-typescript/core'; * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory'; * * const sdk = new UiPath(config); * await sdk.initialize(); * * const memory = new AgentMemory(sdk); * const timeline = await memory.getTimeline(); * ``` */ interface AgentMemoryServiceModel { /** * Gets agent memory state over time, with optional filters. * * @experimental * * /// warning * Preview: This method is experimental and may change or be removed in future releases. * /// * * @param options - Optional time window and scope filters * @returns Promise resolving to an array of {@link AgentMemoryGetTimelineResponse}, one per time bucket. * @example * ```typescript * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory'; * * const memory = new AgentMemory(sdk); * * // Last 24 hours (default window) * const timeline = await memory.getTimeline(); * console.log(timeline[0]?.inMemoryCount); * ``` * @example * ```typescript * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory'; * * // Scoped to one agent in one folder, runtime executions only * const scoped = await memory.getTimeline({ * startTime: new Date('2026-05-01T00:00:00Z'), * endTime: new Date('2026-06-01T00:00:00Z'), * agentId: '', * folderKeys: [''], * executionType: AgentMemoryExecutionType.Runtime, * }); * ``` */ getTimeline(options?: AgentMemoryGetTimelineOptions): Promise; /** * Gets the number of agent memory calls (accesses to the memory store) over time, with optional filters. * * @experimental * * /// warning * Preview: This method is experimental and may change or be removed in future releases. * /// * * @param options - Optional time window and scope filters * @returns Promise resolving to an array of {@link AgentMemoryGetCallsTimelineResponse}, one per time bucket. * @example * ```typescript * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory'; * * const memory = new AgentMemory(sdk); * * // Last 24 hours (default window) * const timeline = await memory.getCallsTimeline(); * console.log(timeline[0]?.memoryCallsCount); * ``` * @example * ```typescript * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory'; * * // Scoped to one agent in one folder, runtime executions only * const scoped = await memory.getCallsTimeline({ * startTime: new Date('2026-05-01T00:00:00Z'), * endTime: new Date('2026-06-01T00:00:00Z'), * agentId: '', * folderKeys: [''], * executionType: AgentMemoryExecutionType.Runtime, * }); * ``` */ getCallsTimeline(options?: AgentMemoryGetCallsTimelineOptions): Promise; /** * Gets the top memory spaces by memory count, with optional filters * * @experimental * * /// warning * Preview: This method is experimental and may change or be removed in future releases. * /// * * @param options - Optional limit, time window, and scope filters * @returns Promise resolving to an array of {@link AgentMemoryGetTopSpacesResponse}, ranked by memory count. * @example * ```typescript * import { AgentMemory } from '@uipath/uipath-typescript/agent-memory'; * * const memory = new AgentMemory(sdk); * * // Top 5 memory spaces (default limit and window) * const top = await memory.getTopSpaces(); * console.log(top[0]?.memorySpaceName, top[0]?.memoryCount); * ``` * @example * ```typescript * import { AgentMemoryExecutionType } from '@uipath/uipath-typescript/agent-memory'; * * // Top 10 spaces for one folder over an explicit window, runtime executions only * const topScoped = await memory.getTopSpaces({ * startTime: new Date('2026-05-01T00:00:00Z'), * endTime: new Date('2026-06-01T00:00:00Z'), * folderKeys: [''], * executionType: AgentMemoryExecutionType.Runtime, * limit: 10, * }); * ``` */ getTopSpaces(options?: AgentMemoryGetTopSpacesOptions): Promise; } declare enum DocumentActionPriority { Low = "Low", Medium = "Medium", High = "High", Critical = "Critical" } declare enum DocumentActionStatus { Unassigned = "Unassigned", Pending = "Pending", Completed = "Completed" } declare enum DocumentActionType { Validation = "Validation", Classification = "Classification" } interface UserData { Id?: number | null; EmailAddress?: string | null; } declare enum ClassifierDocumentTypeType { FormsAi = "FormsAi", SemiStructuredAi = "SemiStructuredAi", Helix = "Helix", Unknown = "Unknown" } declare enum CreateTaskPriority { Low = "Low", Medium = "Medium", High = "High", Critical = "Critical" } declare enum GptFieldType { Address = "Address", Boolean = "Boolean", Date = "Date", Name = "Name", Number = "Number", Text = "Text" } declare enum JobStatus { Succeeded = "Succeeded", Failed = "Failed", Running = "Running", NotStarted = "NotStarted" } declare enum ValidationDisplayMode { Classic = "Classic", Compact = "Compact" } interface ClassificationPrompt { Name?: string | null; Description?: string | null; } interface ClassificationValidationConfiguration { EnablePageReordering?: boolean; } interface ContentValidationData { BucketName?: string | null; BucketId?: number; FolderId?: number; FolderKey?: string; DocumentId?: string; EncodedDocumentPath?: string | null; TextPath?: string | null; DocumentObjectModelPath?: string | null; TaxonomyPath?: string | null; AutomaticExtractionResultsPath?: string | null; ValidatedExtractionResultsPath?: string | null; CustomizationInfoPath?: string | null; } interface DocumentClassificationActionDataModel { Id?: number | null; Status?: DocumentActionStatus; Title?: string | null; Priority?: DocumentActionPriority; TaskCatalogName?: string | null; TaskUrl?: string | null; FolderPath?: string | null; FolderId?: number | null; Data?: unknown | null; Action?: string | null; IsDeleted?: boolean | null; AssignedToUser?: UserData; CreatorUser?: UserData; DeleterUser?: UserData; LastModifierUser?: UserData; CompletedByUser?: UserData; CreationTime?: string | null; LastAssignedTime?: string | null; CompletionTime?: string | null; ProcessingTime?: number | null; Type?: DocumentActionType; } interface DocumentExtractionActionDataModel { Id?: number | null; Status?: DocumentActionStatus; Title?: string | null; Priority?: DocumentActionPriority; TaskCatalogName?: string | null; TaskUrl?: string | null; FolderPath?: string | null; FolderId?: number | null; Data?: unknown | null; Action?: string | null; IsDeleted?: boolean | null; AssignedToUser?: UserData; CreatorUser?: UserData; DeleterUser?: UserData; LastModifierUser?: UserData; CompletedByUser?: UserData; CreationTime?: string | null; LastAssignedTime?: string | null; CompletionTime?: string | null; ProcessingTime?: number | null; Type?: DocumentActionType; } interface ExtractionPrompt { Id?: string | null; Question?: string | null; FieldType?: GptFieldType; MultiValued?: boolean | null; } interface ExtractionValidationConfigurationV2 { EnableRtlControls?: boolean; DisplayMode?: ValidationDisplayMode; FieldsValidationConfidence?: number | null; AllowChangeOfDocumentType?: boolean | null; } interface FieldGroupValueProjection { FieldGroupName?: string | null; FieldValues?: FieldValueProjection[] | null; } interface FieldValueProjection { Id?: string | null; Name?: string | null; Value?: string | null; UnformattedValue?: string | null; Confidence?: number | null; OcrConfidence?: number | null; Type?: FieldType; } interface ClassificationRequestBody { DocumentId?: string; Prompts?: ClassificationPrompt[] | null; } interface ClassificationResponse { ClassificationResults?: ClassificationResult[] | null; } interface StartClassificationResponse { OperationId?: string; ResultUrl?: string | null; } interface DataDeletionRequest { RemoveValidationDataFromStorage?: boolean; } declare enum ErrorSeverity { Info = "Info", Warning = "Warning", Error = "Error" } interface ErrorResponse { Message?: string | null; Severity?: ErrorSeverity; Code?: string | null; Parameters?: string[] | null; } interface StartDigitizationFromAttachmentModel { AttachmentId?: string; FolderId?: string | null; FileName?: string | null; MimeType?: string | null; } interface StartDigitizationResponse { DocumentId?: string; ResultUrl?: string | null; } interface SwaggerGetDigitizeJobResponse { Status?: JobStatus; Error?: ErrorResponse; Result?: SwaggerGetDigitizeJobResult; CreatedAt?: string; LastUpdatedAt?: string; } interface SwaggerGetDigitizeJobResult { DocumentObjectModel?: DocumentEntity; DocumentText?: string | null; } declare enum ProjectProperties { IsPredefined = "IsPredefined", SupportsTags = "SupportsTags", SupportsVersions = "SupportsVersions", IsSplittingEnabled = "IsSplittingEnabled" } declare enum ProjectType { Classic = "Classic", Modern = "Modern", IXP = "IXP", Unknown = "Unknown" } declare enum ResourceStatus { Unknown = "Unknown", NotStarted = "NotStarted", ExportInProgress = "ExportInProgress", ExportCompleted = "ExportCompleted", InProgress = "InProgress", Suspended = "Suspended", Resuming = "Resuming", Available = "Available", Error = "Error", Deleting = "Deleting" } declare enum ResourceType { Specialized = "Specialized", Generative = "Generative", Custom = "Custom", Unknown = "Unknown" } interface Classifier { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; Status?: ResourceStatus; DocumentTypeIds?: string[] | null; DetailsUrl?: string | null; SyncUrl?: string | null; AsyncUrl?: string | null; ProjectVersion?: number | null; ProjectVersionName?: string | null; Properties?: ProjectProperties[] | null; } interface DiscoveredDocumentType { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; DetailsUrl?: string | null; } interface DiscoveredExtractorResourceSummaryResponse { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; DetailsUrl?: string | null; DocumentTypeId?: string | null; DocumentTypeName?: string | null; ProjectVersion?: number | null; ProjectVersionName?: string | null; CreatedOn?: string | null; Description?: string | null; } interface DiscoveredProjectVersionResponseV2_0 { Version?: number; VersionName?: string | null; Tags?: string[] | null; Date?: string; Deployed?: boolean; } interface DiscoveredResourceSummaryResponse { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; DetailsUrl?: string | null; ProjectVersion?: number | null; ProjectVersionName?: string | null; CreatedOn?: string | null; Description?: string | null; } interface Extractor { Id?: string | null; Name?: string | null; DocumentTypeId?: string | null; ResourceType?: ResourceType; Status?: ResourceStatus; DetailsUrl?: string | null; SyncUrl?: string | null; AsyncUrl?: string | null; ProjectVersion?: number | null; ProjectVersionName?: string | null; Description?: string | null; } interface GetClassifierDetailsDocumentTypeResponse { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; Type?: ClassifierDocumentTypeType; CreatedOn?: string | null; } interface GetClassifierDetailsResponse { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; Status?: ResourceStatus; DocumentTypes?: GetClassifierDetailsDocumentTypeResponse[] | null; CreatedOn?: string | null; SyncUrl?: string | null; AsyncUrl?: string | null; ProjectVersion?: number | null; ProjectVersionName?: string | null; Properties?: ProjectProperties[] | null; } interface GetClassifiersResponse { Classifiers?: Classifier[] | null; } interface GetDocumentTypeDetailsByTagResponseV2_0 { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; CreatedOn?: string | null; DocumentTaxonomy?: DocumentTaxonomy; } interface GetDocumentTypeDetailsResponseV2_0 { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; CreatedOn?: string | null; Classifiers?: DiscoveredResourceSummaryResponse[] | null; Extractors?: DiscoveredResourceSummaryResponse[] | null; } interface GetDocumentTypesResponse { DocumentTypes?: DiscoveredDocumentType[] | null; } interface GetExtractorDetailsResponseV2_0 { Id?: string | null; Name?: string | null; ResourceType?: ResourceType; Status?: ResourceStatus; ProjectId?: string; ProjectVersion?: number | null; ProjectVersionName?: string | null; DocumentTypeName?: string | null; DocumentTypeId?: string | null; CreatedOn?: string | null; SyncUrl?: string | null; AsyncUrl?: string | null; Description?: string | null; DocumentTaxonomy?: DocumentTaxonomy; } interface GetExtractorsResponse { Extractors?: Extractor[] | null; } interface GetProjectDetailsResponseV2_0 { Id?: string; Name?: string | null; Description?: string | null; Type?: ProjectType; Properties?: ProjectProperties[] | null; DocumentTypes?: DiscoveredResourceSummaryResponse[] | null; Classifiers?: DiscoveredResourceSummaryResponse[] | null; Extractors?: DiscoveredExtractorResourceSummaryResponse[] | null; ProjectVersions?: DiscoveredProjectVersionResponseV2_0[] | null; CreatedOn?: string | null; } interface GetProjectsResponse { Projects?: Project[] | null; } interface GetProjectTaxonomyResponse { DocumentTaxonomy?: DocumentTaxonomy; } interface GetTagsResponse { Tags?: TagEntity[] | null; } interface Project { Id?: string; Name?: string | null; Type?: ProjectType; Description?: string | null; CreatedOn?: string | null; DetailsUrl?: string | null; DigitizationStartUrl?: string | null; ClassifiersDiscoveryUrl?: string | null; ExtractorsDiscoveryUrl?: string | null; Properties?: ProjectProperties[] | null; } interface TagEntity { Name?: string | null; ProjectVersion?: number | null; ProjectVersionName?: string | null; Extractors?: TaggedExtractor[] | null; Classifiers?: TaggedClassifier[] | null; } interface TaggedClassifier { Name?: string | null; DocumentTypes?: DiscoveredDocumentType[] | null; SyncUrl?: string | null; AsyncUrl?: string | null; } interface TaggedExtractor { Name?: string | null; DocumentType?: DiscoveredDocumentType; SyncUrl?: string | null; AsyncUrl?: string | null; } interface ExtractionPromptRequestBody { Id?: string | null; Question?: string | null; FieldType?: GptFieldType; MultiValued?: boolean | null; } interface ExtractRequestBodyConfiguration { AutoValidationConfidenceThreshold?: number | null; } interface ExtractRequestBodyV2_0 { DocumentId?: string; PageRange?: string | null; Prompts?: ExtractionPromptRequestBody[] | null; Configuration?: ExtractRequestBodyConfiguration; DocumentTaxonomy?: DocumentTaxonomy; } interface ExtractSyncResult { ExtractionResult?: ExtractionResult; } interface StartExtractionResponse { OperationId?: string; ResultUrl?: string | null; } declare enum ModelKind { Extractor = "Extractor", Classifier = "Classifier" } declare enum ModelType { IXP = "IXP", Modern = "Modern", Predefined = "Predefined" } interface FolderBasedStartExtractionRequest { DocumentId?: string; DocumentTaxonomy?: DocumentTaxonomy; PageRange?: string | null; } interface FolderBasedStartExtractionResponse { OperationId?: string; ResultUrl?: string | null; } interface FolderModelsResponse { FolderKey?: string | null; FullyQualifiedName?: string | null; Models?: ModelSummaryResponse[] | null; } interface GetModelDetailsResponse { FullyQualifiedName?: string | null; ModelDisplayName?: string | null; Kind?: ModelKind; Type?: ModelType; Description?: string | null; AsyncDigitizationUrl?: string | null; AsyncExtractionUrl?: string | null; DocumentTaxonomy?: DocumentTaxonomy; } interface GetModelsResponse { Folders?: FolderModelsResponse[] | null; } interface ModelSummaryResponse { ModelName?: string | null; ModelDisplayName?: string | null; Description?: string | null; Kind?: ModelKind; Type?: ModelType; FullyQualifiedName?: string | null; DetailsUrl?: string | null; AsyncDigitizationUrl?: string | null; AsyncExtractionUrl?: string | null; } declare enum ActionStatus { Unassigned = "Unassigned", Pending = "Pending", Completed = "Completed" } interface ClassificationValidationResult { ActionStatus?: ActionStatus; ActionData?: DocumentClassificationActionDataModel; ValidatedClassificationResults?: ClassificationResult[] | null; } interface ExtractionValidationArtifactsResult { ValidatedExtractionResults?: ExtractionResult; } interface ExtractionValidationResult { ActionStatus?: ActionStatus; ActionData?: DocumentExtractionActionDataModel; ValidatedExtractionResults?: ExtractionResult; DataProjection?: FieldGroupValueProjection[] | null; } interface GetClassificationValidationTaskResponse { Status?: JobStatus; Error?: ErrorResponse; CreatedAt?: string; LastUpdatedAt?: string; Result?: ClassificationValidationResult; } interface GetExtractionValidationArtifactsResultTaskResponse { Result?: ExtractionValidationArtifactsResult; } interface GetExtractionValidationArtifactsTaskResponse { Status?: JobStatus; Error?: ErrorResponse; CreatedAt?: string; LastUpdatedAt?: string; ContentValidationData?: ContentValidationData; } interface GetExtractionValidationTaskResponse { Status?: JobStatus; Error?: ErrorResponse; CreatedAt?: string; LastUpdatedAt?: string; Result?: ExtractionValidationResult; } interface StartClassificationValidationTaskRequest { DocumentId?: string | null; ActionTitle?: string | null; ActionPriority?: CreateTaskPriority; ActionCatalog?: string | null; ActionFolder?: string | null; StorageBucketName?: string | null; StorageBucketDirectoryPath?: string | null; Prompts?: ClassificationPrompt[] | null; Configuration?: ClassificationValidationConfiguration; ClassificationResults?: ClassificationResult[] | null; } interface StartExtractionValidationArtifactsRequest { DocumentId?: string; ExtractionResult?: ExtractionResult; DocumentTaxonomy?: DocumentTaxonomy; FolderName?: string | null; StorageBucketName?: string | null; StorageBucketDirectoryPath?: string | null; } interface StartExtractionValidationTaskRequestV2_0 { DocumentId?: string | null; ActionTitle?: string | null; ActionPriority?: CreateTaskPriority; ActionCatalog?: string | null; ActionFolder?: string | null; StorageBucketName?: string | null; StorageBucketDirectoryPath?: string | null; Prompts?: ExtractionPrompt[] | null; ExtractionResult?: ExtractionResult; Configuration?: ExtractionValidationConfigurationV2; DocumentTaxonomy?: DocumentTaxonomy; } interface StartValidationArtifactsTaskResponse { OperationId?: string; ArtifactsUrl?: string | null; ResultUrl?: string | null; } interface StartValidationTaskResponse { OperationId?: string; ResultUrl?: string | null; } interface ClassificationValidationFinishedTaskInfo { Id?: number; Title?: string | null; Priority?: DocumentActionPriority; Status?: ActionStatus; CreationTime?: string; CompletionTime?: string | null; LastAssignedTime?: string; Url?: string | null; AssignedToUser?: string | null; CompletedByUser?: string | null; LastModifierUser?: string | null; DocumentRejectionReason?: string | null; CatalogName?: string | null; FolderName?: string | null; ProcessingTime?: number | null; } interface FinishExtractionValidationTaskInfo { Id?: number; Title?: string | null; Priority?: DocumentActionPriority; Status?: ActionStatus; CreationTime?: string; CompletionTime?: string | null; LastAssignedTime?: string; Url?: string | null; AssignedToUser?: string | null; CompletedByUser?: string | null; LastModifierUser?: string | null; DocumentRejectionReason?: string | null; CatalogName?: string | null; FolderName?: string | null; ProcessingTime?: number | null; } interface StartClassificationValidationTaskInfo { Id?: number; Title?: string | null; FolderName?: string | null; StorageBucketName?: string | null; StorageBucketDirectoryPath?: string | null; CatalogName?: string | null; Priority?: DocumentActionPriority; Status?: ActionStatus; } interface StartExtractionValidationTaskInfo { Id?: number; Title?: string | null; FolderName?: string | null; StorageBucketName?: string | null; StorageBucketDirectoryPath?: string | null; CatalogName?: string | null; Priority?: DocumentActionPriority; Status?: ActionStatus; } interface TrackFinishClassificationValidationRequest { ClassifierId?: string | null; Tag?: string | null; DocumentId?: string; Task?: ClassificationValidationFinishedTaskInfo; ClassificationResult?: ClassificationResult[] | null; } interface TrackFinishExtractionValidationRequest { ExtractorId?: string | null; Tag?: string | null; DocumentTypeId?: string | null; DocumentId?: string; Task?: FinishExtractionValidationTaskInfo; ExtractionResult?: ExtractionResult; ValidatedExtractionResult?: ExtractionResult; } interface TrackStartClassificationValidationRequest { ClassifierId?: string | null; Tag?: string | null; DocumentId?: string; Duration?: number; Task?: StartClassificationValidationTaskInfo; ClassificationResult?: ClassificationResult[] | null; } interface TrackStartExtractionValidationRequest { ExtractorId?: string | null; Tag?: string | null; DocumentTypeId?: string | null; DocumentId?: string; Duration?: number; Task?: StartExtractionValidationTaskInfo; ExtractionResult?: ExtractionResult; } interface GetClassificationResultResponse { Status?: JobStatus; CreatedAt?: string; LastUpdatedAt?: string; Error?: ErrorResponse; Result?: ClassificationResponse; } interface GetDigitizeJobResponse { Status?: JobStatus; Error?: ErrorResponse; Result?: GetDigitizeJobResult; CreatedAt?: string; LastUpdatedAt?: string; } interface GetDigitizeJobResult { DocumentObjectModel?: DocumentEntity; DocumentText?: string | null; } interface GetExtractionResultResponse { Status?: JobStatus; CreatedAt?: string; LastUpdatedAt?: string; Error?: ErrorResponse; Result?: ExtractSyncResult; } type index_ActionStatus = ActionStatus; declare const index_ActionStatus: typeof ActionStatus; type index_ClassificationPrompt = ClassificationPrompt; type index_ClassificationRequestBody = ClassificationRequestBody; type index_ClassificationResponse = ClassificationResponse; type index_ClassificationResult = ClassificationResult; type index_ClassificationValidationConfiguration = ClassificationValidationConfiguration; type index_ClassificationValidationFinishedTaskInfo = ClassificationValidationFinishedTaskInfo; type index_ClassificationValidationResult = ClassificationValidationResult; type index_Classifier = Classifier; type index_ClassifierDocumentTypeType = ClassifierDocumentTypeType; declare const index_ClassifierDocumentTypeType: typeof ClassifierDocumentTypeType; type index_ComparisonOperator = ComparisonOperator; declare const index_ComparisonOperator: typeof ComparisonOperator; type index_ContentValidationData = ContentValidationData; type index_CreateTaskPriority = CreateTaskPriority; declare const index_CreateTaskPriority: typeof CreateTaskPriority; type index_Criticality = Criticality; declare const index_Criticality: typeof Criticality; type index_DataDeletionRequest = DataDeletionRequest; type index_DataSource = DataSource; type index_DiscoveredDocumentType = DiscoveredDocumentType; type index_DiscoveredExtractorResourceSummaryResponse = DiscoveredExtractorResourceSummaryResponse; type index_DiscoveredProjectVersionResponseV2_0 = DiscoveredProjectVersionResponseV2_0; type index_DiscoveredResourceSummaryResponse = DiscoveredResourceSummaryResponse; type index_DocumentActionPriority = DocumentActionPriority; declare const index_DocumentActionPriority: typeof DocumentActionPriority; type index_DocumentActionStatus = DocumentActionStatus; declare const index_DocumentActionStatus: typeof DocumentActionStatus; type index_DocumentActionType = DocumentActionType; declare const index_DocumentActionType: typeof DocumentActionType; type index_DocumentClassificationActionDataModel = DocumentClassificationActionDataModel; type index_DocumentEntity = DocumentEntity; type index_DocumentExtractionActionDataModel = DocumentExtractionActionDataModel; type index_DocumentGroup = DocumentGroup; type index_DocumentTaxonomy = DocumentTaxonomy; type index_DocumentTypeEntity = DocumentTypeEntity; type index_ErrorResponse = ErrorResponse; type index_ErrorSeverity = ErrorSeverity; declare const index_ErrorSeverity: typeof ErrorSeverity; type index_ExceptionReasonOption = ExceptionReasonOption; type index_ExtractRequestBodyConfiguration = ExtractRequestBodyConfiguration; type index_ExtractRequestBodyV2_0 = ExtractRequestBodyV2_0; type index_ExtractSyncResult = ExtractSyncResult; type index_ExtractionPrompt = ExtractionPrompt; type index_ExtractionPromptRequestBody = ExtractionPromptRequestBody; type index_ExtractionResult = ExtractionResult; type index_ExtractionValidationArtifactsResult = ExtractionValidationArtifactsResult; type index_ExtractionValidationConfigurationV2 = ExtractionValidationConfigurationV2; type index_ExtractionValidationResult = ExtractionValidationResult; type index_Extractor = Extractor; type index_ExtractorPayload = ExtractorPayload; type index_Field = Field; type index_FieldGroupValueProjection = FieldGroupValueProjection; type index_FieldType = FieldType; declare const index_FieldType: typeof FieldType; type index_FieldValue = FieldValue; type index_FieldValueProjection = FieldValueProjection; type index_FieldValueResult = FieldValueResult; type index_FinishExtractionValidationTaskInfo = FinishExtractionValidationTaskInfo; type index_FolderBasedStartExtractionRequest = FolderBasedStartExtractionRequest; type index_FolderBasedStartExtractionResponse = FolderBasedStartExtractionResponse; type index_FolderModelsResponse = FolderModelsResponse; type index_GetClassificationResultResponse = GetClassificationResultResponse; type index_GetClassificationValidationTaskResponse = GetClassificationValidationTaskResponse; type index_GetClassifierDetailsDocumentTypeResponse = GetClassifierDetailsDocumentTypeResponse; type index_GetClassifierDetailsResponse = GetClassifierDetailsResponse; type index_GetClassifiersResponse = GetClassifiersResponse; type index_GetDigitizeJobResponse = GetDigitizeJobResponse; type index_GetDigitizeJobResult = GetDigitizeJobResult; type index_GetDocumentTypeDetailsByTagResponseV2_0 = GetDocumentTypeDetailsByTagResponseV2_0; type index_GetDocumentTypeDetailsResponseV2_0 = GetDocumentTypeDetailsResponseV2_0; type index_GetDocumentTypesResponse = GetDocumentTypesResponse; type index_GetExtractionResultResponse = GetExtractionResultResponse; type index_GetExtractionValidationArtifactsResultTaskResponse = GetExtractionValidationArtifactsResultTaskResponse; type index_GetExtractionValidationArtifactsTaskResponse = GetExtractionValidationArtifactsTaskResponse; type index_GetExtractionValidationTaskResponse = GetExtractionValidationTaskResponse; type index_GetExtractorDetailsResponseV2_0 = GetExtractorDetailsResponseV2_0; type index_GetExtractorsResponse = GetExtractorsResponse; type index_GetModelDetailsResponse = GetModelDetailsResponse; type index_GetModelsResponse = GetModelsResponse; type index_GetProjectDetailsResponseV2_0 = GetProjectDetailsResponseV2_0; type index_GetProjectTaxonomyResponse = GetProjectTaxonomyResponse; type index_GetProjectsResponse = GetProjectsResponse; type index_GetTagsResponse = GetTagsResponse; type index_GptFieldType = GptFieldType; declare const index_GptFieldType: typeof GptFieldType; type index_JobStatus = JobStatus; declare const index_JobStatus: typeof JobStatus; type index_LanguageInfo = LanguageInfo; type index_LogicalOperator = LogicalOperator; declare const index_LogicalOperator: typeof LogicalOperator; type index_MarkupType = MarkupType; declare const index_MarkupType: typeof MarkupType; type index_Metadata = Metadata; type index_MetadataEntry = MetadataEntry; type index_ModelKind = ModelKind; declare const index_ModelKind: typeof ModelKind; type index_ModelSummaryResponse = ModelSummaryResponse; type index_ModelType = ModelType; declare const index_ModelType: typeof ModelType; type index_Page = Page; type index_PageMarkup = PageMarkup; type index_PageSection = PageSection; type index_ProcessingSource = ProcessingSource; declare const index_ProcessingSource: typeof ProcessingSource; type index_Project = Project; type index_ProjectProperties = ProjectProperties; declare const index_ProjectProperties: typeof ProjectProperties; type index_ProjectType = ProjectType; declare const index_ProjectType: typeof ProjectType; type index_ReportAsExceptionSettings = ReportAsExceptionSettings; type index_ResourceStatus = ResourceStatus; declare const index_ResourceStatus: typeof ResourceStatus; type index_ResourceType = ResourceType; declare const index_ResourceType: typeof ResourceType; type index_ResultsContentReference = ResultsContentReference; type index_ResultsDataPoint = ResultsDataPoint; type index_ResultsDataSource = ResultsDataSource; declare const index_ResultsDataSource: typeof ResultsDataSource; type index_ResultsDerivedField = ResultsDerivedField; type index_ResultsDocument = ResultsDocument; type index_ResultsDocumentBounds = ResultsDocumentBounds; type index_ResultsTable = ResultsTable; type index_ResultsTableCell = ResultsTableCell; type index_ResultsTableColumnInfo = ResultsTableColumnInfo; type index_ResultsTableValue = ResultsTableValue; type index_ResultsValue = ResultsValue; type index_ResultsValueTokens = ResultsValueTokens; type index_Rotation = Rotation; declare const index_Rotation: typeof Rotation; type index_Rule = Rule; type index_RuleResult = RuleResult; type index_RuleSet = RuleSet; type index_RuleSetResult = RuleSetResult; type index_RuleType = RuleType; declare const index_RuleType: typeof RuleType; type index_SectionType = SectionType; declare const index_SectionType: typeof SectionType; type index_StartClassificationResponse = StartClassificationResponse; type index_StartClassificationValidationTaskInfo = StartClassificationValidationTaskInfo; type index_StartClassificationValidationTaskRequest = StartClassificationValidationTaskRequest; type index_StartDigitizationFromAttachmentModel = StartDigitizationFromAttachmentModel; type index_StartDigitizationResponse = StartDigitizationResponse; type index_StartExtractionResponse = StartExtractionResponse; type index_StartExtractionValidationArtifactsRequest = StartExtractionValidationArtifactsRequest; type index_StartExtractionValidationTaskInfo = StartExtractionValidationTaskInfo; type index_StartExtractionValidationTaskRequestV2_0 = StartExtractionValidationTaskRequestV2_0; type index_StartValidationArtifactsTaskResponse = StartValidationArtifactsTaskResponse; type index_StartValidationTaskResponse = StartValidationTaskResponse; type index_SwaggerGetDigitizeJobResponse = SwaggerGetDigitizeJobResponse; type index_SwaggerGetDigitizeJobResult = SwaggerGetDigitizeJobResult; type index_TagEntity = TagEntity; type index_TaggedClassifier = TaggedClassifier; type index_TaggedExtractor = TaggedExtractor; type index_TextType = TextType; declare const index_TextType: typeof TextType; type index_TrackFinishClassificationValidationRequest = TrackFinishClassificationValidationRequest; type index_TrackFinishExtractionValidationRequest = TrackFinishExtractionValidationRequest; type index_TrackStartClassificationValidationRequest = TrackStartClassificationValidationRequest; type index_TrackStartExtractionValidationRequest = TrackStartExtractionValidationRequest; type index_TypeField = TypeField; type index_UserData = UserData; type index_ValidationDisplayMode = ValidationDisplayMode; declare const index_ValidationDisplayMode: typeof ValidationDisplayMode; type index_Word = Word; type index_WordGroup = WordGroup; type index_WordGroupType = WordGroupType; declare const index_WordGroupType: typeof WordGroupType; declare namespace index { export { index_ActionStatus as ActionStatus, index_ClassifierDocumentTypeType as ClassifierDocumentTypeType, index_ComparisonOperator as ComparisonOperator, index_CreateTaskPriority as CreateTaskPriority, index_Criticality as Criticality, index_DocumentActionPriority as DocumentActionPriority, index_DocumentActionStatus as DocumentActionStatus, index_DocumentActionType as DocumentActionType, index_ErrorSeverity as ErrorSeverity, index_FieldType as FieldType, index_GptFieldType as GptFieldType, index_JobStatus as JobStatus, index_LogicalOperator as LogicalOperator, index_MarkupType as MarkupType, index_ModelKind as ModelKind, index_ModelType as ModelType, index_ProcessingSource as ProcessingSource, index_ProjectProperties as ProjectProperties, index_ProjectType as ProjectType, index_ResourceStatus as ResourceStatus, index_ResourceType as ResourceType, index_ResultsDataSource as ResultsDataSource, index_Rotation as Rotation, index_RuleType as RuleType, index_SectionType as SectionType, index_TextType as TextType, index_ValidationDisplayMode as ValidationDisplayMode, index_WordGroupType as WordGroupType }; export type { index_ClassificationPrompt as ClassificationPrompt, index_ClassificationRequestBody as ClassificationRequestBody, index_ClassificationResponse as ClassificationResponse, index_ClassificationResult as ClassificationResult, index_ClassificationValidationConfiguration as ClassificationValidationConfiguration, index_ClassificationValidationFinishedTaskInfo as ClassificationValidationFinishedTaskInfo, index_ClassificationValidationResult as ClassificationValidationResult, index_Classifier as Classifier, index_ContentValidationData as ContentValidationData, index_DataDeletionRequest as DataDeletionRequest, index_DataSource as DataSource, index_DiscoveredDocumentType as DiscoveredDocumentType, index_DiscoveredExtractorResourceSummaryResponse as DiscoveredExtractorResourceSummaryResponse, index_DiscoveredProjectVersionResponseV2_0 as DiscoveredProjectVersionResponseV2_0, index_DiscoveredResourceSummaryResponse as DiscoveredResourceSummaryResponse, index_DocumentClassificationActionDataModel as DocumentClassificationActionDataModel, index_DocumentEntity as DocumentEntity, index_DocumentExtractionActionDataModel as DocumentExtractionActionDataModel, index_DocumentGroup as DocumentGroup, index_DocumentTaxonomy as DocumentTaxonomy, index_DocumentTypeEntity as DocumentTypeEntity, index_ErrorResponse as ErrorResponse, index_ExceptionReasonOption as ExceptionReasonOption, index_ExtractRequestBodyConfiguration as ExtractRequestBodyConfiguration, index_ExtractRequestBodyV2_0 as ExtractRequestBodyV2_0, index_ExtractSyncResult as ExtractSyncResult, index_ExtractionPrompt as ExtractionPrompt, index_ExtractionPromptRequestBody as ExtractionPromptRequestBody, index_ExtractionResult as ExtractionResult, index_ExtractionValidationArtifactsResult as ExtractionValidationArtifactsResult, index_ExtractionValidationConfigurationV2 as ExtractionValidationConfigurationV2, index_ExtractionValidationResult as ExtractionValidationResult, index_Extractor as Extractor, index_ExtractorPayload as ExtractorPayload, index_Field as Field, index_FieldGroupValueProjection as FieldGroupValueProjection, index_FieldValue as FieldValue, index_FieldValueProjection as FieldValueProjection, index_FieldValueResult as FieldValueResult, index_FinishExtractionValidationTaskInfo as FinishExtractionValidationTaskInfo, index_FolderBasedStartExtractionRequest as FolderBasedStartExtractionRequest, index_FolderBasedStartExtractionResponse as FolderBasedStartExtractionResponse, index_FolderModelsResponse as FolderModelsResponse, index_GetClassificationResultResponse as GetClassificationResultResponse, index_GetClassificationValidationTaskResponse as GetClassificationValidationTaskResponse, index_GetClassifierDetailsDocumentTypeResponse as GetClassifierDetailsDocumentTypeResponse, index_GetClassifierDetailsResponse as GetClassifierDetailsResponse, index_GetClassifiersResponse as GetClassifiersResponse, index_GetDigitizeJobResponse as GetDigitizeJobResponse, index_GetDigitizeJobResult as GetDigitizeJobResult, index_GetDocumentTypeDetailsByTagResponseV2_0 as GetDocumentTypeDetailsByTagResponseV2_0, index_GetDocumentTypeDetailsResponseV2_0 as GetDocumentTypeDetailsResponseV2_0, index_GetDocumentTypesResponse as GetDocumentTypesResponse, index_GetExtractionResultResponse as GetExtractionResultResponse, index_GetExtractionValidationArtifactsResultTaskResponse as GetExtractionValidationArtifactsResultTaskResponse, index_GetExtractionValidationArtifactsTaskResponse as GetExtractionValidationArtifactsTaskResponse, index_GetExtractionValidationTaskResponse as GetExtractionValidationTaskResponse, index_GetExtractorDetailsResponseV2_0 as GetExtractorDetailsResponseV2_0, index_GetExtractorsResponse as GetExtractorsResponse, index_GetModelDetailsResponse as GetModelDetailsResponse, index_GetModelsResponse as GetModelsResponse, index_GetProjectDetailsResponseV2_0 as GetProjectDetailsResponseV2_0, index_GetProjectTaxonomyResponse as GetProjectTaxonomyResponse, index_GetProjectsResponse as GetProjectsResponse, index_GetTagsResponse as GetTagsResponse, index_LanguageInfo as LanguageInfo, index_Metadata as Metadata, index_MetadataEntry as MetadataEntry, index_ModelSummaryResponse as ModelSummaryResponse, index_Page as Page, index_PageMarkup as PageMarkup, index_PageSection as PageSection, index_Project as Project, index_ReportAsExceptionSettings as ReportAsExceptionSettings, index_ResultsContentReference as ResultsContentReference, index_ResultsDataPoint as ResultsDataPoint, index_ResultsDerivedField as ResultsDerivedField, index_ResultsDocument as ResultsDocument, index_ResultsDocumentBounds as ResultsDocumentBounds, index_ResultsTable as ResultsTable, index_ResultsTableCell as ResultsTableCell, index_ResultsTableColumnInfo as ResultsTableColumnInfo, index_ResultsTableValue as ResultsTableValue, index_ResultsValue as ResultsValue, index_ResultsValueTokens as ResultsValueTokens, index_Rule as Rule, index_RuleResult as RuleResult, index_RuleSet as RuleSet, index_RuleSetResult as RuleSetResult, index_StartClassificationResponse as StartClassificationResponse, index_StartClassificationValidationTaskInfo as StartClassificationValidationTaskInfo, index_StartClassificationValidationTaskRequest as StartClassificationValidationTaskRequest, index_StartDigitizationFromAttachmentModel as StartDigitizationFromAttachmentModel, index_StartDigitizationResponse as StartDigitizationResponse, index_StartExtractionResponse as StartExtractionResponse, index_StartExtractionValidationArtifactsRequest as StartExtractionValidationArtifactsRequest, index_StartExtractionValidationTaskInfo as StartExtractionValidationTaskInfo, index_StartExtractionValidationTaskRequestV2_0 as StartExtractionValidationTaskRequestV2_0, index_StartValidationArtifactsTaskResponse as StartValidationArtifactsTaskResponse, index_StartValidationTaskResponse as StartValidationTaskResponse, index_SwaggerGetDigitizeJobResponse as SwaggerGetDigitizeJobResponse, index_SwaggerGetDigitizeJobResult as SwaggerGetDigitizeJobResult, index_TagEntity as TagEntity, index_TaggedClassifier as TaggedClassifier, index_TaggedExtractor as TaggedExtractor, index_TrackFinishClassificationValidationRequest as TrackFinishClassificationValidationRequest, index_TrackFinishExtractionValidationRequest as TrackFinishExtractionValidationRequest, index_TrackStartClassificationValidationRequest as TrackStartClassificationValidationRequest, index_TrackStartExtractionValidationRequest as TrackStartExtractionValidationRequest, index_TypeField as TypeField, index_UserData as UserData, index_Word as Word, index_WordGroup as WordGroup }; } /** * Governance Service Types * * Public types exposed via `@uipath/uipath-typescript/governance`. */ declare enum PolicyEvaluationResult { /** Active policy permitted the action. */ Allow = "Allow", /** Active policy blocked the action. */ Deny = "Deny", /** Simulated (NoOp) policy would have permitted the action. */ SimulatedAllow = "SimulatedAllow", /** Simulated (NoOp) policy would have blocked the action. */ SimulatedDeny = "SimulatedDeny" } /** * Each trace row represents one policy's verdict within a governance * enforcement event. One enforcement event can produce multiple trace rows * when multiple policies contributed to the final verdict. */ interface GovernancePolicyTrace { /** Tenant the trace was recorded in. Present even when `fullOrganization` is `true`. */ tenantId?: string; /** The start time of governance enforcement event. */ startTime: string; /** Final enforcement verdict for the parent governance event. */ finalEnforcement?: string; /** ID of the policy this trace row evaluates. */ policyId?: string; /** This individual policy's enforcement contribution to the parent verdict. */ policyEnforcement?: string; /** The outcome of one policy evaluation — whether it allowed or denied the action, and whether that decision was actively enforced or just simulated (NoOp). */ policyEvaluationResult?: string; /** Display name of the policy. */ policyName?: string; /** Enforcement mode of the policy at the time of evaluation. */ policyStatus?: string; /** Opaque details payload describing the evaluation result. */ policyEvaluationDetails?: string; /** Process or executable that triggered the evaluation. */ actorProcessId?: string; /** Type of the actor process (e.g. coded agent, RPA process). */ actorProcessType?: string; /** Identity (user/principal) that triggered the evaluation. */ actorIdentityId?: string; /** Resource being acted on. */ resourceId?: string; /** Type of the resource being acted on. */ resourceType?: string; /** Orchestrator folder key associated with the evaluation, if any. */ folderKey?: string; /** Distributed-tracing ID covering the governance enforcement event. */ traceId?: string; /** Process key associated with the evaluation, if any. */ processKey?: string; /** Job key associated with the evaluation, if any. */ jobKey?: string; } /** * Common filter options shared across Governance APIs. * * Holds filters that are not specific to any single governance resource, so * other governance endpoints can reuse them. */ interface GovernanceFilterOptions { /** * Inclusive upper bound on trace start time. When omitted, the upper bound * is open. */ endTime?: Date; /** * Whether to query the whole organization instead of just the current tenant. * * Defaults to tenant-scoped: * - omitted → tenant-scoped (default) * - `false` → tenant-scoped (explicit, same result) * - `true` → org-wide across all tenants; requires an organization admin, * otherwise the request returns 403 * * @default false */ fullOrganization?: boolean; } /** * Filter and pagination options for fetching policy traces. * * All filters combine with AND semantics. Array filters match any value in * the array (OR within a single filter). */ type GovernancePolicyTraceGetAllOptions = PaginationOptions & GovernanceFilterOptions & { /** Filter by one or more policy evaluation results. */ evaluationResult?: PolicyEvaluationResult[]; /** Filter by one or more policy IDs. */ policyId?: string[]; /** Filter by one or more actor process IDs. */ actorProcessId?: string[]; /** Filter by one or more actor process types (e.g. coded agent, RPA process). */ actorProcessType?: string[]; /** Filter by one or more actor identity IDs. */ actorIdentityId?: string[]; /** Filter by one or more resource IDs. */ resourceId?: string[]; /** Filter by one or more resource types. */ resourceType?: string[]; /** Filter by one or more distributed-trace IDs. */ traceId?: string[]; }; /** * Aggregate governance enforcement counts returned by * {@link GovernanceServiceModel.getOperationSummary}, covering the requested * time range. */ interface GovernanceOperationSummary { /** Total number of governance enforcement evaluations in range. */ totalEvaluations: number; /** Number of evaluations that resolved to `Allow`. */ allowedCount: number; /** Number of evaluations that resolved to `Deny`. */ deniedCount: number; /** Number of evaluations that resolved to `NoOp` (simulated). */ noOpCount: number; } /** * * @experimental * * /// warning * Preview: This service is experimental and may change or be removed in future releases. * /// * * Service for inspecting governance policy enforcement on the UiPath platform. * * See [Define governance policies](https://docs.uipath.com/automation-ops/automation-cloud/latest/user-guide/define-governance-policies) * for how governance policies are configured in Automation Ops. * * All methods require the caller to be an organization administrator. * * ### Usage * * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize) * * ```typescript * import { Governance } from '@uipath/uipath-typescript/governance'; * * const governance = new Governance(sdk); * const traces = await governance.getPolicyTraces(new Date('2024-01-01')); * ``` */ interface GovernanceServiceModel { /** * Gets per-policy enforcement decisions across the requested time range. * * @experimental * * /// warning * Preview: This method is experimental and may change or be removed in future releases. * /// * * Each result row represents one policy's verdict within a single governance enforcement event. * A single user action can produce multiple rows when multiple policies were consulted. * Results are ordered by event start time, descending. * * @param startTime - Inclusive lower bound on the trace start time. * @param options - Optional filters and pagination options * @returns Promise resolving to {@link NonPaginatedResponse} of {@link GovernancePolicyTrace} * without pagination options, or {@link PaginatedResponse} of * {@link GovernancePolicyTrace} when pagination options are used. * * @example * ```typescript * import { Governance, PolicyEvaluationResult } from '@uipath/uipath-typescript/governance'; * * const governance = new Governance(sdk); * * // Get all policy traces from the specified start time * const recent = await governance.getPolicyTraces(new Date('2024-01-01')); * console.log(recent.items.length); * * // Get all denied decisions across the whole organization * const page1 = await governance.getPolicyTraces( * new Date('2024-01-01'), * { * endTime: new Date(), * evaluationResult: [PolicyEvaluationResult.Deny, PolicyEvaluationResult.SimulatedDeny], * fullOrganization: true, * pageSize: 25, * }, * ); * * if (page1.hasNextPage) { * const page2 = await governance.getPolicyTraces( * new Date('2024-01-01'), * { cursor: page1.nextCursor }, * ); * } * ``` */ getPolicyTraces(startTime: Date, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Gets aggregate governance enforcement counts across the requested time range. * * @experimental * * /// warning * Preview: This method is experimental and may change or be removed in future releases. * /// * * Returns the total number of evaluations along with how many resolved to * `Allow`, `Deny`, or `NoOp`. * * @param startTime - Inclusive lower bound on the evaluation time. * @param options - Optional `endTime` upper bound and `fullOrganization` flag * @returns Promise resolving to {@link GovernanceOperationSummary} * * @example * ```typescript * import { Governance } from '@uipath/uipath-typescript/governance'; * * const governance = new Governance(sdk); * * // Get operation summary from the specified start time to right now * const summary = await governance.getOperationSummary(new Date('2024-01-01')); * console.log(summary.totalEvaluations, summary.allowedCount, summary.deniedCount, summary.noOpCount); * * // Bounded range across the whole organization * const ranged = await governance.getOperationSummary( * new Date('2024-01-01'), * { endTime: new Date(), fullOrganization: true }, * ); * ``` */ getOperationSummary(startTime: Date, options?: GovernanceFilterOptions): Promise; } /** Status of a span: whether it completed successfully, with an error, or was not set. */ declare enum SpanStatus { Unset = "Unset", Ok = "Ok", Error = "Error", /** Span is still in progress. */ Running = "Running", /** Span data is hidden from the caller due to tenant/folder permission rules. */ Restricted = "Restricted", /** Span was cancelled before completion. */ Cancelled = "Cancelled" } /** Platform source that produced the span. */ declare enum SpanSource { Testing = "Testing", Agents = "Agents", ProcessOrchestration = "ProcessOrchestration", ApiWorkflows = "ApiWorkflows", Robots = "Robots", ConversationalAgentsService = "ConversationalAgentsService", IntegrationServiceTrigger = "IntegrationServiceTrigger", Playground = "Playground", Governance = "Governance", /** Intelligent Experience Platform — unstructured and complex document processing source. */ IXPUnstructuredAndComplexDocuments = "IXPUnstructuredAndComplexDocuments", /** Agents authored in code (as opposed to visual/no-code designers). */ CodedAgents = "CodedAgents", /** Intelligent Experience Platform — communications mining source. */ IXPCommunicationsMining = "IXPCommunicationsMining", /** UiPath Context Grounding — span produced by the Enterprise Context Service for RAG/knowledge-base operations. */ EnterpriseContextService = "EnterpriseContextService", /** Model Context Protocol — span produced by an MCP server integration. */ MCP = "MCP", /** Agent-to-Agent — span produced by an A2A protocol call between agents. */ A2A = "A2A", /** Serverless — span produced by a serverless function execution. */ Serverless = "Serverless" } /** Minimum severity level of events captured in the span. */ declare enum SpanVerbosityLevel { Verbose = "Verbose", Trace = "Trace", Information = "Information", Warning = "Warning", Error = "Error", Critical = "Critical", Off = "Off" } /** Whether the span was produced during a debug or production runtime. */ declare enum SpanExecutionType { Debug = "Debug", Runtime = "Runtime" } /** Whether the caller has permission to read this span's data. */ declare enum SpanPermissionStatus { Allow = "Allow", /** Some span fields are redacted due to permission constraints (e.g. attributes visible but payload hidden). */ PartialBlock = "PartialBlock", Block = "Block" } /** Storage provider that created or manages the attachment. */ declare enum SpanAttachmentProvider { Orchestrator = "Orchestrator", /** Span attachment stored by the observability platform. */ LLMOps = "LLMOps" } /** Whether the attachment is an input, output, or neither. */ declare enum SpanAttachmentDirection { None = "None", In = "In", Out = "Out" } /** One level in the reference hierarchy that produced this span. */ interface SpanReferenceHierarchyEntry { serviceType: string; referenceId: string; version: string | null; } /** Contextual lineage attached to the span (reference hierarchy). */ interface SpanContext { referenceHierarchy: SpanReferenceHierarchyEntry[]; } /** File or payload attachment linked to the span. */ interface SpanAttachment { provider: SpanAttachmentProvider; id: string; fileName: string; mimeType: string; direction: SpanAttachmentDirection; } /** A single execution span returned by the Traces API. */ interface SpanGetResponse { /** Unique identifier of this span (GUID). */ id: string; /** Trace this span belongs to (GUID). */ traceId: string; /** Parent span ID, or null for root spans. */ parentId: string | null; /** Human-readable name of the operation, or null if the span has no name. */ name: string | null; /** ISO-8601 UTC timestamp when the span started. */ startTime: string; /** ISO-8601 UTC timestamp when the span ended, or null if still running. */ endTime: string | null; /** * Span attributes (user-defined schema — do not transform keys). * Values depend on the span type and the agent that produced them. */ attributes: Record; /** Completion status of the span. */ status: SpanStatus; /** Platform source that produced the span. */ source: SpanSource | null; /** Span type tag (e.g. `"agentRun"`, `"llmCall"`). */ spanType: string | null; /** Minimum verbosity level captured in this span. */ verbosityLevel: SpanVerbosityLevel | null; /** Whether this span was from a debug or runtime execution. */ executionType: SpanExecutionType | null; /** Folder key (GUID) scoping this span. */ folderKey: string | null; /** Identifier of the entity (agent, process, etc.) that produced the span. */ referenceId: string | null; /** Version of the entity that produced the span. */ referenceVersion: string | null; /** Version of the agent runtime. */ agentVersion: string | null; /** Organization (account) GUID. */ organizationId: string; /** Tenant GUID. */ tenantId: string | null; /** Key of the process associated with this span. */ processKey: string | null; /** Key of the job associated with this span. */ jobKey: string | null; /** ISO-8601 UTC timestamp of last update. */ updatedAt: string; /** Expiry timestamp, or null if the span does not expire. */ expiredTime: string | null; /** Reference hierarchy context for this span. */ context: SpanContext | null; /** File or payload attachments linked to this span. */ attachments: SpanAttachment[] | null; /** Whether the caller can read this span's data. */ permissionStatus: SpanPermissionStatus | null; } /** Options for retrieving all spans belonging to a trace. */ interface TracesGetByIdOptions { /** Maximum number of spans to return. */ pageSize?: number; /** Filter spans to those produced by a specific agent ID. */ agentId?: string; /** When true, include expired spans that are outside the default retention window. */ includeExpiredSpans?: boolean; } /** * Service for querying UiPath execution traces (spans). * * Traces are OpenTelemetry-compatible execution records generated by agents, robots, * Maestro processes, conversational agents, and other UiPath execution sources. * The `source` field on each {@link SpanGetResponse} identifies the originating platform. * * @example * ```typescript * import { UiPath } from '@uipath/uipath-typescript/core'; * import { Traces } from '@uipath/uipath-typescript/traces'; * * const sdk = new UiPath(config); * await sdk.initialize(); * * const traces = new Traces(sdk); * const spans = await traces.getById(''); * ``` */ interface TracesServiceModel { /** * Gets all spans for a specific trace ID. * * Returns up to `pageSize` spans (default 1000) in a single fetch. * Accepts both GUID format and OTEL 32-char hex format — the API normalizes both. * * @param traceId - Trace identifier * @param options - Optional filters {@link TracesGetByIdOptions} * @returns Promise resolving to an array of {@link SpanGetResponse}, each containing span identity, timing, status, source platform, attributes, verbosity, execution type, lineage context, and any file attachments. * @example * ```typescript * import { Traces } from '@uipath/uipath-typescript/traces'; * * const traces = new Traces(sdk); * const spans = await traces.getById(''); * console.log(spans.length, spans[0].spanType, spans[0].status); * ``` * @example * ```typescript * // Filter to a specific agent's spans * const agentSpans = await traces.getById('', { * agentId: '', * pageSize: 500, * }); * ``` */ getById(traceId: string, options?: TracesGetByIdOptions): Promise; /** * Gets specific spans by trace ID and span IDs. * * Accepts OTEL 16-char hex or GUID format for span IDs. * * @param traceId - Trace identifier * @param spanIds - List of span IDs to retrieve * @returns Promise resolving to an array of matching {@link SpanGetResponse}, each containing span identity, timing, status, source platform, attributes, verbosity, execution type, lineage context, and any file attachments. * @example * ```typescript * import { Traces } from '@uipath/uipath-typescript/traces'; * * const traces = new Traces(sdk); * * // First retrieve all spans to find the IDs you want * const allSpans = await traces.getById(''); * const spanIds = allSpans.slice(0, 3).map(s => s.id); * * const subset = await traces.getSpansByIds('', spanIds); * ``` */ getSpansByIds(traceId: string, spanIds: string[]): Promise; } /** * Filter fields shared by the trace-level agent endpoints */ interface AgentTraceFilterOptions { /** Inclusive lower bound for the query window. Omit to use the server default (1 year ago). */ startTime?: Date; /** Exclusive upper bound for the query window. Omit to use the server default (now). */ endTime?: Date; /** Folder keys to scope the query. Intersected with the user's accessible folders. */ folderKeys?: string[]; /** Filter to a single agent by ID. */ agentId?: string; /** Filter to a specific agent version. */ agentVersion?: string; /** Filter to a specific execution type. */ executionType?: SpanExecutionType; } /** * One point on the trace-level errors timeline — error count for a single * (error name, time bucket). */ interface AgentTraceGetErrorsTimelineResponse { /** Error name / category for this time-slice. */ name: string; /** Count of errors in this time bucket for this name. */ value: number; /** Bucket timestamp. */ date: string; } /** * Options for the trace-level errors timeline. */ interface AgentTraceGetErrorsTimelineOptions extends AgentTraceFilterOptions { } /** * One point on the trace-level latency timeline — a latency value for a single * (series, time bucket). */ interface AgentTraceGetLatencyTimelineResponse { /** Series/grouping name for this latency point. */ name: string; /** Latency value in decimal seconds for this series and time bucket. */ value: number; /** Bucket timestamp. */ date: string; } /** * Options for the trace-level latency timeline. */ interface AgentTraceGetLatencyTimelineOptions extends AgentTraceFilterOptions { } /** * Per-agent unit consumption totals over the requested window (trace-level) — * a flat per-(agent, version, folder) breakdown of Agent Units and Platform Units consumed. */ interface AgentTraceGetUnitConsumptionResponse { /** Agent ID these totals belong to. */ agentId: string; /** Folder key (GUID) the consumption was recorded in. */ folderKey: string; /** Agent version these totals belong to. */ agentVersion: string; /** Agent units consumed over the window. */ agentUnitsConsumed: number; /** Platform units consumed over the window. */ platformUnitsConsumed: number; } /** * Options for the trace-level per-agent unit consumption. */ interface AgentTraceGetUnitConsumptionOptions extends AgentTraceFilterOptions { } /** * A single span record from the trace store. */ interface AgentSpanGetResponse { /** Span ID. */ id: string; /** ID of the trace this span belongs to. */ traceId: string; /** Parent span ID. `null` for a root span. */ parentId: string | null; /** Span name. */ name: string; /** Span start time. */ startTime: string; /** Span end time. `null` while the span is in progress. */ endTime: string | null; /** Raw span attributes as a JSON string. */ attributes: string; /** Span status. */ status: string; /** Organization ID (GUID). */ organizationId: string; /** Tenant ID (GUID). */ tenantId: string | null; /** Span retention expiry time. */ expiredTime: string | null; /** Folder key (GUID) the span was recorded in. */ folderKey: string | null; /** Span source. */ source: string | null; /** Span type. */ spanType: string | null; /** Process key (GUID). */ processKey: string | null; /** Job key (GUID). */ jobKey: string | null; /** Reference ID (GUID). */ referenceId: string | null; /** Verbosity level. */ verbosityLevel: string | null; /** Record last-updated time. */ updatedAt: string; /** Whether the span payload is stored as a large payload. */ isLargePayload: boolean; /** Payload compression type. */ compressionType: string | null; /** Agent version that produced the span. */ agentVersion: string | null; /** Raw span context as a JSON string. */ context: string | null; } /** * Options for the spans-by-reference query. * * Composes the optional hierarchy/time filters with pagination options. */ type AgentTraceGetSpansByReferenceOptions = PaginationOptions & { /** Optional trace scope — narrows the scan to a single trace. */ traceId?: string; /** Restrict matches to hierarchy entries with this service type. */ serviceType?: string; /** Restrict matches to hierarchy entries with this version. */ version?: string; /** Inclusive lower bound on span start time. */ startTime?: Date; /** Exclusive upper bound on span end time. */ endTime?: Date; /** Execution type filter */ executionType?: SpanExecutionType; }; /** * Evaluation mode of a governance decision. */ declare enum AgentGovernanceMode { /** Policy evaluated and logged, but not enforced. */ Audit = "AUDIT", /** Policy evaluated and enforced. */ Enforce = "ENFORCE", /** Unrecognized or missing mode. */ Unknown = "Unknown" } /** * Verdict of a governance decision (`Deny` = violation). */ declare enum AgentGovernanceVerdict { /** Allowed — not a violation. */ Allow = "ALLOW", /** Denied — counts as a violation. */ Deny = "DENY", /** Unrecognized or missing verdict. */ Unknown = "Unknown" } /** * A single governance decision — one policy's allow/deny result for an agent run. */ interface AgentGovernanceDecisionGetResponse { /** Tenant ID (GUID). */ tenantId: string | null; /** Decision window start time — ISO 8601, UTC. */ startTime: string; /** Decision window end time — ISO 8601, UTC. */ endTime: string | null; /** Trace ID (GUID). */ traceId: string | null; /** Job key (GUID). */ jobKey: string | null; /** Folder key (GUID). */ folderKey: string | null; /** Runtime the evaluator ran in (context, not a filter). */ source: string | null; /** Policy ID. */ policyId: string | null; /** Policy display name. */ policyName: string | null; /** Governance pack name. */ packName: string | null; /** Governance hook (e.g. `BEFORE_MODEL`). */ hook: string | null; /** Evaluation mode, normalized to {@link AgentGovernanceMode} ({@link AgentGovernanceMode.Unknown} when missing/unrecognized). */ mode: AgentGovernanceMode; /** Enforcement action applied. `null` in audit mode (no action enforced). */ actionApplied: string | null; /** Verdict, normalized to {@link AgentGovernanceVerdict} (`Deny` = violation). */ evaluatorResult: AgentGovernanceVerdict; /** Human-readable reason. */ reason: string | null; /** Resolved agent ID (GUID). */ agentId: string | null; /** Agent display name. */ agentName: string | null; } /** * Options for the governance decisions query — optional filters plus pagination. */ type AgentGovernanceDecisionsOptions = PaginationOptions & { /** Inclusive upper bound for the query window. Defaults to now when omitted. */ endTime?: Date; /** Filter on the governance hook. */ hook?: string; /** Filter on the verdict. */ evaluatorResult?: AgentGovernanceVerdict; /** Filter on a single policy ID. */ policyId?: string; /** Filter on a single agent by its project key. */ agentId?: string; /** When `true`, restrict to violations (deny verdicts). */ violationsOnly?: boolean; }; /** * One breakdown entry in the governance summary — counts for a single key. */ interface AgentGovernanceCountItem { /** The value this row groups by — the distinct hook, agent id, policy id, or pack name for this breakdown. */ key: string | null; /** Display name (populated for the policy and agent breakdowns). */ name: string | null; /** Number of decisions for this key. */ count: number; /** Number of violations (deny verdicts) for this key. */ violationCount: number; } /** * Sections the governance summary can compute. `action` and `mode` are opt-in. */ declare enum AgentGovernanceSection { /** Scalar totals (`total`, `violations`). */ Totals = "totals", /** Breakdown by governance hook. */ Hook = "hook", /** Breakdown by agent. */ Agent = "agent", /** Breakdown by policy. */ Policy = "policy", /** Breakdown by governance pack. */ Pack = "pack", /** Breakdown by enforcement action (opt-in). */ Action = "action", /** Breakdown by evaluation mode (opt-in). */ Mode = "mode" } /** * Aggregated governance posture over the requested window. */ interface AgentGovernanceGetSummaryResponse { /** Total decisions in the window. */ total: number; /** Total violations (deny verdicts). */ violations: number; /** Breakdown by governance hook. */ byHook: AgentGovernanceCountItem[]; /** Breakdown by agent. */ byAgent: AgentGovernanceCountItem[]; /** Breakdown by policy. */ byPolicy: AgentGovernanceCountItem[]; /** Breakdown by governance pack. */ byPack: AgentGovernanceCountItem[]; /** Breakdown by enforcement action. Empty unless `action` is requested in `sections`. */ byAction: AgentGovernanceCountItem[]; /** Breakdown by evaluation mode. Empty unless `mode` is requested in `sections`. */ byMode: AgentGovernanceCountItem[]; } /** * Options for the governance summary. */ interface AgentGovernanceSummaryOptions { /** Inclusive upper bound for the query window. Defaults to now when omitted. */ endTime?: Date; /** Top-N size for each breakdown. */ topN?: number; /** Restrict totals and breakdowns to a single governance pack. */ packName?: string; /** * Which sections to compute. Omit for the default set * (`totals`, `hook`, `agent`, `policy`, `pack`); `action` and `mode` are opt-in. */ sections?: AgentGovernanceSection[]; } /** * Service for retrieving UiPath Agent trace metrics. */ interface AgentTracesServiceModel { /** * Retrieves a trace-level time-series of error counts grouped by error name. * * @param options - Optional window and filters * @returns Promise resolving to an array of {@link AgentTraceGetErrorsTimelineResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * // Get the errors timeline * const result = await trace.getErrorsTimeline(); * result.forEach((point) => { * console.log(`${point.date} ${point.name}: ${point.value} errors`); * }); * ``` * @example * ```typescript * import { AgentTraceExecutionType } from '@uipath/uipath-typescript/traces'; * * // Get the errors timeline for an agent version within a time window * const filtered = await trace.getErrorsTimeline({ * startTime: new Date('2025-05-01T00:00:00Z'), * endTime: new Date('2025-06-01T00:00:00Z'), * agentId: '', * agentVersion: '1.0.0', * executionType: AgentTraceExecutionType.Runtime, * }); * ``` */ getErrorsTimeline(options?: AgentTraceGetErrorsTimelineOptions): Promise; /** * Retrieves a trace-level time-series of latency. * * @param options - Optional window and filters * @returns Promise resolving to an array of {@link AgentTraceGetLatencyTimelineResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * // Get the latency timeline * const result = await trace.getLatencyTimeline(); * result.forEach((point) => { * console.log(`${point.date} ${point.name}: ${point.value}s`); * }); * ``` * @example * ```typescript * import { AgentTraceExecutionType } from '@uipath/uipath-typescript/traces'; * * // Get the latency timeline for an agent version within a time window * const filtered = await trace.getLatencyTimeline({ * startTime: new Date('2025-05-01T00:00:00Z'), * endTime: new Date('2025-06-01T00:00:00Z'), * agentId: '', * agentVersion: '1.0.0', * executionType: AgentTraceExecutionType.Runtime, * }); * ``` */ getLatencyTimeline(options?: AgentTraceGetLatencyTimelineOptions): Promise; /** * Retrieves trace-level per-agent unit consumption totals. * * @param options - Optional window and filters * @returns Promise resolving to an array of {@link AgentTraceGetUnitConsumptionResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * // Get per-agent unit consumption * const result = await trace.getUnitConsumption(); * result.forEach((row) => { * console.log(`${row.agentId}: ${row.agentUnitsConsumed} Agent Units, ${row.platformUnitsConsumed} Platform Units`); * }); * ``` * @example * ```typescript * import { AgentTraceExecutionType } from '@uipath/uipath-typescript/traces'; * * // Get per-agent unit consumption for an agent version within a time window * const filtered = await trace.getUnitConsumption({ * startTime: new Date('2025-05-01T00:00:00Z'), * endTime: new Date('2025-06-01T00:00:00Z'), * agentId: '', * agentVersion: '1.0.0', * executionType: AgentTraceExecutionType.Runtime, * }); * ``` */ getUnitConsumption(options?: AgentTraceGetUnitConsumptionOptions): Promise; /** * Retrieves every span belonging to a single trace. * * @param traceId - Identifier of the trace whose spans should be returned * @returns Promise resolving to an array of {@link AgentSpanGetResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * const spans = await trace.getSpansByTraceId(''); * spans.forEach((span) => { * console.log(`${span.name} (${span.startTime} → ${span.endTime ?? 'in progress'})`); * }); * ``` */ getSpansByTraceId(traceId: string): Promise; /** * Retrieves spans whose reference hierarchy contains the given reference id. * * @param referenceId - Reference id matched against each span's reference hierarchy * @param options - Optional pagination and hierarchy/time filters * @returns Promise resolving to a paginated or non-paginated list of {@link AgentSpanGetResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * // Get spans by referenceId * const result = await trace.getSpansByReference(''); * result.items.forEach((span) => console.log(span.name)); * ``` * @example * ```typescript * import { AgentTraceExecutionType } from '@uipath/uipath-typescript/traces'; * * // Get spans by referenceId within a trace and time window * const page = await trace.getSpansByReference('', { * traceId: '', * executionType: AgentTraceExecutionType.Runtime, * startTime: new Date('2025-05-01T00:00:00Z'), * endTime: new Date('2025-06-01T00:00:00Z'), * pageSize: 25, * }); * * if (page.hasNextPage && page.nextCursor) { * const next = await trace.getSpansByReference('', { cursor: page.nextCursor }); * } * ``` */ getSpansByReference(referenceId: string, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Lists individual governance decisions from agent execution traces — each * policy check's allow/deny outcome with its agent, policy, pack, hook, and * mode, plus the trace it belongs to — over the requested window. Filterable * and paginated. * * @remarks Requires the caller to be an organization admin. Non-admin callers get a `403` and the SDK throws an {@link AuthorizationError}. * * @param startTime - Inclusive lower bound for the query window * @param options - Optional window end, filters, and pagination * @returns Promise resolving to a paginated or non-paginated list of {@link AgentGovernanceDecisionGetResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * // Decision rows since a start time * const result = await trace.getGovernanceDecisions(new Date('2025-05-01T00:00:00Z')); * result.items.forEach((row) => { * console.log(`${row.hook} ${row.policyId}: ${row.evaluatorResult}`); * }); * ``` * @example * ```typescript * // Violations only, for one agent, paginated * const page = await trace.getGovernanceDecisions(new Date('2025-05-01T00:00:00Z'), { * endTime: new Date('2025-06-01T00:00:00Z'), * violationsOnly: true, * agentId: '', * pageSize: 25, * }); * if (page.hasNextPage && page.nextCursor) { * const next = await trace.getGovernanceDecisions(new Date('2025-05-01T00:00:00Z'), { cursor: page.nextCursor }); * } * ``` * @example * ```typescript * import { isAuthorizationError } from '@uipath/uipath-typescript/core'; * * // Non-admin callers get a 403 * try { * await trace.getGovernanceDecisions(new Date('2025-05-01T00:00:00Z')); * } catch (error) { * if (isAuthorizationError(error)) { * console.error('Governance data requires an organization admin.'); * } * } * ``` */ getGovernanceDecisions(startTime: Date, options?: T): Promise ? PaginatedResponse : NonPaginatedResponse>; /** * Summarizes governance decisions across agent execution traces — total * decisions and violations, plus top breakdowns by hook, agent, policy, and * pack — over the requested window. Filterable. * * @remarks Requires the caller to be an organization admin. Non-admin callers get a `403` and the SDK throws an {@link AuthorizationError}. * * @param startTime - Inclusive lower bound for the query window * @param options - Optional window end, top-N, pack scope, and sections * @returns Promise resolving to {@link AgentGovernanceGetSummaryResponse} * @example * ```typescript * import { AgentTraces } from '@uipath/uipath-typescript/traces'; * * const trace = new AgentTraces(sdk); * * // Default posture since a start time * const summary = await trace.getGovernanceSummary(new Date('2025-05-01T00:00:00Z')); * console.log(`${summary.violations} / ${summary.total} violations`); * summary.byPolicy.forEach((p) => console.log(`${p.key}: ${p.violationCount}`)); * ``` * @example * ```typescript * import { AgentGovernanceSection } from '@uipath/uipath-typescript/traces'; * * // Top 5 per breakdown, scoped to a pack, including the opt-in action/mode sections * const summary = await trace.getGovernanceSummary(new Date('2025-05-01T00:00:00Z'), { * topN: 5, * packName: 'ISO/IEC 42001:2023 Runtime', * sections: [AgentGovernanceSection.Action, AgentGovernanceSection.Mode], * }); * ``` * @example * ```typescript * import { isAuthorizationError } from '@uipath/uipath-typescript/core'; * * // Non-admin callers get a 403 * try { * await trace.getGovernanceSummary(new Date('2025-05-01T00:00:00Z')); * } catch (error) { * if (isAuthorizationError(error)) { * console.error('Governance data requires an organization admin.'); * } * } * ``` */ getGovernanceSummary(startTime: Date, options?: AgentGovernanceSummaryOptions): Promise; } /** * Error thrown when authorization fails (403 errors) * Common scenarios: * - Insufficient permissions * - Access denied to resource * - Invalid scope */ declare class AuthorizationError extends UiPathError { constructor(params?: Partial); } /** * Error thrown when validation fails (400 errors or client-side validation) * Common scenarios: * - Invalid input parameters * - Missing required fields * - Invalid data format */ declare class ValidationError extends UiPathError { constructor(params?: Partial); } /** * Error thrown when a resource is not found (404 errors) * Common scenarios: * - Resource doesn't exist * - Invalid ID provided * - Resource deleted */ declare class NotFoundError extends UiPathError { constructor(params?: Partial); } /** * Error thrown when rate limit is exceeded (429 errors) * Common scenarios: * - Too many requests in a time window * - API throttling */ declare class RateLimitError extends UiPathError { constructor(params?: Partial); } /** * Error thrown when server encounters an error (5xx errors) * Common scenarios: * - Internal server error * - Service unavailable * - Gateway timeout */ declare class ServerError extends UiPathError { constructor(params?: Partial); /** * Checks if this is a temporary error that might succeed on retry */ get isRetryable(): boolean; } /** * Base error creation parameters - only what's needed */ interface ErrorParams { message: string; statusCode?: number; requestId?: string; } /** * Base error class for all UiPath SDK errors * Extends Error for standard error handling compatibility */ declare abstract class UiPathError extends Error { /** * Error type identifier (e.g., "AuthenticationError", "ValidationError") */ readonly type: string; /** * HTTP status code (400, 401, 403, 404, 500, etc.) */ readonly statusCode?: number; /** * Request ID for tracking with UiPath support */ readonly requestId?: string; /** * Timestamp when the error occurred */ readonly timestamp: Date; protected constructor(type: string, params: ErrorParams); /** * Returns a clean JSON representation of the error */ private toJSON; /** * Returns detailed debug information including stack trace */ getDebugInfo(): Record; } /** * Error thrown when authentication fails (401 errors) * Common scenarios: * - Invalid credentials * - Expired token * - Missing authentication */ declare class AuthenticationError extends UiPathError { constructor(params?: Partial); } /** * Error thrown when network/connection issues occur * Common scenarios: * - Connection timeout * - DNS resolution failure * - Network unreachable * - Request aborted */ declare class NetworkError extends UiPathError { constructor(params?: Partial); } /** * Type guard to check if an error is a UiPathError */ declare function isUiPathError(error: unknown): error is UiPathError; /** * Type guard to check if an error is an AuthenticationError */ declare function isAuthenticationError(error: unknown): error is AuthenticationError; /** * Type guard to check if an error is an AuthorizationError */ declare function isAuthorizationError(error: unknown): error is AuthorizationError; /** * Type guard to check if an error is a ValidationError */ declare function isValidationError(error: unknown): error is ValidationError; /** * Type guard to check if an error is a NotFoundError */ declare function isNotFoundError(error: unknown): error is NotFoundError; /** * Type guard to check if an error is a RateLimitError */ declare function isRateLimitError(error: unknown): error is RateLimitError; /** * Type guard to check if an error is a ServerError */ declare function isServerError(error: unknown): error is ServerError; /** * Type guard to check if an error is a NetworkError */ declare function isNetworkError(error: unknown): error is NetworkError; /** * Helper to get error details in a safe way */ declare function getErrorDetails(error: unknown): { message: string; statusCode?: number; }; /** * HTTP status code constants for error handling */ declare const HttpStatus: { readonly BAD_REQUEST: 400; readonly UNAUTHORIZED: 401; readonly FORBIDDEN: 403; readonly NOT_FOUND: 404; readonly TOO_MANY_REQUESTS: 429; readonly INTERNAL_SERVER_ERROR: 500; readonly NOT_IMPLEMENTED: 501; readonly BAD_GATEWAY: 502; readonly SERVICE_UNAVAILABLE: 503; readonly GATEWAY_TIMEOUT: 504; }; /** * Error type constants for consistent error identification */ declare const ErrorType: { readonly AUTHENTICATION: "AuthenticationError"; readonly AUTHORIZATION: "AuthorizationError"; readonly VALIDATION: "ValidationError"; readonly NOT_FOUND: "NotFoundError"; readonly RATE_LIMIT: "RateLimitError"; readonly SERVER: "ServerError"; readonly NETWORK: "NetworkError"; }; /** * Asset resolution utilities for UiPath Coded Apps * * These helpers enable developers to write code that works identically * in local development and production environments. * * Values are read from meta tags injected at deployment: * - * - */ /** * Resolves an asset path to the CDN URL (if available) * * In local development: returns path as-is (loads from local dev server) * In production: prepends CDN base URL from meta tag * * @param path - The asset path (e.g., './assets/logo.png' or '/assets/logo.png') * @returns The resolved asset URL * * @example * ```tsx * import { getAsset } from '@uipath/uipath-typescript'; * import logoPath from './assets/logo.png'; * * function MyComponent() { * return Logo; * } * ``` */ declare function getAsset(path: string): string; /** * Returns the app base path for router configuration * * In local development: returns '/' * In production: returns the deployed app path from meta tag * * @returns The app base path * * @example * ```tsx * import { getAppBase } from '@uipath/uipath-typescript'; * import { BrowserRouter } from 'react-router-dom'; * * function App() { * return ( * * {/* routes *\/} * * ); * } * ``` */ declare function getAppBase(): string; /** * UiPath meta tag names for runtime configuration. * * These meta tags are injected at deployment time by the Apps Service * to configure SDK authentication and asset resolution in production. */ declare enum UiPathMetaTags { CLIENT_ID = "uipath:client-id", SCOPE = "uipath:scope", ORG_NAME = "uipath:org-name", TENANT_NAME = "uipath:tenant-name", BASE_URL = "uipath:base-url", REDIRECT_URI = "uipath:redirect-uri", CDN_BASE = "uipath:cdn-base", APP_BASE = "uipath:app-base", FOLDER_KEY = "uipath:folder-key" } declare const track: _uipath_core_telemetry.Track; declare const trackEvent: (eventName: string, name?: string, attributes?: _uipath_core_telemetry.TelemetryAttributes) => void; declare const telemetryClient: { initialize(context?: TelemetryContext): void; /** * Sets the authenticated user's id so every subsequently emitted event * carries it as `CloudUserId`. */ setUserId(userId: string): void; }; export { AgentErrorSortColumn, AgentExecutionType, AgentGovernanceMode, AgentGovernanceSection, AgentGovernanceVerdict, AgentListSortColumn, AgentMap, AgentMemoryExecutionType, SpanExecutionType as AgentTraceExecutionType, AgentType, AssetValueScope, AssetValueType, AuthenticationError, AuthorizationError, BucketOptions, CaseInstanceMessageName, CitationErrorType, ConversationGetAllFilterMap, ConversationMap, DEFAULT_ITEMS_FIELD, DEFAULT_PAGE_SIZE, DEFAULT_TOTAL_COUNT_FIELD, DataDirectionType, DebugMode, index as DuFramework, EntityAggregateFunction, EntityFieldDataType, EntityType, ErrorType, EscalationActionType, EscalationRecipientScope, EscalationTriggerType, ExchangeMap, FeedbackRating, FeedbackStatus, FieldDisplayType, HttpStatus, InputStreamSpeechSensitivity, InstanceFinalStatus, InstanceStatus, InterruptType, JobPriority, JobSourceType, JobState, JobSubState, JobType, JoinType, LogicalOperator$1 as LogicalOperator, MAX_PAGE_SIZE, MessageMap, MessageRole, NetworkError, NotFoundError, PackageSourceType, PackageType, PolicyEvaluationResult, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, QueryFilterOperator, RateLimitError, ReferenceType, RemoteControlAccess, RobotSize, RuntimeType, SLADurationUnit, ServerError, ServerlessJobType, SlaSummaryStatus, SortOrder, SpanAttachmentDirection, SpanAttachmentProvider, SpanExecutionType, SpanPermissionStatus, SpanSource, SpanStatus, SpanVerbosityLevel, StageTaskType, StartStrategy, StopStrategy, TargetFramework, TaskActivityType, TaskAssignmentCriteria, TaskPriority, TaskSlaCriteria, TaskSlaStatus, TaskSourceName, TaskStatus, TaskType, TaskUserType, TimeInterval, UiPath, UiPathError, UiPathMetaTags, UserSettingsMap, ValidationError, createAgentWithMethods, createCaseInstanceWithMethods, createCaseWithMethods, createConversationWithMethods, createEntityWithMethods, createJobWithMethods, createProcessInstanceWithMethods, createProcessWithMethods, createTaskWithMethods, getAppBase, getAsset, getErrorDetails, getLimitedPageSize, isAuthenticationError, isAuthorizationError, isNetworkError, isNotFoundError, isRateLimitError, isServerError, isUiPathError, isValidationError, loadFromMetaTags, telemetryClient, track, trackEvent }; export type { AgentAppearance, AgentConsumption, AgentConversationServiceModel, AgentCreateConversationOptions, AgentError, AgentErrorOrderBy, AgentFilterOptions, AgentGetAllOptions, AgentGetByIdResponse, AgentGetConsumptionTimelineOptions, AgentGetConsumptionTimelineResponse, AgentGetErrorsOptions, AgentGetErrorsTimelineOptions, AgentGetErrorsTimelineResponse, AgentGetIncidentDistributionOptions, AgentGetIncidentDistributionResponse, AgentGetLatencyTimelineOptions, AgentGetLatencyTimelineResponse, AgentGetResponse, AgentGetSummaryOptions, AgentGetSummaryResponse, AgentGetTopConsumptionOptions, AgentGetTopConsumptionResponse, AgentGetTopErrorCountOptions, AgentGetTopErrorCountResponse, AgentGetUnitConsumptionSummaryOptions, AgentGetUnitConsumptionSummaryResponse, AgentGovernanceCountItem, AgentGovernanceDecisionGetResponse, AgentGovernanceDecisionsOptions, AgentGovernanceGetSummaryResponse, AgentGovernanceSummaryOptions, AgentInput, AgentJobConsumptionSummary, AgentJobInfo, AgentListItem, AgentListOrderBy, AgentMemoryFilterOptions, AgentMemoryGetCallsTimelineOptions, AgentMemoryGetCallsTimelineResponse, AgentMemoryGetTimelineOptions, AgentMemoryGetTimelineResponse, AgentMemoryGetTopSpacesOptions, AgentMemoryGetTopSpacesResponse, AgentMemoryServiceModel, AgentMethods, AgentServiceModel, AgentSpanGetResponse, AgentStartingPrompt, AgentSummaryEntry, AgentSummaryPeriod, AgentTopErrorCount, AgentTraceFilterOptions, AgentTraceGetErrorsTimelineOptions, AgentTraceGetErrorsTimelineResponse, AgentTraceGetLatencyTimelineOptions, AgentTraceGetLatencyTimelineResponse, AgentTraceGetSpansByReferenceOptions, AgentTraceGetUnitConsumptionOptions, AgentTraceGetUnitConsumptionResponse, AgentTracesServiceModel, AgentUnitConsumptionEntry, AgentUnitConsumptionPeriod, ArgumentMetadata, AssetGetAllOptions, AssetGetByIdOptions, AssetGetByNameOptions, AssetGetResponse, AssetNewValue, AssetServiceModel, AssetUpdateValueByIdOptions, AsyncInputStream, AsyncInputStreamChunkEvent, AsyncInputStreamEndEvent, AsyncInputStreamEvent, AsyncInputStreamStartEvent, AsyncToolCallStream, AttachmentGetByIdOptions, AttachmentResponse, AttachmentServiceModel, BaseConfig, BaseOptions, BaseProcessStartRequest, BlobItem, BodyOptions, BpmnXmlString, BucketDeleteFileOptions, BucketFile, BucketGetAllOptions, BucketGetByIdOptions, BucketGetByNameOptions, BucketGetFileMetaDataOptions, BucketGetFileMetaDataResponse, BucketGetFileMetaDataWithPaginationOptions, BucketGetFilesOptions, BucketGetReadUriOptions, BucketGetReadUriRequestOptions, BucketGetResponse, BucketGetUriOptions, BucketGetUriResponse, BucketServiceModel, BucketUploadFileOptions, BucketUploadFileRequestOptions, BucketUploadResponse, CaseAppConfig, CaseAppOverview, CaseGetAllOptions, CaseGetAllResponse, CaseGetAllWithMethodsResponse, CaseGetStageResponse, CaseGetTopDurationResponse, CaseGetTopFaultedCountResponse, CaseGetTopRunCountResponse, CaseInstanceExecutionHistoryResponse, CaseInstanceGetAllOptions, CaseInstanceGetAllWithPaginationOptions, CaseInstanceGetResponse, CaseInstanceMethods, CaseInstanceOperationOptions, CaseInstanceOperationResponse, CaseInstanceReopenOptions, CaseInstanceRun, CaseInstanceSendMessageOptions, CaseInstanceSlaSummaryOptions, CaseInstanceStageSLAOptions, CaseInstanceStageSLAResponse, CaseInstanceStageSLAStage, CaseInstancesServiceModel, CaseMethods, CasesServiceModel, ChoiceSetCreateOptions, ChoiceSetDeleteByIdOptions, ChoiceSetGetAllOptions, ChoiceSetGetAllResponse, ChoiceSetGetByIdOptions, ChoiceSetGetResponse, ChoiceSetServiceModel, ChoiceSetUpdateOptions, ChoiceSetValueDeleteOptions, ChoiceSetValueInsertOptions, ChoiceSetValueInsertResponse, ChoiceSetValueUpdateOptions, ChoiceSetValueUpdateResponse, Citation, CitationEndEvent, CitationError, CitationEvent, CitationOptions, CitationSource, CitationSourceBase, CitationSourceMedia, CitationSourceUrl, CitationStartEvent, ClientSideTool, CollectionResponse, CompletedContentPart, CompletedMessage, CompletedToolCall, ContentPart, ContentPartChunkEvent, ContentPartData, ContentPartEndEvent, ContentPartEvent, ContentPartGetResponse, ContentPartInterrupted, ContentPartStartEvent, ContentPartStartMetaData, ContentPartStream, ConversationAttachmentCreateResponse, ConversationAttachmentUploadResponse, ConversationCreateOptions, ConversationCreateResponse, ConversationDeleteResponse, ConversationEvent, ConversationExchangeServiceModel, ConversationGetAllOptions, ConversationGetResponse, ConversationJobStartOverrides, ConversationMethods, ConversationServiceModel, ConversationSessionMethods, ConversationSessionOptions, ConversationUpdateOptions, ConversationUpdateResponse, ConversationalAgentOptions, ConversationalAgentServiceModel, CreateFeedbackOptions, CustomKeyValuePair, DurationStats, ElementExecutionMetadata, ElementGetTopFailedCountResponse, ElementMetaData, ElementRunMetadata, ElementStats, EntityAggregate, EntityBatchInsertOptions, EntityBatchInsertResponse, EntityCreateFieldOptions, EntityCreateOptions, EntityDeleteAttachmentOptions, EntityDeleteAttachmentResponse, EntityDeleteByIdOptions, EntityDeleteOptions, EntityDeleteRecordByIdOptions, EntityDeleteRecordsOptions, EntityDeleteResponse, EntityDownloadAttachmentOptions, EntityFieldBase, EntityFieldUpdateOptions, EntityFileType, EntityFolderScopedOptions, EntityGetAllOptions, EntityGetAllRecordsOptions, EntityGetByIdOptions, EntityGetRecordByIdOptions, EntityGetRecordsByIdOptions, EntityGetResponse, EntityImportRecordsByIdOptions, EntityImportRecordsResponse, EntityInsertOptions, EntityInsertRecordOptions, EntityInsertRecordsOptions, EntityInsertResponse, EntityJoin, EntityMethods, EntityOperationOptions, EntityOperationResponse, EntityQueryFilter, EntityQueryFilterGroup, EntityQueryRecordsOptions, EntityQueryRecordsResponse, EntityQuerySortOption, EntityRecord, EntityRemoveFieldOptions, EntityServiceModel, EntityUpdateByIdOptions, EntityUpdateOptions, EntityUpdateRecordOptions, EntityUpdateRecordResponse, EntityUpdateRecordsOptions, EntityUpdateResponse, EntityUploadAttachmentOptions, EntityUploadAttachmentResponse, ErrorEndEvent, ErrorEvent, ErrorStartEvent, EscalationAction, EscalationRecipient, EscalationRule, EscalationTriggerMetadata, ExceptionReportSubmitResult, Exchange, ExchangeEndEvent, ExchangeEvent, ExchangeGetAllOptions, ExchangeGetByIdOptions, ExchangeGetResponse, ExchangeServiceModel, ExchangeStartEvent, ExchangeStream, ExecutingToolCallEvent, ExternalConnection, ExternalField, ExternalFieldMapping, ExternalObject, ExternalSourceFields, ExternalValue, FailureRecord, FeatureFlags, FeedbackCategory, FeedbackCategoryInput, FeedbackCategoryResponse, FeedbackCreateCategoryOptions, FeedbackCreateResponse, FeedbackDeleteCategoryOptions, FeedbackGetAllOptions, FeedbackGetCategoriesOptions, FeedbackGetResponse, FeedbackOptions, FeedbackResponse, FeedbackServiceModel, FeedbackSubmitOptions, FeedbackUpdateOptions, Field$1 as Field, FieldDataType, FieldMetaData, FileUploadAccess, FolderProperties, FolderScopedOptions, GenericInterruptStartEvent, GetTopBaseResponse, GetTopDurationResponse, GetTopFaultedCountResponse, GetTopRunCountResponse, GlobalVariableMetaData, GovernanceFilterOptions, GovernanceOperationSummary, GovernancePolicyTrace, GovernancePolicyTraceGetAllOptions, GovernanceServiceModel, HasPaginationOptions, Headers, HttpMethod, IncidentTimelineResponse, InlineOrExternalValue, InlineValue, InstanceStats, InstanceStatusTimelineResponse, Interrupt, InterruptEndEvent, InterruptEvent, InterruptStartEvent, JSONArray, JSONObject, JSONPrimitive, JSONValue, JobAttachment, JobError, JobGetAllOptions, JobGetByIdOptions, JobGetResponse, JobMethods, JobResumeOptions, JobServiceModel, JobStopOptions, LabelUpdatedEvent, Machine, MaestroProcessGetAllOptions, MaestroProcessGetAllResponse, MaestroProcessStatsRequest, MaestroProcessesServiceModel, MakeOptional, MakeRequired, Message, MessageEndEvent, MessageEvent, MessageGetResponse, MessageServiceModel, MessageStartEvent, MessageStream, MetaData, MetaEvent, NonPaginatedResponse, OAuthFields, OperationResponse, OrchestratorDuModuleServiceModel, PaginatedResponse, PaginationCursor, PaginationMetadata, PaginationMethodUnion, PaginationOptions, PartialUiPathConfig, ProcessExtractedDataOptions, ProcessExtractedDataRequest, ProcessGetAllOptions, ProcessGetByIdOptions, ProcessGetByNameOptions, ProcessGetResponse, ProcessGetTopDurationResponse, ProcessGetTopFaultedCountResponse, ProcessGetTopRunCountResponse, ProcessIncidentGetAllResponse, ProcessIncidentGetResponse, ProcessIncidentsServiceModel, ProcessInstanceExecutionHistoryResponse, ProcessInstanceGetAllOptions, ProcessInstanceGetAllWithPaginationOptions, ProcessInstanceGetResponse, ProcessInstanceGetVariablesOptions, ProcessInstanceGetVariablesResponse, ProcessInstanceMethods, ProcessInstanceOperationOptions, ProcessInstanceOperationResponse, ProcessInstanceRun, ProcessInstancesServiceModel, ProcessMetadata, ProcessMethods, ProcessProperties, ProcessServiceModel, ProcessStartOptions, ProcessStartRequest, ProcessStartRequestWithKey, ProcessStartRequestWithName, ProcessStartResponse, QueryParams, QueueGetAllOptions, QueueGetByIdOptions, QueueGetResponse, QueueServiceModel, RawAgentGetByIdResponse, RawAgentGetResponse, RawCaseInstanceGetResponse, RawConversationGetResponse, RawEntityGetResponse, RawJobGetResponse, RawMaestroProcessGetAllResponse, RawProcessInstanceGetResponse, RawTaskCreateResponse, RawTaskGetResponse, RequestOptions, RequestSpec, ResponseDictionary, ResponseType, RetryOptions, RobotMetadata, SessionCapabilities, SessionEndEvent, SessionEndingEvent, SessionStartEvent, SessionStartedEvent, SessionStream, Simplify, SlaSummaryResponse, SourceJoinCriteria, SpanAttachment, SpanContext, SpanGetResponse, SpanReferenceHierarchyEntry, SqlType, StageSLA, StageTask, SubmitExceptionReportOptions, SubmitExceptionReportResponse, Tag, TaskActivity, TaskAssignOptions, TaskAssignment, TaskAssignmentOptions, TaskAssignmentResponse, TaskBaseResponse, TaskCompleteOptions, TaskCompletionOptions, TaskCreateOptions, TaskCreateResponse, TaskGetAllOptions, TaskGetByIdOptions, TaskGetResponse, TaskGetUsersOptions, TaskMethods, TaskServiceModel, TaskSlaDetail, TaskSource, TasksUnassignOptions, TimelineOptions, TimeoutOptions, ToolCall, ToolCallConfirmationEndValue, ToolCallConfirmationEvent, ToolCallConfirmationInterruptStartEvent, ToolCallConfirmationValue, ToolCallEndEvent, ToolCallEvent, ToolCallInputValue, ToolCallOutputValue, ToolCallResult, ToolCallStartEvent, ToolCallStream, TopQueryOptions, TracesGetByIdOptions, TracesServiceModel, UiPathSDKConfig, UserLoginInfo, UserSettingsGetResponse, UserSettingsServiceModel, UserSettingsUpdateOptions, UserSettingsUpdateResponse };