import { IUiPath as IUiPath$1 } from '../core/index'; import { ConnectionStatus, ConnectionStatusChangedHandler, LogLevel } from '@/core/websocket'; export { LogLevel } from '@/core/websocket'; import { IUiPath } from '../core/index'; /** * 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; } /** * 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; } /** * 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; } /** * 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; } /** * Helper for managing async tool call events within a conversation. * Handles tool call lifecycle with start/end events at the conversation level. */ declare abstract class AsyncToolCallEventHelper extends ConversationEventHelperBase { readonly session: SessionEventHelper; readonly toolCallId: string; /** * ToolCallStartEvent used to initialize the ToolCallEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ readonly startEventMaybe: ToolCallStartEvent | undefined; protected readonly _endHandlers: ToolCallEndHandler[]; constructor(session: SessionEventHelper, toolCallId: string, /** * ToolCallStartEvent used to initialize the ToolCallEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ startEventMaybe: ToolCallStartEvent | undefined); /** * ToolCallStartEvent used to initialize the AsyncToolCallEventHelper. Throws an ConversationEventValidationError if * some other sub-event was received before the start event, which shouldn't happen under normal circumstances. */ get startEvent(): MakeRequired; /** * Emits an async tool call event through the parent conversation. */ emit(toolCallEvent: Omit): void; /** * Sends meta for this async tool call. * @throws Error if tool call has already ended. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Ends the async tool call with optional end event data. * @throws Error if tool call has already ended. */ sendToolCallEnd(endToolCall?: ToolCallEndEvent): void; /** * @deprecated Use sendToolCallEnd */ sendEndToolCall(endToolCall?: ToolCallEndEvent): void; /** * Registers a handler for tool call end events. * @returns Cleanup function to remove the handler. */ onToolCallEnd(cb: ToolCallEndHandler): () => void; /** * Sends an error start event for this tool call. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this tool call. */ sendErrorEnd(args: ErrorEndEventOptions): void; toString(): string; } declare class AsyncToolCallEventHelperImpl extends AsyncToolCallEventHelper { /** * Dispatches incoming tool call events to registered handlers. */ dispatch(toolCallEvent: ToolCallEvent): void; protected getParentErrorScope(): boolean; protected removeFromParent(): void; protected deleteChildren(): void; protected getSession(): SessionEventHelper; } type ContentPartStartEventWithData = Simplify<{ data?: string; } & MakeOptional>; /** * Helper for managing content part events within a message. * Handles streaming content parts with start/chunk/end lifecycle. */ declare abstract class ContentPartEventHelper extends ConversationEventHelperBase implements ContentPartStream { readonly message: MessageEventHelper; readonly contentPartId: string; /** * ContentPartStartEvent used to initialize the ContentPartEventHelper. Will be undefined if some other sub-event * was received before the start event. See also `startEvent`. */ readonly startEventMaybe: ContentPartStartEvent | undefined; protected readonly _chunkHandlers: ChunkHandler[]; protected readonly _endHandlers: ContentPartEndHandler[]; constructor(message: MessageEventHelper, contentPartId: string, /** * ContentPartStartEvent used to initialize the ContentPartEventHelper. Will be undefined if some other sub-event * was received before the start event. See also `startEvent`. */ startEventMaybe: ContentPartStartEvent | undefined); /** * ContentPartStartEvent used to initialize the ContentPartEventHelper. Throws an ConversationEventValidationError if * some other sub-event was received before the start event, which shouldn't happen under normal circumstances. */ get startEvent(): MakeRequired; /** * The MIME type of this content part. * Returns undefined if the start event hasn't been received yet. */ get mimeType(): string | undefined; /** * Whether this content part is plain text. Matches `text/plain`. */ get isText(): boolean; /** * Whether this content part is markdown. Matches `text/markdown`. */ get isMarkdown(): boolean; /** * Whether this content part is HTML. Matches `text/html`. */ get isHtml(): boolean; /** * Whether this content part is audio content. */ get isAudio(): boolean; /** * Whether this content part is an image. */ get isImage(): boolean; /** * Whether this content part is a transcript (from speech-to-text). * @example * ```typescript * message.onContentPartStart((contentPart) => { * if (contentPart.isTranscript) { * console.log('User voice transcription:'); * contentPart.onChunk((chunk) => { * process.stdout.write(chunk.data ?? ''); * }); * } * }); * ``` */ get isTranscript(): boolean; /** * Emits a content part event through the parent message. */ emit(contentPartEvent: Omit): void; /** * Sends a content part chunk with optional sequence number and citation. * @throws Error if content part stream has already ended. */ sendChunk(chunk: ContentPartChunkEvent): void; /** * Sends meta event for this content part stream. * @throws Error if content part stream has already ended. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Sends a chunk with citation start event. * @throws Error if content part stream has already ended. */ sendChunkWithCitationStart(chunk: Omit & { citationId: string; }): void; /** * Sends a chunk with citation end event. * @throws Error if content part stream has already ended. */ sendChunkWithCitationEnd(chunk: Omit & { citationId: string; sources: CitationSource[]; }): void; /** * Sends a chunk with citation start and end event. * @throws Error if content part stream has already ended. */ sendChunkWithCitation(chunk: Omit & { citationId: string; sources: CitationSource[]; }): void; /** * Ends the content part stream with optional end event data. * @throws Error if content part stream has already ended. */ sendContentPartEnd(endContentPart?: ContentPartEndEvent): void; sendEndContentPart(endContentPart?: ContentPartEndEvent): void; /** * Registers a handler for content part chunks. * @returns Cleanup function to remove the handler. */ onChunk(cb: ChunkHandler): () => void; /** * Registers a handler for content part end events. * @returns Cleanup function to remove the handler. */ onContentPartEnd(cb: ContentPartEndHandler): () => void; onEndContentPart(cb: ContentPartEndHandler): void; /** * Sends an error start event for this content part. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this content part. */ sendErrorEnd(args: ErrorEndEventOptions): void; onCompleted(cb: (completedContentPart: CompletedContentPart) => void): void; toString(): string; } declare class ContentPartEventHelperImpl extends ContentPartEventHelper { static replay(contentPart: ContentPart): Generator; /** * Dispatches incoming content part events to registered handlers. */ dispatch(contentPartEvent: ContentPartEvent): void; protected getParentErrorScope(): boolean; protected removeFromParent(): void; protected deleteChildren(): void; protected getSession(): SessionEventHelper; private static replayChunks; } /** * Helper for managing tool call events within a message. * Handles tool call lifecycle with start/end events. */ declare abstract class ToolCallEventHelper extends ConversationEventHelperBase implements ToolCallStream { readonly message: MessageEventHelper; readonly toolCallId: string; /** * ToolCallStartEvent used to initialize the ToolCallEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ readonly startEventMaybe: ToolCallStartEvent | undefined; protected readonly _endHandlers: ToolCallEndHandler[]; protected readonly _confirmHandlers: ToolCallConfirmationHandler[]; protected readonly _executingHandlers: ExecutingToolCallHandler[]; constructor(message: MessageEventHelper, toolCallId: string, /** * ToolCallStartEvent used to initialize the ToolCallEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ startEventMaybe: ToolCallStartEvent | undefined); /** * MessageStartEvent used to initialize the MessageEventHelper. Throws an ConversationEventValidationError if some * other sub-event was received before the start event, which shouldn't happen under normal circumstances. */ get startEvent(): MakeRequired; /** * Emits a tool call event through the parent message. */ emit(toolCallEvent: Omit): void; /** * Sends meta for this tool call. * @throws Error if tool call has already ended. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Ends the tool call with optional end event data. * @throws Error if tool call has already ended. */ sendToolCallEnd(endToolCall?: ToolCallEndEvent): void; /** * @deprecated Use sendToolCallEnd */ sendEndToolCall(endToolCall?: ToolCallEndEvent): void; /** * Registers a handler for tool call end events. * @returns Cleanup function to remove the handler. */ onToolCallEnd(cb: ToolCallEndHandler): () => void; /** * @deprecated Use onToolCallEnd */ onEndToolCall(cb: ToolCallEndHandler): void; /** * Registers a handler for tool call confirmation events. Fired when the * peer responds to a tool call that was emitted with `requireConfirmation`. * @returns Cleanup function to remove the handler. */ onToolCallConfirm(callback: ToolCallConfirmationHandler): () => void; /** * Sends a tool call confirmation (approve/reject) for a tool call that was * emitted with `requireConfirmation: true`. Replaces the legacy * `sendInterruptEnd` flow for tool call confirmation. * @throws Error if tool call has already ended. */ sendToolCallConfirm(confirmToolCall: ToolCallConfirmationEvent): 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. * @returns Cleanup function to remove the handler. * @internal */ onExecutingToolCall(cb: ExecutingToolCallHandler): () => void; /** * Sends an error start event for this tool call. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this tool call. */ sendErrorEnd(args: ErrorEndEventOptions): void; toString(): string; } declare class ToolCallEventHelperImpl extends ToolCallEventHelper { static replay(toolCall: ToolCall): Generator; /** * Dispatches incoming tool call events to registered handlers. */ dispatch(toolCallEvent: ToolCallEvent): void; protected getParentErrorScope(): boolean; protected removeFromParent(): void; protected deleteChildren(): void; protected getSession(): SessionEventHelper; } /** * Helper for managing message events within an exchange. * Handles message lifecycle including content, tool calls, and citations. */ declare abstract class MessageEventHelper extends ConversationEventHelperBase implements MessageStream { readonly exchange: ExchangeEventHelper; readonly messageId: string; /** * MessageStartEvent used to initialize the MessageEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ readonly startEventMaybe: MessageStartEvent | undefined; protected readonly _contentPartMap: Map; protected readonly _contentPartStartHandlers: ContentPartStartHandler[]; protected readonly _endHandlers: MessageEndHandler[]; protected readonly _toolCallStartHandlers: ToolCallStartHandler[]; protected readonly _toolCallMap: Map; protected readonly _interruptStartHandlers: InterruptStartHandler[]; protected readonly _interruptEndHandlers: InterruptEndHandler[]; protected readonly _toolCallConfirmHandlers: ToolCallConfirmHandler[]; constructor(exchange: ExchangeEventHelper, messageId: string, /** * MessageStartEvent used to initialize the MessageEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ startEventMaybe: MessageStartEvent | undefined); /** * MessageStartEvent used to initialize the MessageEventHelper. Throws an ConversationEventValidationError if some * other sub-event was received before the start event, which shouldn't happen under normal circumstances. */ get startEvent(): MakeRequired; /** * The role of this message (user, assistant, or system). * Returns undefined if the start event hasn't been received yet. */ get role(): MessageRole | undefined; /** * Whether this message is from the user. * @example * ```typescript * message.onContentPartStart((contentPart) => { * if (message.isUser) { * console.log('User message content:', contentPart.mimeType); * } * }); * ``` */ get isUser(): boolean; /** * Whether this message is from the assistant. * @example * ```typescript * exchange.onMessageStart((message) => { * if (message.isAssistant) { * message.onContentPartStart((contentPart) => { * contentPart.onChunk((chunk) => { * process.stdout.write(chunk.data ?? ''); * }); * }); * } * }); * ``` */ get isAssistant(): boolean; /** * Whether this message is a system message. */ get isSystem(): boolean; /** * Emits a message event through the parent exchange. */ emit(messageEvent: Omit): void; /** * Starts a new content part stream with automatic cleanup when callback is provided. * @returns ContentPartEventHelper for manual control or Promise when using callback. * @throws Error if message has already ended. */ startContentPart(args: ContentPartStartEventOptions): ContentPartEventHelper; startContentPart(args: ContentPartStartEventOptions, cb: ContentPartStartHandlerAsync): Promise; /** * Iterator over all the content parts in this message. */ get contentParts(): IteratorObject; /** * Retrieves the content part with a specified id from this message. * @param contentPartId The id of the content part to get. * @returns The ContentPartEventHelper for the specified id, or undefined if no such content part exists. */ getContentPart(contentPartId: string): ContentPartEventHelper | undefined; /** * Sends a complete content part with data and optional mime type. Defaults to mimeType "text/markdown". */ sendContentPart(args: ContentPartStartEventWithData): Promise; startToolCall(args: ToolCallStartEventWithId): ToolCallEventHelper; startToolCall(args: ToolCallStartEventWithId, cb: ToolCallStartHandlerAsync): Promise; /** * Iterator over all the tool calls in this message. */ get toolCalls(): IteratorObject; /** * Retrieves the tool call with a specified id from this message. * @param toolCallId The id of the tool call to get. * @returns The ToolCallEventHelper for the specified id, or undefined if no such tool call exists. */ getToolCall(toolCallId: string): ToolCallEventHelper | undefined; /** * Sends meta for this message. * @throws Error if message has already ended. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Ends the message with optional end event data. * @throws Error if message has already ended. */ sendMessageEnd(endMessage?: MessageEndEvent): void; /** * @deprecated Use sendMessageEnd */ sendEndMessage(endMessage?: MessageEndEvent): void; /** * Registers a handler for message end events. * @returns Cleanup function to remove the handler. */ onMessageEnd(cb: MessageEndHandler): () => void; /** * @deprecated Use onMessageEnd */ onEndMessage(cb: MessageEndHandler): void; /** * Registers a handler for content part start events. * @returns Cleanup function to remove the handler. */ onContentPartStart(cb: ContentPartStartHandler): () => void; /** * Registers a handler that receives complete content parts after a content part stream ends. */ onContentPartCompleted(cb: ContentPartCompletedHandler): void; /** * Registers a handler for tool call start events. * @returns Cleanup function to remove the handler. */ onToolCallStart(cb: ToolCallStartHandler): () => void; onToolCallCompleted(cb: ToolCallCompletedHandler): void; /** * Registers a handler for interrupt start events. * @returns Cleanup function to remove the handler. */ onInterruptStart(cb: InterruptStartHandler): () => void; /** * Registers a handler for interrupt end events. * @returns Cleanup function to remove the handler. */ onInterruptEnd(cb: InterruptEndHandler): () => void; /** * Registers a handler for tool-call confirmation events. Fired when a peer * responds to a tool call that was emitted with `requireConfirmation: true`. * * Fires at the message level before the event is delegated to the per-tool-call * helper, so this handler runs even when no `ToolCallEventHelper` exists for the * confirmed tool call (e.g. on the agent side after the originating helper has * been cleaned up, or on the client side if no `onToolCallStart` is registered). * * @returns Cleanup function to remove the handler. */ onToolCallConfirm(callback: ToolCallConfirmHandler): () => void; /** * Sends an interrupt start event. */ sendInterrupt(interruptId: string, startInterrupt: InterruptStartEvent): void; /** * Sends an interrupt end event. */ sendInterruptEnd(interruptId: string, endInterrupt: InterruptEndEvent): void; /** * Sends an error start event for this message. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this message. */ sendErrorEnd(args: ErrorEndEventOptions): void; onCompleted(cb: MessageCompletedHandler): void; toString(): string; } declare class MessageEventHelperImpl extends MessageEventHelper { static replay(message: Message): Generator; /** * Dispatches incoming message events to registered handlers. */ dispatch(messageEvent: MessageEvent): void; /** * Internal method used by child ContentPartEventHelper to remove itself. */ removeContentPart(helper: ContentPartEventHelperImpl): void; /** * Internal method used by child ToolCallEventHelper to remove itself. */ removeToolCall(helper: ToolCallEventHelperImpl): void; protected removeFromParent(): void; protected deleteChildren(): void; protected getParentErrorScope(): boolean; protected getSession(): SessionEventHelper; } /** * Helper for managing exchange events within a conversation. * Handles exchange lifecycle including messages. */ declare abstract class ExchangeEventHelper extends ConversationEventHelperBase implements ExchangeStream { readonly session: SessionEventHelper; readonly exchangeId: string; /** * ExchangeStartEvent used to initialize the ExchangeEventHelper. Will be undefined if some other sub-event * was received before the start event. See also `startEvent`. */ readonly startEventMaybe: ExchangeStartEvent | undefined; protected readonly _messageMap: Map; protected readonly _messageStartHandlers: MessageStartHandler[]; protected readonly _endHandlers: ExchangeEndHandler[]; constructor(session: SessionEventHelper, exchangeId: string, /** * ExchangeStartEvent used to initialize the ExchangeEventHelper. Will be undefined if some other sub-event * was received before the start event. See also `startEvent`. */ startEventMaybe: ExchangeStartEvent | undefined); /** * ExchangeStartEvent used to initialize the ExchangeEventHelper. Throws an ConversationEventValidationError if some * other sub-event was received before the start event, which shouldn't happen under normal circumstances. */ get startEvent(): MakeRequired; /** * Emits an exchange event through the parent session. */ emit(exchangeEvent: Omit): void; /** * Starts a new message with automatic cleanup when callback is provided. * @returns MessageEventHelper for manual control or Promise when using callback. * @throws Error if exchange has already ended. */ startMessage(args?: MessageStartEventOptions): MessageEventHelper; startMessage(args: MessageStartEventOptions, cb: MessageStartHandlerAsync): Promise; startMessage(cb: MessageStartHandlerAsync): Promise; /** * Sends a complete message with content part data and optional mime type. */ sendMessageWithContentPart(options: SendMessageWithContentPartOptions): Promise; /** * Iterator over all the messages in this exchange. */ get messages(): IteratorObject; /** * Retrieves the message with a specified id from this exchange. * @param exchangeId The id of the message to get. * @returns The MessageEventHelper for the specified id, or undefined if no such content part exists. */ getMessage(messageId: string): MessageEventHelper | undefined; /** * Sends meta for this exchange. * @throws Error if exchange has already ended. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Ends the exchange. Stops further events for that exchange from being received. * Can be called from either the client side (to stop an in-progress response) or * the server/agent side (to signal natural completion). * @throws Error if exchange has already ended. */ sendExchangeEnd(endExchange?: ExchangeEndEvent): void; /** * @deprecated Use sendExchangeEnd */ sendEndExchange(endExchange?: ExchangeEndEvent): void; /** * Registers a handler for exchange end events. * @returns Cleanup function to remove the handler. */ onExchangeEnd(cb: ExchangeEndHandler): () => void; /** * Registers a handler for message start events. * @returns Cleanup function to remove the handler. */ onMessageStart(cb: MessageStartHandler): () => void; /** * Registers a handler that receives a complete message after all the content part streams end. */ onMessageCompleted(cb: MessageCompletedHandler): void; /** * Sends an error start event for this exchange. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this exchange. */ sendErrorEnd(args: ErrorEndEventOptions): void; toString(): string; } declare class ExchangeEventHelperImpl extends ExchangeEventHelper { static replay(exchange: Exchange): Generator; /** * Dispatches incoming exchange events to registered handlers. */ dispatch(exchangeEvent: ExchangeEvent): void; /** * Internal method used by child MessageEventHelper to remove itself. */ removeMessage(helper: MessageEventHelperImpl): void; protected getParentErrorScope(): boolean; protected removeFromParent(): void; protected deleteChildren(): void; protected getSession(): SessionEventHelper; } /** * Helper for managing conversation session events. Handles conversation lifecycle including exchanges, input streams, * and async operations. */ declare abstract class SessionEventHelper extends ConversationEventHelperBase implements SessionStream { readonly conversationId: string; /** * SessionStartEvent used to initialize the SessionEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ readonly startEventMaybe: SessionStartEvent | undefined; readonly echo: boolean; protected readonly _exchangeMap: Map; protected readonly _inputStreamMap: Map; protected readonly _exchangeStartHandlers: ExchangeStartHandler[]; protected readonly _inputStreamStartHandlers: InputStreamStartHandler[]; protected readonly _asyncToolCallStartHandlers: AsyncToolCallStartHandler[]; protected readonly _asyncToolCallMap: Map; protected readonly _labelUpdatedHandlers: LabelUpdatedHandler[]; protected readonly _sessionStartedHandlers: SessionStartedHandler[]; protected readonly _sessionEndingHandlers: SessionEndingHandler[]; protected readonly _sessionEndHandlers: SessionEndHandler[]; protected _emitBuffer: Array> | null; protected readonly _anyErrorStartHandlers: AnyErrorStartHandler[]; protected readonly _anyErrorEndHandlers: AnyErrorEndHandler[]; constructor(manager: ConversationEventHelperManager, conversationId: string, /** * SessionStartEvent used to initialize the SessionEventHelper. Will be undefined if some other sub-event was * received before the start event. See also `startEvent`. */ startEventMaybe: SessionStartEvent | undefined, echo?: boolean); /** * SessionStartEvent used to initialize the SessionEventHelper. Throws an ConversationEventValidationError if some * other sub-event was received before the start event, which shouldn't happen under normal circumstances. */ get startEvent(): SessionStartEvent; /** * Emits a conversation event. */ emit(conversationEvent: Omit): void; get isEmitPaused(): boolean; pauseEmits(): void; resumeEmits(): void; /** * Sends a session started event. */ sendSessionStarted(sessionStarted?: SessionStartedEvent): void; /** * Sends a session end event. */ sendSessionEnd(endSession?: SessionEndEvent): void; /** * @deprecated Use sendSessionEnd */ sendEndSession(endSession?: SessionEndEvent): void; /** * Starts a new exchange with automatic cleanup when callback is provided. * @returns ExchangeEventHelper for manual control or Promise when using callback. */ startExchange(args?: ExchangeStartEventOptions): ExchangeEventHelper; startExchange(cb: ExchangeStartHandlerAsync): Promise; startExchange(args: ExchangeStartEventOptions, cb: ExchangeStartHandlerAsync): Promise; /** * Iterator over all the exchanges in this session. */ get exchanges(): IteratorObject; /** * Retrieves the exchange with a specified id from this session. * @param exchangeId The id of the exchange to get. * @returns The ExchangeEventHelper for the specified id, or undefined if no such exchange exists. */ getExchange(exchangeId: string): ExchangeEventHelper | undefined; /** * Starts a new async input stream with automatic cleanup when callback is provided. * @returns InputStreamEventHelper for manual control or Promise when using callback. */ startAsyncInputStream(args: InputStreamStartEventOptions): AsyncInputStreamEventHelper; startAsyncInputStream(args: InputStreamStartEventOptions, cb: (x: AsyncInputStreamEventHelperImpl) => Promise): Promise; /** * Iterator over all the async input streams in this session. */ get asyncInputStreams(): Iterable; /** * Retrieves the async input stream with a specified id from this session. * @param exchangeId The id of the async input stream to get. * @returns The AsyncInputStreamEventHelper for the specified id, or undefined if no such async input stream exists. */ getAsyncInputStream(streamId: string): AsyncInputStreamEventHelper | undefined; /** * Starts a new async tool call with automatic cleanup when callback is provided. * @returns AsyncToolCallEventHelper for manual control or Promise when using callback. */ startAsyncToolCall(args: ToolCallStartEventWithId): AsyncToolCallEventHelper; startAsyncToolCall(args: ToolCallStartEventWithId, cb: AsyncToolCallStartHandlerAsync): Promise; /** * Iterator over all the async tool call in this session. */ get asyncToolCalls(): Iterable; /** * Retrieves the async tool call with a specified id from this session. * @param toolCallId The id of the async tool call to get. * @returns The AsyncToolCallEventHelper for the specified id, or undefined if no such async tool call exists. */ getAsyncToolCall(toolCallId: string): AsyncToolCallEventHelper | undefined; /** * Sends meta for this conversation. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Registers a handler for session started events. * @returns Cleanup function to remove the handler. */ onSessionStarted(cb: SessionStartedHandler): () => void; /** * Registers a handler for session ending events. * @returns Cleanup function to remove the handler. */ onSessionEnding(cb: SessionEndingHandler): () => void; /** * Registers a handler for session end events. * @returns Cleanup function to remove the handler. */ onSessionEnd(cb: SessionEndHandler): () => void; /** * Registers a handler for exchange start events. * @returns Cleanup function to remove the handler. */ onExchangeStart(cb: ExchangeStartHandler): () => void; /** * Registers a handler for input stream start events. * @returns Cleanup function to remove the handler. */ onInputStreamStart(cb: InputStreamStartHandler): () => void; /** * Registers a handler for async tool call start events. * @returns Cleanup function to remove the handler. */ onAsyncToolCallStart(cb: AsyncToolCallStartHandler): () => void; /** * Registers a handler that will be called when a label updated event is received for this session. * @returns Cleanup function to remove the handler. */ onLabelUpdated(cb: LabelUpdatedHandler): () => void; /** * Sends an error start event for this conversation. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this conversation. */ sendErrorEnd(args: ErrorEndEventOptions): void; toString(): string; replay(exchanges: Exchange[]): void; /** * Registers a handler that will be called when an error start event is received by any nested * conversation event helper object. * * @returns Cleanup function to remove the handler. */ onAnyErrorStart(cb: AnyErrorStartHandler): () => void; /** * Registers a handler that will be called when an error end event is received by any nested * conversation event helper object. * * @returns Cleanup function to remove the handler. */ onAnyErrorEnd(cb: AnyErrorEndHandler): () => void; private emitInternal; } declare class SessionEventHelperImpl extends SessionEventHelper { /** * Dispatches incoming conversation events to registered handlers. */ dispatch(conversationEvent: ConversationEvent): void; /** * Internal method used by child ExchangeEventHelper to remove itself. */ removeExchange(helper: ExchangeEventHelperImpl): void; /** * Internal method used by child AsyncInputStreamEventHelper to remove itself. */ removeInputStream(helper: AsyncInputStreamEventHelperImpl): void; /** * Internal method used by child AsyncToolCallEventHelper to remove itself. */ removeAsyncToolCall(helper: AsyncToolCallEventHelperImpl): void; /** * Internal method. */ dispatchAnyErrorStart(args: AnyErrorStartHandlerArgs): boolean; /** * Internal method. */ dispatchAnyErrorEnd(args: AnyErrorEndHandlerArgs): boolean; /** * For SessionEventHelper, there is no parent error scope to chain to. */ protected getParentErrorScope(): boolean; protected removeFromParent(): void; protected deleteChildren(): void; protected getSession(): this; } /** * Provides functions for sending and receiving conversation events. */ declare abstract class ConversationEventHelperManager { private readonly config; protected readonly _sessionStartHandlers: SessionStartHandler[]; protected readonly _sessionMap: Map; protected readonly _anyEventHandlers: ConversationEventHandler[]; protected readonly _anyErrorStartHandlers: AnyErrorStartHandler[]; protected readonly _anyErrorEndHandlers: AnyErrorEndHandler[]; protected readonly _unhandledErrorStartHandlers: UnhandledErrorStartHandler[]; protected readonly _unhandledErrorEndHandlers: UnhandledErrorEndHandler[]; constructor(config: ConversationEventHelperManagerConfig); makeId(): string; /** * Sends a conversation event to the service. Typically client applications use the various helper methods, like * startSession or sendErrorStart on this object or on the nested helper objects it creates, rather than using this * API. * * @param conversationEvent The event to send. */ emitAny(conversationEvent: ConversationEvent): void; /** * Registers a handler that will be called whenever any conversation event is received. Typically client applications * use the various helper methods, like onSessionStarted on an Session object returned by startSession, rather than * using this API. * * @returns Cleanup function to remove the handler. */ onAny(cb: ConversationEventHandler): () => void; /** * Registers a handler for session start events. * @returns Cleanup function to remove the handler. */ onSessionStart(cb: SessionStartHandler): () => void; /** * Send an {@link SessionStartEvent} to indicate the start of an event stream for a conversation and return a * {@link SessionEventHelper} for that conversation. * * @param args a {@link SessionStartEvent} with a required conversationId property. * # */ startSession(args: SessionStartEventOptions): SessionEventHelper; /** * Send an {@link SessionStartEvent} to indicate the start of an event stream for a conversation and call an * async function with a {@link SessionEventHelper} for that conversation. A {@link SessionEndEvent} will * be sent when the function completes. * * @param args a {@link SessionStartEvent} with a required conversationId property. * @param cb a function called with a {@link SessionEventHelper} for the started conversation. */ startSession(args: SessionStartEventOptions, cb: SessionStartHandlerAsync): Promise; /** * An iterator over current sessions. */ get sessions(): Iterable; /** * Retrieves the session for a specified conversation id. * * @param conversationId The conversation id of the session to retrieve. * @returns The existing SessionEventHelper object for the specified conversation id, or undefined if no such session exists. */ getSession(conversationId: string): SessionEventHelperImpl | undefined; /** * Sends an error start event for a specified conversation. As a special case, this function allows any value for * conversationId, not just string. This is so that errors for invalid conversation ids can be emitted. */ sendErrorStart(args: ErrorStartEventOptions & { conversationId: any; }): void; /** * Sends an error end event for this conversation. As a special case, this function allows any value for * conversationId, not just string. This is so that errors for invalid conversation ids can be emitted. */ sendErrorEnd(args: ErrorEndEventOptions & { conversationId: any; }): void; toString(): string; /** * Registers a handler that will be called when an error start event is received by any nested * conversation event helper object. * * @returns Cleanup function to remove the handler. */ onAnyErrorStart(cb: AnyErrorStartHandler): () => void; /** * Registers a handler that will be called when an error end event is received by any nested * conversation event helper object. * * @returns Cleanup function to remove the handler. */ onAnyErrorEnd(cb: AnyErrorEndHandler): () => void; /** * Registers a handler that will be called when an error start event is received by any nested conversation event * helper object and that helper has no error start event handler, and there is no onAnyErrorStart event handler. If * there is no unhandled error start event handler, an exception will be thrown as an unhandled promise rejection. * * @returns Cleanup function to remove the handler. */ onUnhandledErrorStart(cb: UnhandledErrorStartHandler): () => void; /** * Registers a handler that will be called when an error start event is received by any nested conversation event * helper object and that helper has no error start event handler, and there is no onAnyErrorStart event handler. * * @returns Cleanup function to remove the handler. */ onUnhandledErrorEnd(cb: ErrorEndHandler): () => void; } declare class ConversationEventHelperManagerImpl extends ConversationEventHelperManager { /** * Internal method. */ dispatch(conversationEvent: ConversationEvent): void; /** * Internal method. */ removeSession(helper: SessionEventHelperImpl): void; /** * Internal method. */ dispatchAnyErrorStart(args: AnyErrorStartHandlerArgs): boolean; /** * Internal method. */ dispatchAnyErrorEnd(args: AnyErrorEndHandlerArgs): boolean; /** * Internal method. */ dispatchUnhandledErrorStart(args: UnhandledErrorStartHandlerArgs): void; /** * Internal method. */ dispatchUnhandledErrorEnd(args: UnhandledErrorEndHandlerArgs): void; } /** * Base class for all conversation event helpers, providing common functionality for: * - Event buffering (pause/resume) * - Property storage * - Error state management * - Lifecycle state (ended/deleted) * - Handler registration for errors, meta events, and deletion * * @template TStartEvent - The start event type for this helper * @template TEvent - The event type for this helper (used for event buffering) */ declare abstract class ConversationEventHelperBase { /** * Can be used to store application defined properties related to this helper. */ readonly properties: Record; /** * The active errors for this helper. Entries are added when a start error event is sent or received, and removed * when the end error event is sent or received. */ readonly errors: Map; /** * Reference to the conversation event helper manager. */ readonly manager: ConversationEventHelperManager; protected _ended: boolean; protected _deleted: boolean; protected _eventBuffer: Array | null; protected readonly _errorStartHandlers: ErrorStartHandler[]; protected readonly _errorEndHandlers: ErrorEndHandler[]; protected readonly _metaEventHandlers: MetaEventHandler[]; protected readonly _deletedHandlers: DeletedHandler[]; constructor(manager: ConversationEventHelperManager); /** * The start event used to initialize this helper. May be undefined if some other sub-event * was received before the start event. */ abstract get startEventMaybe(): TStartEvent | undefined; /** * Returns a string representation of this helper for debugging. */ abstract toString(): string; /** * Returns true if the parent scope has an error. Used for error scope chaining. */ protected abstract getParentErrorScope(): boolean; /** * Removes this helper from its parent's collection. Called during deletion. */ protected abstract removeFromParent(): void; /** * Deletes any child helpers managed by this helper. Called during deletion. */ protected abstract deleteChildren(): void; /** * Buffer received events, until `resume` is called. */ pause(): void; /** * Resume the processing of received events. All registered event handlers will be called before `resume` returns. * Subclasses must implement dispatch to handle buffered events. */ resume(): void; /** * Determine if event processing is currently paused. */ get isPaused(): boolean; /** * Determines if there is an error condition associated with this helper. */ get hasError(): boolean; /** * Determines if there is an error condition associated with this helper or any parent scope. */ get inErrorScope(): boolean; /** * Determines if this helper has ended. */ get ended(): boolean; /** * Determines if this helper has been deleted. */ get deleted(): boolean; /** * Gets application-defined properties with the specified type. */ getProperties(): T; /** * Sets application-defined properties. */ setProperties(properties: T): void; /** * Registers a handler for error start events. * @returns Cleanup function to remove the handler. */ onErrorStart(cb: ErrorStartHandler): () => void; /** * Registers a handler for error end events. * @returns Cleanup function to remove the handler. */ onErrorEnd(cb: ErrorEndHandler): () => void; /** * Registers a handler for meta events. * @returns Cleanup function to remove the handler. */ onMetaEvent(cb: MetaEventHandler): () => void; /** * Registers a handler that is called when this helper is deleted. * @returns Cleanup function to remove the handler. */ onDeleted(cb: DeletedHandler): () => void; /** * Deletes this helper, removing it from its parent and cleaning up all child helpers. */ delete(): void; /** * Dispatches events to registered handlers. This is an internal method used by the event system. * Subclasses implement this in their Impl class. * @internal */ protected abstract dispatch(event: TEvent): void; /** * Helper method for dispatching error start events. Used by subclass dispatch implementations. */ protected dispatchErrorStart(errorId: string, startError: ErrorStartEvent): void; /** * Helper method for dispatching error end events. Used by subclass dispatch implementations. */ protected dispatchErrorEnd(errorId: string, endError: ErrorEndEvent): void; /** * Marks this helper as ended. Used by subclass send end event methods. */ protected setEnded(): void; /** * Asserts that this helper has not ended. Throws if it has. * @throws ConversationEventInvalidOperationError if helper has ended */ protected assertNotEnded(): void; /** * Sets the timestamp property in the start event object if the object is defined by the property isn't. */ protected addStartEventTimestamp(startEventMaybe?: T): void; protected abstract getSession(): SessionEventHelper; } /** * Helper for managing async input stream events within a conversation. * Handles streaming input with start/chunk/end lifecycle. */ declare abstract class AsyncInputStreamEventHelper extends ConversationEventHelperBase { readonly session: SessionEventHelper; readonly streamId: string; /** * AsyncInputStreamStartEvent used to initialize the AsyncInputStreamEventHelper. Will be undefined if some other * sub-event was received before the start event. Which shouldn't happen under normal circumstances. */ readonly startEventMaybe: AsyncInputStreamStartEvent | undefined; protected readonly _chunkHandlers: AsyncInputStreamChunkHandler[]; protected readonly _endHandlers: AsyncInputStreamEndHandler[]; constructor(session: SessionEventHelper, streamId: string, /** * AsyncInputStreamStartEvent used to initialize the AsyncInputStreamEventHelper. Will be undefined if some other * sub-event was received before the start event. Which shouldn't happen under normal circumstances. */ startEventMaybe: AsyncInputStreamStartEvent | undefined); /** * AsyncInputStreamStartEvent used to initialize the AsyncInputStreamEventHelper. Throws an * ConversationEventValidationError if some other sub-event was received before the start event, which shouldn't * happen under normal circumstances. */ get startEvent(): AsyncInputStreamStartEvent; /** * Emits an input stream event through the parent conversation. */ emit(streamEvent: Omit): void; /** * Sends a stream chunk with optional sequence number. * @throws Error if input stream has already ended. */ sendChunk(chunk: AsyncInputStreamChunkEvent): void; /** * Sends meta for this input stream. * @throws Error if input stream has already ended. */ sendMetaEvent(metaEvent: MetaEvent): void; /** * Ends the input stream with optional end event data. * @throws Error if input stream has already ended. */ sendAsyncInputStreamEnd(endAsyncInputStream?: AsyncInputStreamEndEvent): void; /** * @deprecated Use sendAsyncInputStreamEnd */ sendEndAsyncInputStream(endAsyncInputStream?: AsyncInputStreamEndEvent): void; /** * Registers a handler for stream chunks. * @returns Cleanup function to remove the handler. */ onChunk(cb: AsyncInputStreamChunkHandler): () => void; /** * Registers a handler for stream end events. * @returns Cleanup function to remove the handler. */ onAsyncInputStreamEnd(cb: AsyncInputStreamEndHandler): () => void; /** * Sends an error start event for this async input stream. */ sendErrorStart(args: ErrorStartEventOptions): void; /** * Sends an error end event for this async input stream. */ sendErrorEnd(args: ErrorEndEventOptions): void; toString(): string; } declare class AsyncInputStreamEventHelperImpl extends AsyncInputStreamEventHelper { /** * Dispatches incoming stream events to registered handlers. */ dispatch(streamEvent: AsyncInputStreamEvent): void; protected getParentErrorScope(): boolean; protected removeFromParent(): void; protected deleteChildren(): void; protected getSession(): SessionEventHelper; } type ConversationEventEmitter = (e: ConversationEvent) => void; type ConversationEventHandler = (e: ConversationEvent) => void; type AsyncInputStreamChunkHandler = (chunk: AsyncInputStreamChunkEvent) => void; type AsyncInputStreamEndHandler = (endAsyncInputStreamEnd: AsyncInputStreamEndEvent) => void; type AsyncToolCallStartHandler = (asyncToolCall: AsyncToolCallEventHelper) => void; type AsyncToolCallStartHandlerAsync = (toolCall: AsyncToolCallEventHelper) => Promise; type ChunkHandler = (chunk: ContentPartChunkEvent) => void; type ContentPartEndHandler = (endContentPart: ContentPartEndEvent) => void; type ContentPartStartHandler = (contentPart: ContentPartEventHelper) => void; type ContentPartStartHandlerAsync = (contentPart: ContentPartEventHelper) => Promise; type DeletedHandler = () => void; type ErrorStartHandler = (errorStart: ErrorStartHandlerArgs) => void; type ErrorEndHandler = (errorEnd: ErrorEndHandlerArgs) => void; type AnyErrorStartHandler = (errorStart: AnyErrorStartHandlerArgs) => void; type AnyErrorEndHandler = (errorEnd: AnyErrorEndHandlerArgs) => void; type UnhandledErrorStartHandler = (errorStart: UnhandledErrorStartHandlerArgs) => void; type UnhandledErrorEndHandler = (errorStart: UnhandledErrorEndHandlerArgs) => void; type ExchangeEndHandler = (endExchange: ExchangeEndEvent) => void; type ExchangeStartHandler = (exchange: ExchangeEventHelper) => void; type ExchangeStartHandlerAsync = (exchange: ExchangeEventHelper) => Promise; type InputStreamStartHandler = (inputStream: AsyncInputStreamEventHelper) => void; type LabelUpdatedHandler = (labelUpdated: LabelUpdatedEvent) => void; type MessageEndHandler = (endMessage: MessageEndEvent) => void; type MessageStartHandler = (message: MessageEventHelper) => void; type MessageStartHandlerAsync = (x: MessageEventHelper) => Promise; type MetaEventHandler = (meta: MetaEvent) => void; type SessionEndHandler = (sessionEndEvent: SessionEndEvent) => void; type SessionStartedHandler = (sessionStartedEvent: SessionStartedEvent) => void; type SessionEndingHandler = (sessionEndingEvent: SessionEndingEvent) => void; type SessionStartHandler = (session: SessionEventHelper) => void; type SessionStartHandlerAsync = (session: SessionEventHelper) => Promise; type ToolCallEndHandler = (endToolCall: ToolCallEndEvent) => void; type ToolCallStartHandler = (toolCall: ToolCallEventHelper) => void; type ToolCallStartHandlerAsync = (toolCall: ToolCallEventHelper) => Promise; type ToolCallConfirmationHandler = (confirmToolCall: ToolCallConfirmationEvent) => void; type ExecutingToolCallHandler = (event: ExecutingToolCallEvent) => void; type ToolCallConfirmHandler = (args: ToolCallConfirmationHandlerArgs) => void; type ToolCallCompletedHandler = (completedToolCall: CompletedToolCall) => void; type ContentPartCompletedHandler = (completedContentPart: CompletedContentPart) => void; type MessageCompletedHandler = (completedMessage: CompletedMessage) => void; type InterruptStartHandler = (interruptStart: InterruptStartHandlerArgs) => void; type InterruptEndHandler = (interruptEnd: InterruptEndHandlerArgs) => void; type InterruptCompletedHandler = (interruptCompleted: InterruptCompletedHandlerArgs) => void; type SessionStartEventOptions = { conversationId: string; /** * 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; properties?: ConversationEventHelperProperties; } & SessionStartEvent; type ErrorEndEventOptions = { errorId: string; } & ErrorEndEvent; type ErrorStartEventOptions = { errorId?: string; } & ErrorStartEvent; type ExchangeStartEventOptions = { exchangeId?: string; properties?: ConversationEventHelperProperties; } & ExchangeStartEvent; type InputStreamStartEventOptions = { streamId?: string; properties?: ConversationEventHelperProperties; } & AsyncInputStreamStartEvent; type MessageStartEventOptions = { messageId?: string; properties?: ConversationEventHelperProperties; } & MakeOptional; type ToolCallStartEventWithId = { toolCallId?: string; properties?: ConversationEventHelperProperties; } & ToolCallStartEvent; type ContentPartStartEventOptions = { contentPartId?: string; properties?: ConversationEventHelperProperties; } & ContentPartStartEvent; type ConversationEventHelperProperties = Record; type ErrorStartHandlerArgs = { errorId: string; } & ErrorStartEvent; type ErrorEndHandlerArgs = { errorId: string; } & ErrorEndEvent; type AnyErrorStartHandlerArgs = { source: ConversationEventErrorSource; } & ErrorStartHandlerArgs; type AnyErrorEndHandlerArgs = { source: ConversationEventErrorSource; } & ErrorEndHandlerArgs; type UnhandledErrorStartHandlerArgs = AnyErrorStartHandlerArgs; type UnhandledErrorEndHandlerArgs = AnyErrorEndHandlerArgs; type InterruptStartHandlerArgs = { interruptId: string; startEvent: InterruptStartEvent; }; type InterruptEndHandlerArgs = { interruptId: string; endEvent: InterruptEndEvent; }; type InterruptCompletedHandlerArgs = { interruptId: string; startEvent: InterruptStartEvent; endEvent: InterruptEndEvent; }; type ToolCallConfirmationHandlerArgs = { toolCallId: string; confirmEvent: ToolCallConfirmationEvent; }; type ConversationEventErrorSource = ConversationEventHelperBase; type SendMessageWithContentPartOptions = Simplify, 'data'> & MessageStartEventOptions & MakeOptional>; type ConversationEventHelperManagerConfig = { emit: ConversationEventEmitter; }; /** * Thrown by conversation event helper classes when invalid event content is detected. This error can be returned to * clients to inform them of the invalid input. */ declare class ConversationEventValidationError extends Error { } /** * Thrown by conversation event helper classes when an operation was performed while the helper is in state that doesn't * allow that operation. This error should be treated as an internal error and not returned to clients. */ declare class ConversationEventInvalidOperationError extends Error { } declare enum EventErrorId { AGENT_COULD_NOT_BE_STARTED = "AGENT_COULD_NOT_BE_STARTED", SESSION_START_PROCESSING_FAILED = "SESSION_START_PROCESSING_FAILED", CLIENT_EVENT_PROCESSING_FAILED = "CLIENT_EVENT_PROCESSING_FAILED", EXCHANGE_COULD_NOT_BE_CREATED = "EXCHANGE_COULD_NOT_BE_CREATED", MESSAGE_COULD_NOT_BE_CREATED = "MESSAGE_COULD_NOT_BE_CREATED", COULD_NOT_CREATE_CONTENT_PART = "COULD_NOT_CREATE_CONTENT_PART", COULD_SIGNAL_USER_ACTIVITY = "COULD_SIGNAL_USER_ACTIVITY", AGENT_EVENT_PROCESSING_FAILED = "AGENT_EVENT_PROCESSING_FAILED", COULD_NOT_ENSURE_EXCHANGE = "COULD_NOT_ENSURE_EXCHANGE", COULD_NOT_CREATE_MESSAGE = "COULD_NOT_CREATE_MESSAGE", CONTENT_PART_HAS_CITATION_ERRORS = "CONTENT_PART_HAS_CITATION_ERRORS", EXCHANGE_START_PROCESSING_FAILED = "EXCHANGE_START_PROCESSING_FAILED", EXCHANGE_END_PROCESSING_FAILED = "EXCHANGE_END_PROCESSING_FAILED", MESSAGE_START_PROCESSING_FAILED = "MESSAGE_START_PROCESSING_FAILED", MESSAGE_END_PROCESSING_FAILED = "MESSAGE_END_PROCESSING_FAILED", CONTENT_PART_START_PROCESSING_FAILED = "CONTENT_PART_START_PROCESSING_FAILED", COULD_NOT_CREATE_TOOL_CALL = "COULD_NOT_CREATE_TOOL_CALL", TOOL_CALL_START_PROCESSING_FAILED = "TOOL_CALL_START_PROCESSING_FAILED", TOOL_CALL_END_PROCESSING_FAILED = "TOOL_CALL_END_PROCESSING_FAILED", COULD_NOT_CREATE_INTERRUPT = "COULD_NOT_CREATE_INTERRUPT", COULD_NOT_END_INTERRUPT = "COULD_NOT_END_INTERRUPT", TEXT_CONTENT_PART_PROCESSING_FAILED = "TEXT_CONTENT_PART_PROCESSING_FAILED", EXTERNAL_CONTENT_PART_PROCESSING_FAILED = "EXTERNAL_CONTENT_PART_PROCESSING_FAILED" } /** * Type guard that determines if an InlineOrExternalValue value is an InlineValue value. * @param value The value to check. * @returns true if the value has type InlineValue */ declare const isInlineValue: (value: InlineOrExternalValue | null | undefined) => value is InlineValue; /** * Type assertion that fails if an InlineOrExternalValue value is not an InlineValue value. * @param value The value to check. * @throw TypeError if the value is not an InlineValue. */ declare function assertInlineValue(value: InlineOrExternalValue | null | undefined): asserts value is InlineValue; /** * Type guard that determines if an InlineOrExternalValue value is an ExternalValue value. * @param value The value to check. * @returns true if the value has type ExternalValue */ declare const isExternalValue: (value: InlineOrExternalValue | null | undefined) => value is ExternalValue; /** * Type assertion that fails if an InlineOrExternalValue value is not an ExternalValue value. * @param value The value to check. * @throw TypeError if the value is not an ExternalValue. */ declare function assertExternalValue(value: InlineOrExternalValue | null | undefined): asserts value is ExternalValue; declare function isCitationSourceUrl(citationSource: CitationSource): citationSource is CitationSourceUrl; declare function assertCitationSourceUrl(citationSource: CitationSource): asserts citationSource is CitationSourceUrl; declare function isCitationSourceMedia(citationSource: CitationSource): citationSource is CitationSourceMedia; declare function assertCitationSourceMedia(citationSource: CitationSource): asserts citationSource is CitationSourceMedia; /** * ContentPartHelper - Helper class for ContentPart with convenience methods */ /** * Helper class that wraps ContentPart with convenience methods * for accessing inline/external data. */ declare class ContentPartHelper implements ContentPartGetResponse { /** Unique identifier for the content part (alias for contentPartId) */ id: string; /** Unique identifier for the content part */ contentPartId: string; /** The MIME type of the content */ mimeType: string; /** The actual content data (inline or external) */ data: InlineOrExternalValue; /** Array of citations referenced in this content part */ citations: Citation[]; /** Whether this content part is a transcript produced by the LLM */ isTranscript?: boolean; /** 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; constructor(contentPart: ContentPart); /** * Check if data is stored inline */ get isDataInline(): boolean; /** * Check if data is stored externally (URI) */ get isDataExternal(): boolean; /** * Get the data content. * Returns string for inline data, or fetches from URI for external data. */ getData(): Promise; } /** * Transformers for Conversational Agent Service * * Transform API responses to use helper classes and SDK naming conventions. */ /** * Transform an array of exchanges to use helper classes * * @internal * @param exchanges - Raw exchange data from the API * @returns Transformed exchanges with helper classes and SDK naming conventions */ declare function transformExchanges(exchanges: Exchange[]): ExchangeGetResponse[]; /** * Transform a single exchange to use helper classes and SDK naming conventions * * @internal * @param exchange - Raw exchange data from the API * @returns Transformed exchange with helper classes and SDK naming conventions */ declare function transformExchange(exchange: Exchange): ExchangeGetResponse; /** * Transform a message to use helper classes and SDK naming conventions * * @internal * @param message - Raw message data from the API * @returns Transformed message with helper classes and SDK naming conventions */ declare function transformMessage(message: Message): MessageGetResponse; /** * ConversationService - Service for conversation management * * Provides conversation CRUD operations and real-time WebSocket functionality. */ /** * Service for creating and managing conversations with UiPath Conversational Agents * * @example * ```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' }); * * // Start a real-time chat session * const session = conversation.startSession(); * session.onExchangeStart((exchange) => { * exchange.onMessageStart((message) => { * if (message.isAssistant) { * message.onContentPartStart((part) => { * if (part.isMarkdown) { * part.onChunk((chunk) => console.log(chunk.data)); * } * }); * } * }); * }); * * // Send a message * const exchange = session.startExchange(); * await exchange.sendMessageWithContentPart({ data: 'Hello!' }); * ``` */ declare class ConversationService extends BaseService implements ConversationServiceModel, ConversationSessionMethods { /** Session manager for WebSocket lifecycle */ private _sessionManager; /** Exchange service for scoped exchange methods on conversation objects */ private _exchangeService; /** Event helper for conversation events */ private _eventHelper; /** * Creates an instance of the Conversations service. * * @param instance - UiPath SDK instance providing authentication and configuration * @param options - Optional configuration (e.g. externalUserId for external app auth) */ constructor(instance: IUiPath$1, options?: ConversationalAgentOptions); create(agentId: number, folderId: number, options?: ConversationCreateOptions): Promise; getById(id: string): Promise; getAll(options?: ConversationGetAllOptions): Promise>; updateById(id: string, options: ConversationUpdateOptions): Promise; deleteById(id: string): Promise; uploadAttachment(id: string, file: File): Promise; getAttachmentUploadUri(conversationId: string, fileName: string): Promise; startSession(conversationId: string, options?: ConversationSessionOptions): SessionStream; getSession(conversationId: string): SessionStream | undefined; endSession(conversationId: string): void; /** * Iterator over all active sessions */ get sessions(): Iterable; /** * @internal */ get events(): ConversationEventHelperManager; /** * Current connection status */ get connectionStatus(): ConnectionStatus; /** * Whether WebSocket is connected */ get isConnected(): boolean; /** * Current connection error, if any */ get connectionError(): Error | null; onConnectionStatusChanged(handler: ConnectionStatusChangedHandler): () => void; disconnect(): void; private _getEvents; } /** * ExchangeService - Exchange operations for Conversations * * Exchanges represent individual request-response pairs within a conversation. * Each exchange contains messages from the user and assistant. */ /** * Service for exchange operations within a conversation * * Provides methods to list, retrieve, and provide feedback on exchanges. * Exchanges are the conversation turns containing user prompts and assistant responses. * * @example * ```typescript * import { Exchanges } from '@uipath/uipath-typescript/conversational-agent'; * * const exchanges = new Exchanges(sdk); * * // List all exchanges in a conversation * const conversationExchanges = await exchanges.getAll(conversationId); * * // Get a specific exchange with messages * const exchangeDetails = await exchanges.getById(conversationId, exchangeId); * * // Submit feedback for an exchange * await exchanges.createFeedback(conversationId, exchangeId, { * rating: FeedbackRating.Positive, * comment: 'Great response!' * }); * ``` */ declare class ExchangeService extends BaseService implements ExchangeServiceModel { /** * Creates an instance of the ExchangeService. * * @param instance - UiPath SDK instance providing authentication and configuration * @param options - Optional configuration (e.g. externalUserId for external app auth) */ constructor(instance: IUiPath$1, options?: ConversationalAgentOptions); getAll(conversationId: string, options?: ExchangeGetAllOptions): Promise>; getById(conversationId: string, exchangeId: string, options?: ExchangeGetByIdOptions): Promise; createFeedback(conversationId: string, exchangeId: string, options: CreateFeedbackOptions): Promise; } /** * MessageService - Message operations for Conversations * * Messages are the individual turns within an exchange. Each exchange typically * contains a user message (the prompt) and an assistant message (the response). * Messages contain content parts which hold the actual text, attachments, or tool calls. */ /** * Service for message operations within a conversation * * Provides methods to retrieve individual messages and their content parts. * Content parts can contain text, attachments, citations, or tool calls. * * @example * ```typescript * import { Messages } from '@uipath/uipath-typescript/conversational-agent'; * * const messages = new Messages(sdk); * * // Get a specific message * const messageDetails = await messages.getById(conversationId, exchangeId, messageId); * * // Access message properties * console.log(messageDetails.role); * console.log(messageDetails.contentParts); * console.log(messageDetails.toolCalls); * * // Get external content part data * const contentPartDetails = await messages.getContentPartById( * conversationId, * exchangeId, * messageId, * contentPartId * ); * ``` */ declare class MessageService extends BaseService implements MessageServiceModel { /** * Creates an instance of the MessageService. * * @param instance - UiPath SDK instance providing authentication and configuration * @param options - Optional configuration (e.g. externalUserId for external app auth) */ constructor(instance: IUiPath$1, options?: ConversationalAgentOptions); getById(conversationId: string, exchangeId: string, messageId: string): Promise; getContentPartById(conversationId: string, exchangeId: string, messageId: string, contentPartId: string): Promise; } /** * UserSettingsService - Service for managing user profile and context settings */ /** * 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. */ declare class UserSettingsService extends BaseService implements UserSettingsServiceModel { /** * Creates an instance of the UserSettingsService. * * @param instance - UiPath SDK instance providing authentication and configuration * @param options - Optional configuration (e.g. externalUserId for external app auth) */ constructor(instance: IUiPath$1, options?: ConversationalAgentOptions); getSettings(): Promise; updateSettings(options: UserSettingsUpdateOptions): Promise; } /** * ConversationalAgentService - Main entry point for Conversational Agent functionality */ /** * Service for interacting with UiPath Conversational Agent API */ declare class ConversationalAgentService extends BaseService implements ConversationalAgentServiceModel { /** Service for creating and managing conversations. See {@link ConversationServiceModel}. */ readonly conversations: ConversationService; /** Service for reading and updating the current user's profile/context settings. See {@link UserSettingsServiceModel}. */ readonly user: UserSettingsService; /** Configured SDK origin, used to keep citation downloads on the tenant's host. */ private readonly baseUrl; /** * Creates an instance of the ConversationalAgent service. * * @param instance - UiPath SDK instance providing authentication and configuration * @param options - Optional configuration (e.g. externalUserId for external app auth) */ constructor(instance: IUiPath$1, options?: ConversationalAgentOptions); onConnectionStatusChanged(handler: ConnectionStatusChangedHandler): () => void; getAll(folderId?: number): Promise; getById(id: number, folderId: number): Promise; downloadCitationSource(source: CitationSourceMedia): Promise; getFeatureFlags(): Promise; } export { AgentMap, AsyncInputStreamEventHelper, AsyncInputStreamEventHelperImpl, AsyncToolCallEventHelper, AsyncToolCallEventHelperImpl, CitationErrorType, ContentPartEventHelper, ContentPartEventHelperImpl, ContentPartHelper, ConversationEventHelperBase, ConversationEventHelperManager, ConversationEventHelperManagerImpl, ConversationEventInvalidOperationError, ConversationEventValidationError, ConversationGetAllFilterMap, ConversationMap, ConversationalAgentService as ConversationalAgent, ConversationalAgentService, EventErrorId, ExchangeEventHelper, ExchangeEventHelperImpl, ExchangeMap, ExchangeService, ExchangeService as Exchanges, FeedbackRating, InputStreamSpeechSensitivity, InterruptType, MessageEventHelper, MessageEventHelperImpl, MessageMap, MessageRole, MessageService, MessageService as Messages, SessionEventHelper, SessionEventHelperImpl, SortOrder, ToolCallEventHelper, ToolCallEventHelperImpl, UserSettingsService as UserSettings, UserSettingsMap, UserSettingsService, assertCitationSourceMedia, assertCitationSourceUrl, assertExternalValue, assertInlineValue, createAgentWithMethods, createConversationWithMethods, isCitationSourceMedia, isCitationSourceUrl, isExternalValue, isInlineValue, transformExchange, transformExchanges, transformMessage }; export type { AgentAppearance, AgentConversationServiceModel, AgentCreateConversationOptions, AgentGetByIdResponse, AgentGetResponse, AgentInput, AgentMethods, AgentStartingPrompt, AnyErrorEndHandler, AnyErrorEndHandlerArgs, AnyErrorStartHandler, AnyErrorStartHandlerArgs, AsyncInputStream, AsyncInputStreamChunkEvent, AsyncInputStreamChunkHandler, AsyncInputStreamEndEvent, AsyncInputStreamEndHandler, AsyncInputStreamEvent, AsyncInputStreamStartEvent, AsyncToolCallStartHandler, AsyncToolCallStartHandlerAsync, AsyncToolCallStream, ChunkHandler, Citation, CitationEndEvent, CitationError, CitationEvent, CitationOptions, CitationSource, CitationSourceBase, CitationSourceMedia, CitationSourceUrl, CitationStartEvent, ClientSideTool, CompletedContentPart, CompletedMessage, CompletedToolCall, ContentPart, ContentPartChunkEvent, ContentPartCompletedHandler, ContentPartData, ContentPartEndEvent, ContentPartEndHandler, ContentPartEvent, ContentPartGetResponse, ContentPartInterrupted, ContentPartStartEvent, ContentPartStartEventOptions, ContentPartStartEventWithData, ContentPartStartHandler, ContentPartStartHandlerAsync, ContentPartStartMetaData, ContentPartStream, ConversationAttachmentCreateResponse, ConversationAttachmentUploadResponse, ConversationCreateOptions, ConversationCreateResponse, ConversationDeleteResponse, ConversationEvent, ConversationEventEmitter, ConversationEventErrorSource, ConversationEventHandler, ConversationEventHelperManagerConfig, ConversationEventHelperProperties, ConversationExchangeServiceModel, ConversationGetAllOptions, ConversationGetResponse, ConversationJobStartOverrides, ConversationMethods, ConversationServiceModel, ConversationSessionMethods, ConversationSessionOptions, ConversationUpdateOptions, ConversationUpdateResponse, ConversationalAgentOptions, ConversationalAgentServiceModel, CreateFeedbackOptions, DeletedHandler, ErrorEndEvent, ErrorEndEventOptions, ErrorEndHandler, ErrorEndHandlerArgs, ErrorEvent, ErrorStartEvent, ErrorStartEventOptions, ErrorStartHandler, ErrorStartHandlerArgs, Exchange, ExchangeEndEvent, ExchangeEndHandler, ExchangeEvent, ExchangeGetAllOptions, ExchangeGetByIdOptions, ExchangeGetResponse, ExchangeServiceModel, ExchangeStartEvent, ExchangeStartEventOptions, ExchangeStartHandler, ExchangeStartHandlerAsync, ExchangeStream, ExecutingToolCallEvent, ExecutingToolCallHandler, ExternalValue, FeatureFlags, FeedbackCreateResponse, FileUploadAccess, GenericInterruptStartEvent, InlineOrExternalValue, InlineValue, InputStreamStartEventOptions, InputStreamStartHandler, Interrupt, InterruptCompletedHandler, InterruptCompletedHandlerArgs, InterruptEndEvent, InterruptEndHandler, InterruptEndHandlerArgs, InterruptEvent, InterruptStartEvent, InterruptStartHandler, InterruptStartHandlerArgs, JSONArray, JSONObject, JSONPrimitive, JSONValue, LabelUpdatedEvent, LabelUpdatedHandler, MakeOptional, MakeRequired, Message, MessageCompletedHandler, MessageEndEvent, MessageEndHandler, MessageEvent, MessageGetResponse, MessageServiceModel, MessageStartEvent, MessageStartEventOptions, MessageStartHandler, MessageStartHandlerAsync, MessageStream, MetaData, MetaEvent, MetaEventHandler, RawAgentGetByIdResponse, RawAgentGetResponse, RawConversationGetResponse, SendMessageWithContentPartOptions, SessionCapabilities, SessionEndEvent, SessionEndHandler, SessionEndingEvent, SessionEndingHandler, SessionStartEvent, SessionStartEventOptions, SessionStartHandler, SessionStartHandlerAsync, SessionStartedEvent, SessionStartedHandler, SessionStream, Simplify, ToolCall, ToolCallCompletedHandler, ToolCallConfirmHandler, ToolCallConfirmationEndValue, ToolCallConfirmationEvent, ToolCallConfirmationHandler, ToolCallConfirmationHandlerArgs, ToolCallConfirmationInterruptStartEvent, ToolCallConfirmationValue, ToolCallEndEvent, ToolCallEndHandler, ToolCallEvent, ToolCallInputValue, ToolCallOutputValue, ToolCallResult, ToolCallStartEvent, ToolCallStartEventWithId, ToolCallStartHandler, ToolCallStartHandlerAsync, ToolCallStream, UnhandledErrorEndHandler, UnhandledErrorEndHandlerArgs, UnhandledErrorStartHandler, UnhandledErrorStartHandlerArgs, UserSettingsGetResponse, UserSettingsServiceModel, UserSettingsUpdateOptions, UserSettingsUpdateResponse };