@uipath/uipath-typescript 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -56,6 +56,11 @@ interface IUiPath {
56
56
  * Get the current authentication token
57
57
  */
58
58
  getToken(): string | undefined;
59
+ /**
60
+ * Logout from the SDK, clearing all authentication state.
61
+ * After calling this method, the user will need to re-initialize to authenticate again.
62
+ */
63
+ logout(): void;
59
64
  }
60
65
 
61
66
  /**
@@ -116,6 +121,11 @@ declare class UiPath$1 implements IUiPath {
116
121
  * Get the current authentication token
117
122
  */
118
123
  getToken(): string | undefined;
124
+ /**
125
+ * Logout from the SDK, clearing all authentication state.
126
+ * After calling this method, the user will need to re-initialize to authenticate again.
127
+ */
128
+ logout(): void;
119
129
  }
120
130
 
121
131
  /**
@@ -5586,101 +5596,4430 @@ declare class UiPath extends UiPath$1 {
5586
5596
  }
5587
5597
 
5588
5598
  /**
5589
- * Error thrown when authorization fails (403 errors)
5590
- * Common scenarios:
5591
- * - Insufficient permissions
5592
- * - Access denied to resource
5593
- * - Invalid scope
5599
+ * Constants for Conversational Agent
5594
5600
  */
5595
- declare class AuthorizationError extends UiPathError {
5596
- constructor(params?: Partial<ErrorParams>);
5597
- }
5601
+ /**
5602
+ * Maps API response fields to SDK field names (API → SDK)
5603
+ * Used when transforming API responses for SDK consumers.
5604
+ * For request transformation (SDK → API), use `transformRequest(data, ConversationMap)`.
5605
+ */
5606
+ declare const ConversationMap: {
5607
+ [key: string]: string;
5608
+ };
5609
+ /**
5610
+ * Maps fields for Exchange entity to ensure consistent SDK naming
5611
+ */
5612
+ declare const ExchangeMap: {
5613
+ [key: string]: string;
5614
+ };
5615
+ /**
5616
+ * Maps fields for Message entity to ensure consistent SDK naming
5617
+ */
5618
+ declare const MessageMap: {
5619
+ [key: string]: string;
5620
+ };
5598
5621
 
5599
5622
  /**
5600
- * Error thrown when validation fails (400 errors or client-side validation)
5601
- * Common scenarios:
5602
- * - Invalid input parameters
5603
- * - Missing required fields
5604
- * - Invalid data format
5623
+ * Common types for Conversational Agent
5624
+ * Contains IDs, primitives, and utility types used across conversation types.
5605
5625
  */
5606
- declare class ValidationError extends UiPathError {
5607
- constructor(params?: Partial<ErrorParams>);
5626
+ /**
5627
+ * Identifies the origin of a message in the conversation.
5628
+ */
5629
+ declare enum MessageRole {
5630
+ System = "system",
5631
+ User = "user",
5632
+ Assistant = "assistant"
5608
5633
  }
5609
-
5610
5634
  /**
5611
- * Error thrown when a resource is not found (404 errors)
5612
- * Common scenarios:
5613
- * - Resource doesn't exist
5614
- * - Invalid ID provided
5615
- * - Resource deleted
5635
+ * Identifies the type of an interrupt.
5616
5636
  */
5617
- declare class NotFoundError extends UiPathError {
5618
- constructor(params?: Partial<ErrorParams>);
5637
+ declare enum InterruptType {
5638
+ ToolCallConfirmation = "uipath_cas_tool_call_confirmation"
5619
5639
  }
5620
-
5621
5640
  /**
5622
- * Error thrown when rate limit is exceeded (429 errors)
5623
- * Common scenarios:
5624
- * - Too many requests in a time window
5625
- * - API throttling
5641
+ * Base interface for citation sources.
5626
5642
  */
5627
- declare class RateLimitError extends UiPathError {
5628
- constructor(params?: Partial<ErrorParams>);
5643
+ interface CitationSourceBase {
5644
+ /**
5645
+ * Title for the citation source, suitable for display to users.
5646
+ */
5647
+ title: string;
5648
+ /**
5649
+ * Label number for the citation source, suitable for display to users
5650
+ * (e.g. [1] for the first unique source, [2] for the second, etc.).
5651
+ */
5652
+ number: number;
5629
5653
  }
5630
-
5631
5654
  /**
5632
- * Error thrown when server encounters an error (5xx errors)
5633
- * Common scenarios:
5634
- * - Internal server error
5635
- * - Service unavailable
5636
- * - Gateway timeout
5655
+ * Used when the citation can be rendered as a link.
5637
5656
  */
5638
- declare class ServerError extends UiPathError {
5639
- constructor(params?: Partial<ErrorParams>);
5657
+ interface CitationSourceUrl extends CitationSourceBase {
5640
5658
  /**
5641
- * Checks if this is a temporary error that might succeed on retry
5659
+ * Citation url.
5642
5660
  */
5643
- get isRetryable(): boolean;
5661
+ url: string;
5644
5662
  }
5645
-
5646
5663
  /**
5647
- * Base error creation parameters - only what's needed
5664
+ * Used when the citation references media, such as a PDF document.
5648
5665
  */
5649
- interface ErrorParams {
5650
- message: string;
5651
- statusCode?: number;
5652
- requestId?: string;
5666
+ interface CitationSourceMedia extends CitationSourceBase {
5667
+ /** The mime type of the media. If non-specified, should be discovered through the downloadUrl. */
5668
+ mimeType?: string;
5669
+ /** Download URL for the media */
5670
+ downloadUrl?: string;
5671
+ /** The page number for the media, if applicable (e.g. for application/pdf documents) */
5672
+ pageNumber?: string;
5673
+ }
5674
+ /**
5675
+ * Citation sources can target either an Url or a media (e.g. a pdf document).
5676
+ * Repeated citation sources within a content part are identified by the same title and number.
5677
+ */
5678
+ type CitationSource = CitationSourceUrl | CitationSourceMedia;
5679
+ /**
5680
+ * JSON compatible primitive type.
5681
+ */
5682
+ type JSONPrimitive = string | number | boolean | null;
5683
+ /**
5684
+ * JSON compatible value type.
5685
+ */
5686
+ type JSONValue = JSONPrimitive | Record<string, any> | any[];
5687
+ /**
5688
+ * JSON compatible object type.
5689
+ */
5690
+ type JSONObject = Record<string, JSONValue>;
5691
+ /**
5692
+ * JSON compatible array type.
5693
+ */
5694
+ type JSONArray = JSONValue[];
5695
+ /**
5696
+ * An arbitrary JSON serializable object.
5697
+ */
5698
+ type MetaData = JSONObject;
5699
+ /**
5700
+ * Produces the provided object type with specified properties changed to optional.
5701
+ */
5702
+ type MakeOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
5703
+ /**
5704
+ * Produces the provided object type with specified properties changed to required.
5705
+ */
5706
+ type MakeRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
5707
+ /**
5708
+ * Causes typescript to simplify the display of object types created using MakeOptional, MakeRequired, and other utility
5709
+ * types. This doesn't change the effective type, but makes popups in the ide and compile error messages cleaner.
5710
+ */
5711
+ type Simplify<T> = T extends any[] | Date ? T : {
5712
+ [K in keyof T]: T[K];
5713
+ } & {};
5714
+ /**
5715
+ * Inline value - used when a value is small enough to be returned inline with an API result.
5716
+ */
5717
+ interface InlineValue<T> {
5718
+ inline: T;
5719
+ }
5720
+ /**
5721
+ * External value - used when a value is too large to be returned inline with an API result.
5722
+ */
5723
+ interface ExternalValue {
5724
+ uri: string;
5725
+ byteCount?: number;
5653
5726
  }
5727
+ /**
5728
+ * Inline or external value - used when a value can be too large to include inline in input or output data.
5729
+ * If the inline property is set, it contains the full value, otherwise the uri property is set and it contains an uri
5730
+ * from which the data can be downloaded.
5731
+ */
5732
+ type InlineOrExternalValue<T> = InlineValue<T> | ExternalValue;
5733
+ /**
5734
+ * Tool call input value type.
5735
+ */
5736
+ type ToolCallInputValue = JSONObject;
5737
+ /**
5738
+ * Tool call output value type.
5739
+ */
5740
+ type ToolCallOutputValue = JSONValue;
5654
5741
 
5655
5742
  /**
5656
- * Base error class for all UiPath SDK errors
5657
- * Pure TypeScript class with clean interface
5743
+ * Core data model types for Conversational Agent REST endpoints
5744
+ * Contains: Conversation, Exchange, Message, ContentPart, ToolCall, etc.
5745
+ */
5746
+
5747
+ /**
5748
+ * Represents the order in which items should be sorted.
5749
+ */
5750
+ declare enum SortOrder {
5751
+ Ascending = "ascending",
5752
+ Descending = "descending"
5753
+ }
5754
+ /**
5755
+ * Represents a citation or reference to an external source within a content part.
5658
5756
  */
5659
- declare abstract class UiPathError {
5757
+ interface Citation {
5660
5758
  /**
5661
- * Error type identifier (e.g., "AuthenticationError", "ValidationError")
5759
+ * Unique identifier for the citation.
5662
5760
  */
5663
- readonly type: string;
5761
+ id: string;
5664
5762
  /**
5665
- * Error message describing what went wrong
5763
+ * Unique identifier for the citation within its content part.
5666
5764
  */
5667
- readonly message: string;
5765
+ citationId: string;
5668
5766
  /**
5669
- * HTTP status code (400, 401, 403, 404, 500, etc.)
5767
+ * The offset of the start of the citation target in the content part data.
5670
5768
  */
5671
- readonly statusCode?: number;
5769
+ offset: number;
5672
5770
  /**
5673
- * Request ID for tracking with UiPath support
5771
+ * The length of the citation target in the content part data.
5674
5772
  */
5675
- readonly requestId?: string;
5773
+ length: number;
5676
5774
  /**
5677
- * Timestamp when the error occurred
5775
+ * The source being referenced by this citation.
5678
5776
  */
5679
- readonly timestamp: Date;
5777
+ sources: CitationSource[];
5778
+ /**
5779
+ * Timestamp indicating when the citation was created.
5780
+ */
5781
+ createdTime: string;
5782
+ /**
5783
+ * Timestamp indicating when the citation was last updated.
5784
+ */
5785
+ updatedTime: string;
5786
+ }
5787
+ /**
5788
+ * Citation options for input operations (without timestamps).
5789
+ */
5790
+ interface CitationOptions {
5791
+ citationId: string;
5792
+ offset: number;
5793
+ length: number;
5794
+ sources: CitationSource[];
5795
+ }
5796
+ /**
5797
+ * Content part data type - can be inline or external.
5798
+ */
5799
+ type ContentPartData = Simplify<InlineOrExternalValue<string>>;
5800
+ /**
5801
+ * Represents a single part of message content.
5802
+ */
5803
+ interface ContentPart {
5804
+ /**
5805
+ * Unique identifier for the content part.
5806
+ */
5807
+ id: string;
5808
+ /**
5809
+ * Unique identifier for the content part within the message.
5810
+ */
5811
+ contentPartId: string;
5812
+ /**
5813
+ * The MIME type of the content.
5814
+ */
5815
+ mimeType: string;
5816
+ /**
5817
+ * The actual content data.
5818
+ */
5819
+ data: ContentPartData;
5820
+ /**
5821
+ * Array of citations referenced in this content part.
5822
+ */
5823
+ citations: Citation[];
5824
+ /**
5825
+ * Indicates whether this content part is a transcript produced by the LLM.
5826
+ */
5827
+ isTranscript?: boolean;
5828
+ /**
5829
+ * Indicates whether this content part may be incomplete.
5830
+ */
5831
+ isIncomplete?: boolean;
5832
+ /**
5833
+ * Optional name for the content part.
5834
+ */
5835
+ name?: string;
5836
+ /**
5837
+ * Timestamp indicating when the content part was created.
5838
+ */
5839
+ createdTime: string;
5840
+ /**
5841
+ * Timestamp indicating when the content part was last updated.
5842
+ */
5843
+ updatedTime: string;
5844
+ }
5845
+ /**
5846
+ * Represents the result of a tool call execution.
5847
+ */
5848
+ interface ToolCallResult {
5849
+ /**
5850
+ * Timestamp indicating when the result was generated.
5851
+ */
5852
+ timestamp?: string;
5853
+ /**
5854
+ * The value returned by the tool.
5855
+ */
5856
+ output?: ToolCallOutputValue;
5857
+ /**
5858
+ * field for the tool call output value.
5859
+ */
5860
+ value?: InlineOrExternalValue<ToolCallOutputValue>;
5861
+ /**
5862
+ * Indicates whether the tool call resulted in an error.
5863
+ */
5864
+ isError?: boolean;
5865
+ /**
5866
+ * Indicates whether the tool call was cancelled.
5867
+ */
5868
+ cancelled?: boolean;
5869
+ }
5870
+ /**
5871
+ * Represents a call to an external tool or function within a message.
5872
+ */
5873
+ interface ToolCall {
5874
+ /**
5875
+ * Unique identifier for the tool call.
5876
+ */
5877
+ id: string;
5878
+ /**
5879
+ * Unique identifier for the tool call within the message.
5880
+ */
5881
+ toolCallId: string;
5882
+ /**
5883
+ * The name of the tool being called.
5884
+ */
5885
+ name: string;
5886
+ /**
5887
+ * Optional input value provided to the tool.
5888
+ */
5889
+ input?: ToolCallInputValue;
5890
+ /**
5891
+ * Legacy field for tool call input arguments.
5892
+ */
5893
+ arguments?: InlineOrExternalValue<ToolCallInputValue>;
5894
+ /**
5895
+ * Timestamp indicating when the tool call was initiated.
5896
+ */
5897
+ timestamp?: string;
5898
+ /**
5899
+ * Optional output value returned by the tool's execution.
5900
+ */
5901
+ result?: ToolCallResult;
5902
+ /**
5903
+ * Timestamp indicating when the tool call was created.
5904
+ */
5905
+ createdTime: string;
5906
+ /**
5907
+ * Timestamp indicating when the tool call was last updated.
5908
+ */
5909
+ updatedTime: string;
5910
+ }
5911
+ /**
5912
+ * Represents an interrupt within a message.
5913
+ */
5914
+ interface Interrupt {
5915
+ /**
5916
+ * Unique identifier for the interrupt.
5917
+ */
5918
+ id: string;
5919
+ /**
5920
+ * Unique identifier for the interrupt within the message.
5921
+ */
5922
+ interruptId: string;
5923
+ /**
5924
+ * The type of interrupt.
5925
+ */
5926
+ type: InterruptType;
5927
+ /**
5928
+ * The value associated with the interrupt start event.
5929
+ */
5930
+ interruptValue: unknown;
5931
+ /**
5932
+ * The value provided to end/resolve the interrupt.
5933
+ */
5934
+ endValue?: unknown;
5935
+ /**
5936
+ * Timestamp indicating when the interrupt was created.
5937
+ */
5938
+ createdTime: string;
5939
+ /**
5940
+ * Timestamp indicating when the interrupt was last updated.
5941
+ */
5942
+ updatedTime: string;
5943
+ }
5944
+ /**
5945
+ * Represents a single message within a conversation exchange.
5946
+ */
5947
+ interface Message {
5948
+ /**
5949
+ * Unique identifier for the message.
5950
+ */
5951
+ id: string;
5952
+ /**
5953
+ * Unique identifier for the message within its exchange.
5954
+ */
5955
+ messageId: string;
5956
+ /**
5957
+ * The role of the message sender.
5958
+ */
5959
+ role: MessageRole;
5960
+ /**
5961
+ * Contains the message's content parts.
5962
+ */
5963
+ contentParts: ContentPart[];
5964
+ /**
5965
+ * Array of tool calls made within this message.
5966
+ */
5967
+ toolCalls: ToolCall[];
5968
+ /**
5969
+ * Array of interrupts within this message.
5970
+ */
5971
+ interrupts: Interrupt[];
5972
+ /**
5973
+ * Timestamp indicating when the message was created.
5974
+ */
5975
+ createdTime: string;
5976
+ /**
5977
+ * Timestamp indicating when the message was last updated.
5978
+ */
5979
+ updatedTime: string;
5980
+ /**
5981
+ * Span identifier for distributed tracing.
5982
+ */
5983
+ spanId?: string;
5984
+ }
5985
+ /**
5986
+ * Feedback rating type.
5987
+ */
5988
+ declare enum FeedbackRating {
5989
+ Positive = "positive",
5990
+ Negative = "negative"
5991
+ }
5992
+ /**
5993
+ * Represents a group of related messages (exchange).
5994
+ */
5995
+ interface Exchange {
5996
+ /**
5997
+ * Unique identifier for the exchange.
5998
+ */
5999
+ id: string;
6000
+ /**
6001
+ * Identifies the exchange.
6002
+ */
6003
+ exchangeId: string;
6004
+ /**
6005
+ * Messages in the exchange.
6006
+ */
6007
+ messages: Message[];
6008
+ /**
6009
+ * Timestamp indicating when the exchange was created.
6010
+ */
6011
+ createdTime: string;
6012
+ /**
6013
+ * Timestamp indicating when the exchange was last updated.
6014
+ */
6015
+ updatedTime: string;
6016
+ /**
6017
+ * Span identifier for distributed tracing.
6018
+ */
6019
+ spanId?: string;
5680
6020
  /**
5681
- * Stack trace for debugging
6021
+ * The optional feedback rating given by the user.
5682
6022
  */
5683
- readonly stack?: string;
6023
+ feedbackRating?: FeedbackRating;
6024
+ }
6025
+ /**
6026
+ * Optional configuration options for when the service automatically starts agent job(s) to serve the conversation.
6027
+ * When not provided, service uses default configuration with RunAsMe set to false.
6028
+ */
6029
+ interface ConversationJobStartOverrides {
6030
+ /**
6031
+ * Whether the job(s) should run with the user's identity (RunAsMe). Defaults to false when not provided.
6032
+ */
6033
+ runAsMe?: boolean;
6034
+ }
6035
+ /**
6036
+ * Raw response type for conversation operations (without methods).
6037
+ * Represents a conversation between users and AI agents.
6038
+ */
6039
+ interface RawConversationGetResponse {
6040
+ /**
6041
+ * A globally unique identifier for the conversation.
6042
+ */
6043
+ id: string;
6044
+ /**
6045
+ * Timestamp indicating when the conversation was created.
6046
+ */
6047
+ createdTime: string;
6048
+ /**
6049
+ * Timestamp indicating when any conversation field(s) are updated.
6050
+ */
6051
+ updatedTime: string;
6052
+ /**
6053
+ * Timestamp indicating when the conversation last had activity.
6054
+ */
6055
+ lastActivityTime: string;
6056
+ /**
6057
+ * The human-readable label or title for the conversation.
6058
+ */
6059
+ label: string;
6060
+ /**
6061
+ * Whether the conversation label was automatically generated.
6062
+ */
6063
+ autogenerateLabel: boolean;
6064
+ /**
6065
+ * Identifier of the user who owns or initiated the conversation.
6066
+ */
6067
+ userId: string;
6068
+ /**
6069
+ * Identifier of the organization.
6070
+ */
6071
+ orgId: string;
6072
+ /**
6073
+ * Identifier of the tenant within the organization.
6074
+ */
6075
+ tenantId: string;
6076
+ /**
6077
+ * Identifier of the folder where the conversation is stored.
6078
+ */
6079
+ folderId: number;
6080
+ /**
6081
+ * Identifier of the agent used for this conversation
6082
+ */
6083
+ agentId?: number;
6084
+ /**
6085
+ * Trace identifier for distributed tracing.
6086
+ */
6087
+ traceId: string;
6088
+ /**
6089
+ * Span identifier for distributed tracing.
6090
+ */
6091
+ spanId?: string;
6092
+ /**
6093
+ * Optional configuration options for when the service automatically starts agent job(s).
6094
+ */
6095
+ jobStartOverrides?: ConversationJobStartOverrides;
6096
+ /**
6097
+ * Optional job key for conversations that are part of a larger job.
6098
+ */
6099
+ jobKey?: string;
6100
+ /**
6101
+ * Whether the conversation's job is running locally.
6102
+ */
6103
+ isLocalJobExecution?: boolean;
6104
+ }
6105
+
6106
+ /**
6107
+ * Event types for Conversational Agent WebSocket protocol
6108
+ */
6109
+
6110
+ /**
6111
+ * Identifies how sensitive the LLM should be when detecting the start or end of speech.
6112
+ *
6113
+ * * UNSPECIFIED - the default is HIGH
6114
+ * * HIGH - Will detect the start/end of speech more often.
6115
+ * * LOW - Will detect the start/end of speech less often.
6116
+ */
6117
+ declare enum InputStreamSpeechSensitivity {
6118
+ Unspecified = "UNSPECIFIED",
6119
+ High = "HIGH",
6120
+ Low = "LOW"
6121
+ }
6122
+ /**
6123
+ * Signals that a content stream was interrupted.
6124
+ */
6125
+ interface ContentPartInterrupted {
6126
+ }
6127
+ /**
6128
+ * Describes the capabilities of the sender. This type allows custom properties, in addition to the ones defined.
6129
+ */
6130
+ interface SessionCapabilities {
6131
+ /**
6132
+ * Indicates the sender may produce a cross exchange input stream events if the receiver indicates they can be handled.
6133
+ */
6134
+ asyncInputStreamEmitter?: boolean;
6135
+ /**
6136
+ * Indicates the sender can handle cross exchange input stream events.
6137
+ */
6138
+ asyncInputStreamHandler?: boolean;
6139
+ /**
6140
+ * Indicates the sender may produce cross exchange tool calls if the receiver indicates they can be handled.
6141
+ */
6142
+ asyncToolCallEmitter?: boolean;
6143
+ /**
6144
+ * Indicates the sender can handle cross exchange tool calls.
6145
+ */
6146
+ asyncToolCallHandler?: boolean;
6147
+ /**
6148
+ * Indicates the mime types which the sender can send in input streams and as message content, provided the receiver
6149
+ * indicates they can handle the mime type.
6150
+ */
6151
+ mimeTypesEmitted?: string[];
6152
+ /**
6153
+ * Indicates the mime types the sender can handle. Wildcards such as "*\/*" and "text/*" are allowed.
6154
+ */
6155
+ mimeTypesHandled?: string[];
6156
+ /** Allow custom properties */
6157
+ [key: string]: unknown;
6158
+ }
6159
+ /**
6160
+ * Signals the start of a session.
6161
+ */
6162
+ interface SessionStartEvent {
6163
+ /**
6164
+ * Indicates the capabilities of the end point that sent the session start event.
6165
+ */
6166
+ capabilities?: SessionCapabilities;
6167
+ /**
6168
+ * Optional metadata that can be used for any data pertaining to the starting event stream.
6169
+ */
6170
+ metaData?: MetaData;
6171
+ }
6172
+ /**
6173
+ * Signals the acceptance of the start of a session.
6174
+ */
6175
+ interface SessionStartedEvent {
6176
+ /**
6177
+ * Indicates the capabilities of the end point that received the session start event.
6178
+ */
6179
+ capabilities?: SessionCapabilities;
6180
+ }
6181
+ /**
6182
+ * Indicates the end of a session.
6183
+ */
6184
+ interface SessionEndEvent {
6185
+ /**
6186
+ * Optional metadata that can be used for any data having to do with the completion of the session.
6187
+ */
6188
+ metaData?: MetaData;
6189
+ }
6190
+ /**
6191
+ * Indicates the service wants the client to end the current session.
6192
+ */
6193
+ interface SessionEndingEvent {
6194
+ /**
6195
+ * Number of milliseconds before the websocket is closed by the service to force the session to end.
6196
+ */
6197
+ timeToLiveMS: number;
6198
+ }
6199
+ /**
6200
+ * Signals the start of an exchange of messages within a conversation.
6201
+ */
6202
+ interface ExchangeStartEvent {
6203
+ /**
6204
+ * Optional value specifying the sequence number of the exchange within the conversation.
6205
+ */
6206
+ conversationSequence?: number;
6207
+ /**
6208
+ * Optional metadata that can be used for any data pertaining to the starting event stream.
6209
+ */
6210
+ metadata?: MetaData;
6211
+ /**
6212
+ * The time the exchange started.
6213
+ */
6214
+ timestamp?: string;
6215
+ }
6216
+ /**
6217
+ * Signals the end of an exchange of messages within a conversation.
6218
+ */
6219
+ interface ExchangeEndEvent {
6220
+ /**
6221
+ * Optional metadata that can be used for any data having to do with the completion of the event stream.
6222
+ */
6223
+ metaData?: MetaData;
6224
+ }
6225
+ /**
6226
+ * Signals the start of a message.
6227
+ */
6228
+ interface MessageStartEvent {
6229
+ /**
6230
+ * Optional value that provides the sequence of the message within the exchange.
6231
+ */
6232
+ exchangeSequence?: number;
6233
+ /**
6234
+ * Message timestamp.
6235
+ */
6236
+ timestamp?: string;
6237
+ /**
6238
+ * Required value that identifies the origin of the message (system, user, or agent).
6239
+ */
6240
+ role: MessageRole;
6241
+ /**
6242
+ * Optional metadata that can be used for any data pertaining to the starting event stream.
6243
+ */
6244
+ metaData?: MetaData;
6245
+ }
6246
+ /**
6247
+ * Signals the end of a message.
6248
+ */
6249
+ interface MessageEndEvent {
6250
+ /**
6251
+ * Optional metadata that can be used for any data having to do with the completion of the event stream.
6252
+ */
6253
+ metaData?: MetaData;
6254
+ }
6255
+ /**
6256
+ * Content part start event metadata with transcript indicator.
6257
+ */
6258
+ type ContentPartStartMetaData = MetaData & {
6259
+ /**
6260
+ * Indicates that the content part is transcript produced by the LLM from user voice input.
6261
+ */
6262
+ isTranscript?: boolean;
6263
+ };
6264
+ /**
6265
+ * Signals the start of a message content part.
6266
+ */
6267
+ interface ContentPartStartEvent {
6268
+ /**
6269
+ * Describes the type and format of a content part.
6270
+ */
6271
+ mimeType: string;
6272
+ /**
6273
+ * Optional metadata that can be used for any data pertaining to the starting event stream.
6274
+ */
6275
+ metaData?: ContentPartStartMetaData;
6276
+ /**
6277
+ * If present, indicates that the content part's data is stored externally.
6278
+ */
6279
+ externalValue?: ExternalValue;
6280
+ /**
6281
+ * Optional name for the content part. Typically used for file attachment names.
6282
+ */
6283
+ name?: string;
6284
+ /**
6285
+ * The time the content part was created.
6286
+ */
6287
+ timestamp?: string;
6288
+ }
6289
+ /**
6290
+ * Signals the end of a message content part.
6291
+ */
6292
+ interface ContentPartEndEvent {
6293
+ /**
6294
+ * Optional value that provides the contentPartSequence sent in the last content part chunk sent.
6295
+ */
6296
+ lastChunkContentPartSequence?: number;
6297
+ /**
6298
+ * Indicates if the content part stream was interrupted.
6299
+ */
6300
+ interrupted?: ContentPartInterrupted;
6301
+ /**
6302
+ * Optional metadata that can be used for any data having to do with the completion of the event stream.
6303
+ */
6304
+ metaData?: MetaData;
6305
+ }
6306
+ /**
6307
+ * Represents the start of an error condition.
6308
+ */
6309
+ interface ErrorStartEvent {
6310
+ /**
6311
+ * A message that can be displayed to the user.
6312
+ */
6313
+ message: string;
6314
+ /**
6315
+ * An optional property that contains error related details.
6316
+ */
6317
+ details?: JSONValue;
6318
+ }
6319
+ /**
6320
+ * Represents the end of an error condition.
6321
+ */
6322
+ interface ErrorEndEvent {
6323
+ }
6324
+ /**
6325
+ * Encapsulates sub-events that represent the start and end of an error condition.
6326
+ */
6327
+ interface ErrorEvent {
6328
+ /**
6329
+ * An identifier for the error.
6330
+ */
6331
+ errorId: string;
6332
+ /**
6333
+ * If present, indicates the start of an error condition.
6334
+ */
6335
+ startError?: ErrorStartEvent;
6336
+ /**
6337
+ * If present, indicates the end of an error condition.
6338
+ */
6339
+ endError?: ErrorEndEvent;
6340
+ }
6341
+ /**
6342
+ * Indicates the start of a citation target in the stream of content part chunks.
6343
+ */
6344
+ interface CitationStartEvent {
6345
+ }
6346
+ /**
6347
+ * Indicates the end of a citation target in the stream of content part chunks.
6348
+ */
6349
+ interface CitationEndEvent {
6350
+ /**
6351
+ * Provides data concerning the citation sources.
6352
+ */
6353
+ sources: CitationSource[];
6354
+ }
6355
+ /**
6356
+ * Encapsulates sub-events related to citations.
6357
+ */
6358
+ interface CitationEvent {
6359
+ /**
6360
+ * Identifies a set of citation sources.
6361
+ */
6362
+ citationId: string;
6363
+ /**
6364
+ * Indicates the start of a citation target.
6365
+ */
6366
+ startCitation?: CitationStartEvent;
6367
+ /**
6368
+ * Indicates the end of a citation target.
6369
+ */
6370
+ endCitation?: CitationEndEvent;
6371
+ /**
6372
+ * Sent by the service to indicate an error condition impacting a citation.
6373
+ */
6374
+ citationError?: ErrorEvent;
6375
+ }
6376
+ /**
6377
+ * Contains a chunk of a message content part.
6378
+ */
6379
+ interface ContentPartChunkEvent {
6380
+ /**
6381
+ * Content part data.
6382
+ */
6383
+ data?: string;
6384
+ /**
6385
+ * Sub-event for attaching citations to content chunks.
6386
+ */
6387
+ citation?: CitationEvent;
6388
+ }
6389
+ /**
6390
+ * Signals the start of an input stream.
6391
+ */
6392
+ interface AsyncInputStreamStartEvent {
6393
+ /**
6394
+ * Describes the type of data sent over the input stream.
6395
+ */
6396
+ mimeType: string;
6397
+ /**
6398
+ * Determines how sensitive the LLM should be in detecting the start of speech.
6399
+ */
6400
+ startOfSpeechSensitivity?: InputStreamSpeechSensitivity;
6401
+ /**
6402
+ * Determines how sensitive the LLM should be in detecting the end of speech.
6403
+ */
6404
+ endOfSpeechSensitivity?: InputStreamSpeechSensitivity;
6405
+ /**
6406
+ * The required duration of detected speech before start-of-speech is committed.
6407
+ */
6408
+ prefixPaddingMs?: number;
6409
+ /**
6410
+ * The required duration of detected non-speech before end-of-speech is committed.
6411
+ */
6412
+ silenceDurationMs?: number;
6413
+ /**
6414
+ * Optional metadata that can be used for any data pertaining to the starting event stream.
6415
+ */
6416
+ metaData?: MetaData;
6417
+ }
6418
+ /**
6419
+ * Signals the end of a cross exchange input stream.
6420
+ */
6421
+ interface AsyncInputStreamEndEvent {
6422
+ /**
6423
+ * Optional metadata that can be used for any data having to do with the completion of the event stream.
6424
+ */
6425
+ metaData?: MetaData;
6426
+ /**
6427
+ * Optional value that provides the contentPartSequence value in the last content part chunk sent.
6428
+ */
6429
+ lastChunkContentPartSequence?: number;
6430
+ }
6431
+ /**
6432
+ * Async input stream chunk event.
6433
+ */
6434
+ interface AsyncInputStreamChunkEvent {
6435
+ data: string;
6436
+ }
6437
+ /**
6438
+ * Signals the start of a tool call.
6439
+ */
6440
+ interface ToolCallStartEvent {
6441
+ /**
6442
+ * Identifies the tool that is to be called.
6443
+ */
6444
+ toolName: string;
6445
+ /**
6446
+ * The time the tool call was made.
6447
+ */
6448
+ timestamp?: string;
6449
+ /**
6450
+ * Optional input value provided to the tool when executed.
6451
+ */
6452
+ input?: ToolCallInputValue;
6453
+ /**
6454
+ * Optional metadata pertaining to the tool call.
6455
+ */
6456
+ metaData?: MetaData;
6457
+ }
6458
+ /**
6459
+ * Signals the end of a tool call.
6460
+ */
6461
+ interface ToolCallEndEvent {
6462
+ /**
6463
+ * The time the result was generated.
6464
+ */
6465
+ timestamp?: string;
6466
+ /**
6467
+ * Optional output value returned by the tool's execution.
6468
+ */
6469
+ output?: ToolCallOutputValue;
6470
+ /**
6471
+ * Indicates if the tool call resulted in an error.
6472
+ */
6473
+ isError?: boolean;
6474
+ /**
6475
+ * Indicates if the tool call was canceled before the result was generated.
6476
+ */
6477
+ cancelled?: boolean;
6478
+ /**
6479
+ * Metadata pertaining to the tool call's execution or result.
6480
+ */
6481
+ metaData?: MetaData;
6482
+ }
6483
+ /**
6484
+ * Allows additional events to be sent in the context of the enclosing event stream.
6485
+ */
6486
+ interface MetaEvent {
6487
+ [key: string]: unknown;
6488
+ }
6489
+ /**
6490
+ * Indicates the update of the conversation label.
6491
+ */
6492
+ interface LabelUpdatedEvent {
6493
+ /**
6494
+ * The new label for the conversation.
6495
+ */
6496
+ label: string;
6497
+ /**
6498
+ * Whether the label was autogenerated by the system, or manually updated through the API.
6499
+ */
6500
+ autogenerated: boolean;
6501
+ }
6502
+ /**
6503
+ * Encapsulates the data related to a tool call event.
6504
+ */
6505
+ interface ToolCallEvent {
6506
+ /**
6507
+ * Identifies the tool call.
6508
+ */
6509
+ toolCallId: string;
6510
+ /**
6511
+ * Signals the start of a tool call.
6512
+ */
6513
+ startToolCall?: ToolCallStartEvent;
6514
+ /**
6515
+ * Signals the end of a tool call.
6516
+ */
6517
+ endToolCall?: ToolCallEndEvent;
6518
+ /**
6519
+ * Allows additional events to be sent in the context of the enclosing event stream.
6520
+ */
6521
+ metaEvent?: MetaEvent;
6522
+ /**
6523
+ * Sent by the service to indicate an error condition impacting a tool call.
6524
+ */
6525
+ toolCallError?: ErrorEvent;
6526
+ }
6527
+ /**
6528
+ * Schema for tool call confirmation interrupt value.
6529
+ */
6530
+ interface ToolCallConfirmationValue {
6531
+ /**
6532
+ * The ID of the tool call being confirmed.
6533
+ */
6534
+ toolCallId: string;
6535
+ /**
6536
+ * The name of the tool to be called.
6537
+ */
6538
+ toolName: string;
6539
+ /**
6540
+ * The input schema for the tool call.
6541
+ */
6542
+ inputSchema: JSONValue;
6543
+ /**
6544
+ * The input value for the tool call.
6545
+ */
6546
+ inputValue?: JSONValue;
6547
+ }
6548
+ /**
6549
+ * Schema for tool call confirmation end value.
6550
+ */
6551
+ interface ToolCallConfirmationEndValue {
6552
+ /**
6553
+ * Whether the tool call was approved.
6554
+ */
6555
+ approved: boolean;
6556
+ /**
6557
+ * Modified input parameters for the tool call.
6558
+ */
6559
+ input?: JSONValue;
6560
+ }
6561
+ /**
6562
+ * Known interrupt start event for tool call confirmation.
6563
+ */
6564
+ interface ToolCallConfirmationInterruptStartEvent {
6565
+ /**
6566
+ * Tool call confirmation interrupt type.
6567
+ */
6568
+ type: typeof InterruptType.ToolCallConfirmation;
6569
+ /**
6570
+ * The tool call confirmation data.
6571
+ */
6572
+ value: ToolCallConfirmationValue;
6573
+ }
6574
+ /**
6575
+ * Generic interrupt start event for custom interrupts.
6576
+ */
6577
+ interface GenericInterruptStartEvent {
6578
+ /**
6579
+ * The type of the interrupt.
6580
+ */
6581
+ type: string;
6582
+ /**
6583
+ * The value of the interrupt.
6584
+ */
6585
+ value: unknown;
6586
+ }
6587
+ /**
6588
+ * Signals the start of an interrupt - a pause point where the agent needs external input.
6589
+ */
6590
+ type InterruptStartEvent = ToolCallConfirmationInterruptStartEvent | GenericInterruptStartEvent;
6591
+ /**
6592
+ * Signals the interrupt end event with the provided value.
6593
+ */
6594
+ type InterruptEndEvent = Record<string, unknown>;
6595
+ /**
6596
+ * Encapsulates interrupt-related events within a message.
6597
+ */
6598
+ interface InterruptEvent {
6599
+ /**
6600
+ * Identifies the interrupt.
6601
+ */
6602
+ interruptId: string;
6603
+ /**
6604
+ * Signals the start of an interrupt.
6605
+ */
6606
+ startInterrupt?: InterruptStartEvent;
6607
+ /**
6608
+ * Signals the end of an interrupt.
6609
+ */
6610
+ endInterrupt?: InterruptEndEvent;
6611
+ }
6612
+ /**
6613
+ * Encapsulates sub-events related to message content parts.
6614
+ */
6615
+ interface ContentPartEvent {
6616
+ /**
6617
+ * Identifies the content part.
6618
+ */
6619
+ contentPartId: string;
6620
+ /**
6621
+ * Optional value that signals the start of message content.
6622
+ */
6623
+ startContentPart?: ContentPartStartEvent;
6624
+ /**
6625
+ * Optional value that signals the end of message content.
6626
+ */
6627
+ endContentPart?: ContentPartEndEvent;
6628
+ /**
6629
+ * Optional content part chunk sub-event.
6630
+ */
6631
+ chunk?: ContentPartChunkEvent;
6632
+ /**
6633
+ * Allows additional events to be sent in the context of the enclosing event stream.
6634
+ */
6635
+ metaEvent?: MetaEvent;
6636
+ /**
6637
+ * Sent by the service to indicate an error condition impacting a content part.
6638
+ */
6639
+ contentPartError?: ErrorEvent;
6640
+ }
6641
+ /**
6642
+ * Encapsulates sub-events related to a message within an exchange.
6643
+ */
6644
+ interface MessageEvent {
6645
+ /**
6646
+ * Identifies a message.
6647
+ */
6648
+ messageId: string;
6649
+ /**
6650
+ * Optional value that signals that start of a message.
6651
+ */
6652
+ startMessage?: MessageStartEvent;
6653
+ /**
6654
+ * Optional value that signals the end of a message.
6655
+ */
6656
+ endMessage?: MessageEndEvent;
6657
+ /**
6658
+ * Optional content part sub-event.
6659
+ */
6660
+ contentPart?: ContentPartEvent;
6661
+ /**
6662
+ * Optional tool call sub-event.
6663
+ */
6664
+ toolCall?: ToolCallEvent;
6665
+ /**
6666
+ * Optional interrupt sub-event for human-in-the-loop patterns.
6667
+ */
6668
+ interrupt?: InterruptEvent;
6669
+ /**
6670
+ * Allows additional events to be sent in the context of the enclosing event stream.
6671
+ */
6672
+ metaEvent?: MetaEvent;
6673
+ /**
6674
+ * Sent by the service to indicate an error condition impacting a message.
6675
+ */
6676
+ messageError?: ErrorEvent;
6677
+ }
6678
+ /**
6679
+ * Encapsulates events related to a cross exchange input stream for the conversation.
6680
+ */
6681
+ interface AsyncInputStreamEvent {
6682
+ /**
6683
+ * Identifies the input stream.
6684
+ */
6685
+ streamId: string;
6686
+ /**
6687
+ * Optional value that signals the start of an input stream.
6688
+ */
6689
+ startAsyncInputStream?: AsyncInputStreamStartEvent;
6690
+ /**
6691
+ * Optional value that signals the end of an input stream.
6692
+ */
6693
+ endAsyncInputStream?: AsyncInputStreamEndEvent;
6694
+ /**
6695
+ * Optional input stream chunk sub-event.
6696
+ */
6697
+ chunk?: AsyncInputStreamChunkEvent;
6698
+ /**
6699
+ * Allows additional events to be sent in the context of the enclosing event stream.
6700
+ */
6701
+ metaEvent?: MetaEvent;
6702
+ /**
6703
+ * Sent by the service to indicate an error condition impacting an async input stream.
6704
+ */
6705
+ asyncInputStreamError?: ErrorEvent;
6706
+ }
6707
+ /**
6708
+ * An event that applies to a single exchange of messages within a conversation.
6709
+ */
6710
+ interface ExchangeEvent {
6711
+ /**
6712
+ * Identifies the exchange.
6713
+ */
6714
+ exchangeId: string;
6715
+ /**
6716
+ * Optional value that signals the start of an exchange.
6717
+ */
6718
+ startExchange?: ExchangeStartEvent;
6719
+ /**
6720
+ * Optional value that signals the end of an exchange.
6721
+ */
6722
+ endExchange?: ExchangeEndEvent;
6723
+ /**
6724
+ * Optional message sub-events related to the exchange.
6725
+ */
6726
+ message?: MessageEvent;
6727
+ /**
6728
+ * Allows additional events to be sent in the context of the enclosing event stream.
6729
+ */
6730
+ metaEvent?: MetaEvent;
6731
+ /**
6732
+ * Sent by the service to indicate an error condition impacting an exchange.
6733
+ */
6734
+ exchangeError?: ErrorEvent;
6735
+ }
6736
+ /**
6737
+ * The ConversationEvent type represents an event in a conversation with an LLM.
6738
+ */
6739
+ interface ConversationEvent {
6740
+ /**
6741
+ * A globally unique identifier for conversation to which the other sub-event and data properties apply.
6742
+ */
6743
+ conversationId: string;
6744
+ /**
6745
+ * Signals the start of session for a conversation.
6746
+ */
6747
+ startSession?: SessionStartEvent;
6748
+ /**
6749
+ * Sent in response to a SessionStartEvent to signal the acceptance of the session.
6750
+ */
6751
+ sessionStarted?: SessionStartedEvent;
6752
+ /**
6753
+ * Sent by the service when the client needs to end the current session.
6754
+ */
6755
+ sessionEnding?: SessionEndingEvent;
6756
+ /**
6757
+ * Signals the end of a session for a conversation.
6758
+ */
6759
+ endSession?: SessionEndEvent;
6760
+ /**
6761
+ * Optional exchange sub-event.
6762
+ */
6763
+ exchange?: ExchangeEvent;
6764
+ /**
6765
+ * Optional input stream sub-events.
6766
+ */
6767
+ asyncInputStream?: AsyncInputStreamEvent;
6768
+ /**
6769
+ * Optional async tool call sub-event.
6770
+ */
6771
+ asyncToolCall?: ToolCallEvent;
6772
+ /**
6773
+ * Indicates that the conversation's label has been updated.
6774
+ */
6775
+ labelUpdated?: LabelUpdatedEvent;
6776
+ /**
6777
+ * Allows additional events to be sent in the context of the enclosing event stream.
6778
+ */
6779
+ metaEvent?: MetaEvent;
6780
+ /**
6781
+ * Sent by the service to indicate an error condition impacting a conversation.
6782
+ */
6783
+ conversationError?: ErrorEvent;
6784
+ }
6785
+
6786
+ /**
6787
+ * Content Part Stream Types
6788
+ *
6789
+ * Defines the public API for interacting with streaming content parts
6790
+ * within a message. Content parts represent text, audio, images, etc.
6791
+ */
6792
+
6793
+ /**
6794
+ * Error encountered during citation processing
6795
+ */
6796
+ type CitationError = {
6797
+ citationId: string;
6798
+ errorType: CitationErrorType;
6799
+ };
6800
+ /**
6801
+ * Types of citation processing errors
6802
+ */
6803
+ declare enum CitationErrorType {
6804
+ CitationNotEnded = "CitationNotEnded",
6805
+ CitationNotStarted = "CitationNotStarted"
6806
+ }
6807
+ /**
6808
+ * Aggregated data for a completed content part
6809
+ *
6810
+ * Contains the full buffered text, citations, and metadata
6811
+ * available after a content part stream has ended.
6812
+ */
6813
+ type CompletedContentPart = ContentPartStartEvent & ContentPartEndEvent & {
6814
+ contentPartId: string;
6815
+ data: string;
6816
+ citations: CitationOptions[];
6817
+ citationErrors: CitationError[];
6818
+ };
6819
+ /**
6820
+ * Model for content part event helpers.
6821
+ *
6822
+ * A content part is a single piece of content within a message — text,
6823
+ * audio, an image, or a transcript. Use the type-check properties
6824
+ * (`isText`, `isMarkdown`, `isHtml`, `isAudio`, `isImage`, `isTranscript`)
6825
+ * to determine the content type and handle it accordingly.
6826
+ *
6827
+ * @example Streaming markdown content
6828
+ * ```typescript
6829
+ * message.onContentPartStart((part) => {
6830
+ * if (part.isMarkdown) {
6831
+ * part.onChunk((chunk) => {
6832
+ * process.stdout.write(chunk.data ?? '');
6833
+ * });
6834
+ * }
6835
+ * });
6836
+ * ```
6837
+ *
6838
+ * @example Handling different content types
6839
+ * ```typescript
6840
+ * message.onContentPartStart((part) => {
6841
+ * if (part.isText) {
6842
+ * part.onChunk((chunk) => showPlainText(chunk.data ?? ''));
6843
+ * } else if (part.isMarkdown) {
6844
+ * part.onChunk((chunk) => renderMarkdown(chunk.data ?? ''));
6845
+ * } else if (part.isHtml) {
6846
+ * part.onChunk((chunk) => renderHtml(chunk.data ?? ''));
6847
+ * } else if (part.isAudio) {
6848
+ * part.onChunk((chunk) => audioPlayer.enqueue(chunk.data ?? ''));
6849
+ * } else if (part.isImage) {
6850
+ * part.onChunk((chunk) => imageBuffer.append(chunk.data ?? ''));
6851
+ * } else if (part.isTranscript) {
6852
+ * part.onChunk((chunk) => showTranscript(chunk.data ?? ''));
6853
+ * }
6854
+ * });
6855
+ * ```
6856
+ *
6857
+ * @example Getting complete content with citations (buffered)
6858
+ * ```typescript
6859
+ * message.onContentPartStart((part) => {
6860
+ * part.onCompleted((completed) => {
6861
+ * console.log(`Full text: ${completed.data}`);
6862
+ *
6863
+ * // Access citations — each has offset, length, and sources
6864
+ * for (const citation of completed.citations) {
6865
+ * const citedText = completed.data.substring(
6866
+ * citation.offset,
6867
+ * citation.offset + citation.length
6868
+ * );
6869
+ * console.log(`"${citedText}" cited from:`, citation.sources);
6870
+ * }
6871
+ * });
6872
+ * });
6873
+ * ```
6874
+ *
6875
+ * @example Using the content part completed handler at the message level
6876
+ * ```typescript
6877
+ * message.onContentPartCompleted((completed) => {
6878
+ * console.log(`[${completed.mimeType}] ${completed.data}`);
6879
+ * });
6880
+ * ```
6881
+ */
6882
+ interface ContentPartStream {
6883
+ /** Unique identifier for this content part */
6884
+ readonly contentPartId: string;
6885
+ /** The MIME type of this content part, or undefined if start event not yet received */
6886
+ readonly mimeType: string | undefined;
6887
+ /** Whether this content part is plain text. Matches `text/plain`. */
6888
+ readonly isText: boolean;
6889
+ /** Whether this content part is markdown. Matches `text/markdown`. */
6890
+ readonly isMarkdown: boolean;
6891
+ /** Whether this content part is HTML. Matches `text/html`. */
6892
+ readonly isHtml: boolean;
6893
+ /** Whether this content part is audio content */
6894
+ readonly isAudio: boolean;
6895
+ /** Whether this content part is an image */
6896
+ readonly isImage: boolean;
6897
+ /** Whether this content part is a transcript (from speech-to-text) */
6898
+ readonly isTranscript: boolean;
6899
+ /**
6900
+ * The start event, or undefined if not yet received
6901
+ * @internal
6902
+ */
6903
+ readonly startEventMaybe: ContentPartStartEvent | undefined;
6904
+ /**
6905
+ * The start event (throws if not yet received)
6906
+ * @internal
6907
+ */
6908
+ readonly startEvent: MakeRequired<ContentPartStartEvent, 'timestamp'>;
6909
+ /** Whether this content part has ended */
6910
+ readonly ended: boolean;
6911
+ /**
6912
+ * Registers a handler for error start events
6913
+ *
6914
+ * @param cb - Callback receiving the error event
6915
+ * @returns Cleanup function to remove the handler
6916
+ *
6917
+ * @example Content part error handling
6918
+ * ```typescript
6919
+ * part.onErrorStart((error) => {
6920
+ * console.error(`Content part error: ${error.message}`);
6921
+ * });
6922
+ * ```
6923
+ */
6924
+ onErrorStart(cb: (error: {
6925
+ errorId: string;
6926
+ } & ErrorStartEvent) => void): () => void;
6927
+ /**
6928
+ * Registers a handler for error end events
6929
+ * @param cb - Callback receiving the error end event
6930
+ * @returns Cleanup function to remove the handler
6931
+ */
6932
+ onErrorEnd(cb: (error: {
6933
+ errorId: string;
6934
+ } & ErrorEndEvent) => void): () => void;
6935
+ /**
6936
+ * Registers a handler for content part chunks
6937
+ *
6938
+ * Chunks are the fundamental unit of streaming data. Each chunk
6939
+ * contains a piece of the content (text, audio data, etc.).
6940
+ *
6941
+ * @param cb - Callback receiving each chunk
6942
+ * @returns Cleanup function to remove the handler
6943
+ *
6944
+ * @example Streaming text output
6945
+ * ```typescript
6946
+ * part.onChunk((chunk) => {
6947
+ * process.stdout.write(chunk.data ?? '');
6948
+ * });
6949
+ * ```
6950
+ */
6951
+ onChunk(cb: (chunk: ContentPartChunkEvent) => void): () => void;
6952
+ /**
6953
+ * Registers a handler for content part end events
6954
+ *
6955
+ * @param cb - Callback receiving the end event
6956
+ * @returns Cleanup function to remove the handler
6957
+ *
6958
+ * @example Tracking content part lifecycle
6959
+ * ```typescript
6960
+ * part.onContentPartEnd((endEvent) => {
6961
+ * console.log('Content part finished');
6962
+ * });
6963
+ * ```
6964
+ */
6965
+ onContentPartEnd(cb: (endContentPart: ContentPartEndEvent) => void): () => void;
6966
+ /**
6967
+ * Registers a handler called when this content part finishes
6968
+ *
6969
+ * The handler receives the aggregated content part data including
6970
+ * all buffered text, citations, and any citation errors.
6971
+ *
6972
+ * @param cb - Callback receiving the completed content part data
6973
+ *
6974
+ * @example Getting buffered content with citation data
6975
+ * ```typescript
6976
+ * part.onCompleted((completed) => {
6977
+ * console.log(`Content type: ${completed.mimeType}`);
6978
+ * console.log(`Full text: ${completed.data}`);
6979
+ *
6980
+ * // Citations provide offset/length into the text and source references
6981
+ * for (const citation of completed.citations) {
6982
+ * const citedText = completed.data.substring(
6983
+ * citation.offset,
6984
+ * citation.offset + citation.length
6985
+ * );
6986
+ * console.log(`"${citedText}" — sources:`, citation.sources);
6987
+ * }
6988
+ *
6989
+ * // Citation errors indicate malformed citation ranges
6990
+ * if (completed.citationErrors.length > 0) {
6991
+ * console.warn('Citation errors:', completed.citationErrors);
6992
+ * }
6993
+ * });
6994
+ * ```
6995
+ */
6996
+ onCompleted(cb: (completedContentPart: CompletedContentPart) => void): void;
6997
+ /**
6998
+ * Sends a content part chunk
6999
+ *
7000
+ * @param chunk - Chunk data to send
7001
+ *
7002
+ * @example Sending text chunks
7003
+ * ```typescript
7004
+ * part.sendChunk({ data: 'Hello ' });
7005
+ * part.sendChunk({ data: 'world!' });
7006
+ * ```
7007
+ */
7008
+ sendChunk(chunk: ContentPartChunkEvent): void;
7009
+ /**
7010
+ * Ends the content part stream
7011
+ *
7012
+ * @param endContentPart - Optional end event data
7013
+ *
7014
+ * @example Ending a content part
7015
+ * ```typescript
7016
+ * part.sendContentPartEnd();
7017
+ * ```
7018
+ */
7019
+ sendContentPartEnd(endContentPart?: ContentPartEndEvent): void;
7020
+ /**
7021
+ * Sends an error start event for this content part
7022
+ * @param args - Error details including optional error ID and message
7023
+ * @internal
7024
+ */
7025
+ sendErrorStart(args: {
7026
+ errorId?: string;
7027
+ } & ErrorStartEvent): void;
7028
+ /**
7029
+ * Sends an error end event for this content part
7030
+ * @param args - Error end details including the error ID
7031
+ * @internal
7032
+ */
7033
+ sendErrorEnd(args: {
7034
+ errorId: string;
7035
+ } & ErrorEndEvent): void;
7036
+ /**
7037
+ * Sends a metadata event for this content part
7038
+ * @param metaEvent - Metadata to send
7039
+ * @internal
7040
+ */
7041
+ sendMetaEvent(metaEvent: MetaEvent): void;
7042
+ /**
7043
+ * Sends a chunk that starts a citation range
7044
+ *
7045
+ * Marks the beginning of a cited passage. All subsequent chunks
7046
+ * until `sendChunkWithCitationEnd` are considered part of this citation.
7047
+ *
7048
+ * @param chunk - Chunk data with citation ID
7049
+ * @internal
7050
+ */
7051
+ sendChunkWithCitationStart(chunk: Omit<ContentPartChunkEvent, 'citation'> & {
7052
+ citationId: string;
7053
+ }): void;
7054
+ /**
7055
+ * Sends a chunk that ends a citation range
7056
+ *
7057
+ * Marks the end of a cited passage and provides the citation sources.
7058
+ *
7059
+ * @param chunk - Chunk data with citation ID and sources
7060
+ * @internal
7061
+ */
7062
+ sendChunkWithCitationEnd(chunk: Omit<ContentPartChunkEvent, 'citation'> & {
7063
+ citationId: string;
7064
+ sources: CitationSource[];
7065
+ }): void;
7066
+ /**
7067
+ * Sends a chunk that is a complete citation (start and end in one)
7068
+ *
7069
+ * Use this for inline citations where the entire cited text is in a single chunk.
7070
+ *
7071
+ * @param chunk - Chunk data with citation ID and sources
7072
+ * @internal
7073
+ */
7074
+ sendChunkWithCitation(chunk: Omit<ContentPartChunkEvent, 'citation'> & {
7075
+ citationId: string;
7076
+ sources: CitationSource[];
7077
+ }): void;
7078
+ /**
7079
+ * Emits a raw content part event
7080
+ * @param contentPartEvent - The event to emit (contentPartId is added automatically)
7081
+ * @internal
7082
+ */
7083
+ emit(contentPartEvent: Omit<ContentPartEvent, 'contentPartId'>): void;
7084
+ /**
7085
+ * Returns a string representation of this content part
7086
+ * @internal
7087
+ */
7088
+ toString(): string;
7089
+ }
7090
+
7091
+ /**
7092
+ * Consumer-facing interface for ToolCallEventHelper
7093
+ *
7094
+ * Defines the public API for interacting with tool call events
7095
+ * within a message. Tool calls represent external tool invocations
7096
+ * made by the assistant during a conversation.
7097
+ */
7098
+
7099
+ /**
7100
+ * Aggregated data for a completed tool call
7101
+ *
7102
+ * Contains the merged start and end event data
7103
+ * available after a tool call has ended.
7104
+ */
7105
+ type CompletedToolCall = ToolCallStartEvent & ToolCallEndEvent & {
7106
+ toolCallId: string;
7107
+ };
7108
+ /**
7109
+ * Consumer-facing model for tool call event helpers.
7110
+ *
7111
+ * A tool call represents the agent invoking an external tool (API call,
7112
+ * database query, etc.) during a conversation. Tool calls live within
7113
+ * a message and have a start event (with tool name and input) and an
7114
+ * end event (with the output/result).
7115
+ *
7116
+ * @example Listening for tool call results
7117
+ * ```typescript
7118
+ * message.onToolCallStart((toolCall) => {
7119
+ * console.log(`Tool: ${toolCall.startEvent.toolName}`);
7120
+ * toolCall.onToolCallEnd((endEvent) => {
7121
+ * console.log('Tool call completed:', endEvent.output);
7122
+ * });
7123
+ * });
7124
+ * ```
7125
+ *
7126
+ * @example Parsing tool call input and output
7127
+ * ```typescript
7128
+ * message.onToolCallStart((toolCall) => {
7129
+ * const { toolName, input } = toolCall.startEvent;
7130
+ * const parsedInput = JSON.parse(input ?? '{}');
7131
+ * console.log(`Calling ${toolName} with:`, parsedInput);
7132
+ *
7133
+ * toolCall.onToolCallEnd((endEvent) => {
7134
+ * const result = JSON.parse(endEvent.output ?? '{}');
7135
+ * console.log(`${toolName} returned:`, result);
7136
+ * });
7137
+ * });
7138
+ * ```
7139
+ *
7140
+ * @example Responding to a tool call (agent-side)
7141
+ * ```typescript
7142
+ * message.onToolCallStart(async (toolCall) => {
7143
+ * const { toolName, input } = toolCall.startEvent;
7144
+ *
7145
+ * // Execute the tool and return the result
7146
+ * const result = await executeTool(toolName, input);
7147
+ * toolCall.sendToolCallEnd({
7148
+ * output: JSON.stringify(result)
7149
+ * });
7150
+ * });
7151
+ * ```
7152
+ */
7153
+ interface ToolCallStream {
7154
+ /** Unique identifier for this tool call */
7155
+ readonly toolCallId: string;
7156
+ /**
7157
+ * The start event, or undefined if not yet received
7158
+ * @internal
7159
+ */
7160
+ readonly startEventMaybe: ToolCallStartEvent | undefined;
7161
+ /**
7162
+ * The start event (throws if not yet received)
7163
+ * @internal
7164
+ */
7165
+ readonly startEvent: MakeRequired<ToolCallStartEvent, 'timestamp'>;
7166
+ /** Whether this tool call has ended */
7167
+ readonly ended: boolean;
7168
+ /**
7169
+ * Registers a handler for error start events
7170
+ *
7171
+ * @param cb - Callback receiving the error event
7172
+ * @returns Cleanup function to remove the handler
7173
+ *
7174
+ * @example Tool call error handling
7175
+ * ```typescript
7176
+ * toolCall.onErrorStart((error) => {
7177
+ * console.error(`Tool call error: ${error.message}`);
7178
+ * });
7179
+ * ```
7180
+ */
7181
+ onErrorStart(cb: (error: {
7182
+ errorId: string;
7183
+ } & ErrorStartEvent) => void): () => void;
7184
+ /**
7185
+ * Registers a handler for error end events
7186
+ * @param cb - Callback receiving the error end event
7187
+ * @returns Cleanup function to remove the handler
7188
+ */
7189
+ onErrorEnd(cb: (error: {
7190
+ errorId: string;
7191
+ } & ErrorEndEvent) => void): () => void;
7192
+ /**
7193
+ * Registers a handler for tool call end events
7194
+ *
7195
+ * @param cb - Callback receiving the end event
7196
+ * @returns Cleanup function to remove the handler
7197
+ *
7198
+ * @example Handling tool call completion
7199
+ * ```typescript
7200
+ * toolCall.onToolCallEnd((endEvent) => {
7201
+ * console.log('Output:', endEvent.output);
7202
+ * });
7203
+ * ```
7204
+ */
7205
+ onToolCallEnd(cb: (endToolCall: ToolCallEndEvent) => void): () => void;
7206
+ /**
7207
+ * Ends the tool call
7208
+ *
7209
+ * @param endToolCall - Optional end event data
7210
+ *
7211
+ * @example Completing a tool call with output
7212
+ * ```typescript
7213
+ * toolCall.sendToolCallEnd({
7214
+ * output: JSON.stringify({ temperature: 18, condition: 'cloudy' })
7215
+ * });
7216
+ * ```
7217
+ */
7218
+ sendToolCallEnd(endToolCall?: ToolCallEndEvent): void;
7219
+ /**
7220
+ * Sends an error start event for this tool call
7221
+ * @param args - Error details including optional error ID and message
7222
+ * @internal
7223
+ */
7224
+ sendErrorStart(args: {
7225
+ errorId?: string;
7226
+ } & ErrorStartEvent): void;
7227
+ /**
7228
+ * Sends an error end event for this tool call
7229
+ * @param args - Error end details including the error ID
7230
+ * @internal
7231
+ */
7232
+ sendErrorEnd(args: {
7233
+ errorId: string;
7234
+ } & ErrorEndEvent): void;
7235
+ /**
7236
+ * Sends a metadata event for this tool call
7237
+ * @param metaEvent - Metadata to send
7238
+ * @internal
7239
+ */
7240
+ sendMetaEvent(metaEvent: MetaEvent): void;
7241
+ /**
7242
+ * Emits a raw tool call event
7243
+ * @param toolCallEvent - The event to emit (toolCallId is added automatically)
7244
+ * @internal
7245
+ */
7246
+ emit(toolCallEvent: Omit<ToolCallEvent, 'toolCallId'>): void;
7247
+ /**
7248
+ * Returns a string representation of this tool call
7249
+ * @internal
7250
+ */
7251
+ toString(): string;
7252
+ }
7253
+ /**
7254
+ * Consumer-facing model for async tool call event helpers.
7255
+ *
7256
+ * Async tool calls operate at the session level (not within a single message)
7257
+ * and can span across multiple exchanges. They are used for long-running
7258
+ * tool invocations that need to persist beyond a single request-response cycle.
7259
+ *
7260
+ * Unlike regular {@link ToolCallStream} which live inside a message,
7261
+ * async tool calls are managed directly on the {@link SessionStream}.
7262
+ *
7263
+ * @example Listening for async tool call completion
7264
+ * ```typescript
7265
+ * session.onAsyncToolCallStart((toolCall) => {
7266
+ * console.log(`Async tool started: ${toolCall.startEvent.toolName}`);
7267
+ * toolCall.onToolCallEnd((endEvent) => {
7268
+ * console.log('Async tool completed:', endEvent.output);
7269
+ * });
7270
+ * });
7271
+ * ```
7272
+ *
7273
+ * @example Starting and completing an async tool call
7274
+ * ```typescript
7275
+ * // Start a long-running analysis
7276
+ * const toolCall = session.startAsyncToolCall({
7277
+ * toolName: 'document-analysis',
7278
+ * input: JSON.stringify({ documentId: 'doc-123' })
7279
+ * });
7280
+ *
7281
+ * // ... perform the analysis across multiple exchanges ...
7282
+ *
7283
+ * // Complete when done
7284
+ * toolCall.sendToolCallEnd({
7285
+ * output: JSON.stringify({ summary: 'Analysis complete', pages: 42 })
7286
+ * });
7287
+ * ```
7288
+ *
7289
+ * @example Handling errors on async tool calls
7290
+ * ```typescript
7291
+ * session.onAsyncToolCallStart((toolCall) => {
7292
+ * toolCall.onErrorStart((error) => {
7293
+ * console.error(`Async tool error: ${error.message}`);
7294
+ * });
7295
+ * });
7296
+ * ```
7297
+ */
7298
+ interface AsyncToolCallStream {
7299
+ /** Unique identifier for this async tool call */
7300
+ readonly toolCallId: string;
7301
+ /**
7302
+ * The start event, or undefined if not yet received
7303
+ * @internal
7304
+ */
7305
+ readonly startEventMaybe: ToolCallStartEvent | undefined;
7306
+ /**
7307
+ * The start event (throws if not yet received)
7308
+ * @internal
7309
+ */
7310
+ readonly startEvent: MakeRequired<ToolCallStartEvent, 'timestamp'>;
7311
+ /** Whether this async tool call has ended */
7312
+ readonly ended: boolean;
7313
+ /**
7314
+ * Registers a handler for error start events
7315
+ * @param cb - Callback receiving the error event
7316
+ * @returns Cleanup function to remove the handler
7317
+ */
7318
+ onErrorStart(cb: (error: {
7319
+ errorId: string;
7320
+ } & ErrorStartEvent) => void): () => void;
7321
+ /**
7322
+ * Registers a handler for error end events
7323
+ * @param cb - Callback receiving the error end event
7324
+ * @returns Cleanup function to remove the handler
7325
+ */
7326
+ onErrorEnd(cb: (error: {
7327
+ errorId: string;
7328
+ } & ErrorEndEvent) => void): () => void;
7329
+ /**
7330
+ * Registers a handler for tool call end events
7331
+ * @param cb - Callback receiving the end event
7332
+ * @returns Cleanup function to remove the handler
7333
+ */
7334
+ onToolCallEnd(cb: (endToolCall: ToolCallEndEvent) => void): () => void;
7335
+ /**
7336
+ * Ends the async tool call
7337
+ * @param endToolCall - Optional end event data including output
7338
+ */
7339
+ sendToolCallEnd(endToolCall?: ToolCallEndEvent): void;
7340
+ /**
7341
+ * Sends an error start event for this async tool call
7342
+ * @param args - Error details including optional error ID and message
7343
+ * @internal
7344
+ */
7345
+ sendErrorStart(args: {
7346
+ errorId?: string;
7347
+ } & ErrorStartEvent): void;
7348
+ /**
7349
+ * Sends an error end event for this async tool call
7350
+ * @param args - Error end details including the error ID
7351
+ * @internal
7352
+ */
7353
+ sendErrorEnd(args: {
7354
+ errorId: string;
7355
+ } & ErrorEndEvent): void;
7356
+ /**
7357
+ * Sends a metadata event for this async tool call
7358
+ * @param metaEvent - Metadata to send
7359
+ * @internal
7360
+ */
7361
+ sendMetaEvent(metaEvent: MetaEvent): void;
7362
+ /**
7363
+ * Emits a raw tool call event
7364
+ * @param toolCallEvent - The event to emit (toolCallId is added automatically)
7365
+ * @internal
7366
+ */
7367
+ emit(toolCallEvent: Omit<ToolCallEvent, 'toolCallId'>): void;
7368
+ /**
7369
+ * Returns a string representation of this async tool call
7370
+ * @internal
7371
+ */
7372
+ toString(): string;
7373
+ }
7374
+
7375
+ /**
7376
+ * Consumer-facing interface for AsyncInputStreamEventHelper
7377
+ *
7378
+ * Defines the public API for interacting with async input streams
7379
+ * at the session level. Async input streams are used for streaming
7380
+ * audio or other media data to the agent.
7381
+ */
7382
+
7383
+ /**
7384
+ * Consumer-facing model for async input stream event helpers.
7385
+ *
7386
+ * Async input streams operate at the session level and are used for
7387
+ * streaming audio or other media data to the agent in real-time.
7388
+ * They persist across exchanges, making them ideal for continuous
7389
+ * audio input from a microphone.
7390
+ *
7391
+ * Unlike content parts (which carry agent output), async input streams
7392
+ * carry user input to the agent via the {@link SessionStream}.
7393
+ *
7394
+ * @example Streaming microphone audio
7395
+ * ```typescript
7396
+ * const stream = session.startAsyncInputStream({
7397
+ * mimeType: 'audio/pcm;rate=24000'
7398
+ * });
7399
+ *
7400
+ * // Stream microphone PCM data
7401
+ * microphone.on('data', (pcmData: string) => {
7402
+ * stream.sendChunk({ data: pcmData });
7403
+ * });
7404
+ *
7405
+ * // End when user stops speaking
7406
+ * microphone.on('end', () => {
7407
+ * stream.sendAsyncInputStreamEnd();
7408
+ * });
7409
+ * ```
7410
+ *
7411
+ * @example Receiving audio input (agent-side)
7412
+ * ```typescript
7413
+ * session.onInputStreamStart((inputStream) => {
7414
+ * console.log(`Receiving audio: ${inputStream.startEvent.mimeType}`);
7415
+ *
7416
+ * inputStream.onChunk((chunk) => {
7417
+ * // Process incoming audio data
7418
+ * audioProcessor.process(chunk.data);
7419
+ * });
7420
+ *
7421
+ * inputStream.onAsyncInputStreamEnd(() => {
7422
+ * console.log('Audio stream ended');
7423
+ * });
7424
+ * });
7425
+ * ```
7426
+ *
7427
+ * @example Handling stream errors
7428
+ * ```typescript
7429
+ * const stream = session.startAsyncInputStream({
7430
+ * mimeType: 'audio/pcm;rate=24000'
7431
+ * });
7432
+ *
7433
+ * stream.onErrorStart((error) => {
7434
+ * console.error(`Stream error: ${error.message}`);
7435
+ * // Clean up microphone resources
7436
+ * microphone.stop();
7437
+ * });
7438
+ * ```
7439
+ */
7440
+ interface AsyncInputStream {
7441
+ /** Unique identifier for this input stream */
7442
+ readonly streamId: string;
7443
+ /**
7444
+ * The start event, or undefined if not yet received
7445
+ * @internal
7446
+ */
7447
+ readonly startEventMaybe: AsyncInputStreamStartEvent | undefined;
7448
+ /**
7449
+ * The start event (throws if not yet received)
7450
+ * @internal
7451
+ */
7452
+ readonly startEvent: AsyncInputStreamStartEvent;
7453
+ /** Whether this input stream has ended */
7454
+ readonly ended: boolean;
7455
+ /**
7456
+ * Registers a handler for error start events
7457
+ * @param cb - Callback receiving the error event
7458
+ * @returns Cleanup function to remove the handler
7459
+ */
7460
+ onErrorStart(cb: (error: {
7461
+ errorId: string;
7462
+ } & ErrorStartEvent) => void): () => void;
7463
+ /**
7464
+ * Registers a handler for error end events
7465
+ * @param cb - Callback receiving the error end event
7466
+ * @returns Cleanup function to remove the handler
7467
+ */
7468
+ onErrorEnd(cb: (error: {
7469
+ errorId: string;
7470
+ } & ErrorEndEvent) => void): () => void;
7471
+ /**
7472
+ * Sends a stream chunk
7473
+ * @param chunk - Chunk data to send (e.g., audio data)
7474
+ */
7475
+ sendChunk(chunk: AsyncInputStreamChunkEvent): void;
7476
+ /**
7477
+ * Registers a handler for stream chunks
7478
+ * @param cb - Callback receiving each chunk
7479
+ * @returns Cleanup function to remove the handler
7480
+ */
7481
+ onChunk(cb: (chunk: AsyncInputStreamChunkEvent) => void): () => void;
7482
+ /**
7483
+ * Ends the input stream
7484
+ * @param endAsyncInputStream - Optional end event data
7485
+ */
7486
+ sendAsyncInputStreamEnd(endAsyncInputStream?: AsyncInputStreamEndEvent): void;
7487
+ /**
7488
+ * Registers a handler for stream end events
7489
+ * @param cb - Callback receiving the end event
7490
+ * @returns Cleanup function to remove the handler
7491
+ */
7492
+ onAsyncInputStreamEnd(cb: (endAsyncInputStream: AsyncInputStreamEndEvent) => void): () => void;
7493
+ /**
7494
+ * Sends an error start event for this stream
7495
+ * @param args - Error details including optional error ID and message
7496
+ * @internal
7497
+ */
7498
+ sendErrorStart(args: {
7499
+ errorId?: string;
7500
+ } & ErrorStartEvent): void;
7501
+ /**
7502
+ * Sends an error end event for this stream
7503
+ * @param args - Error end details including the error ID
7504
+ * @internal
7505
+ */
7506
+ sendErrorEnd(args: {
7507
+ errorId: string;
7508
+ } & ErrorEndEvent): void;
7509
+ /**
7510
+ * Sends a metadata event for this stream
7511
+ * @param metaEvent - Metadata to send
7512
+ * @internal
7513
+ */
7514
+ sendMetaEvent(metaEvent: MetaEvent): void;
7515
+ /**
7516
+ * Emits a raw async input stream event
7517
+ * @param streamEvent - The event to emit (streamId is added automatically)
7518
+ * @internal
7519
+ */
7520
+ emit(streamEvent: Omit<AsyncInputStreamEvent, 'streamId'>): void;
7521
+ /**
7522
+ * Returns a string representation of this input stream
7523
+ * @internal
7524
+ */
7525
+ toString(): string;
7526
+ }
7527
+
7528
+ /**
7529
+ * Consumer-facing interface for MessageEventHelper
7530
+ *
7531
+ * Defines the public API for interacting with message events
7532
+ * within an exchange. Messages represent individual turns from
7533
+ * users, assistants, or the system.
7534
+ */
7535
+
7536
+ /**
7537
+ * Aggregated data for a completed message
7538
+ *
7539
+ * Contains all content parts, tool calls, and metadata
7540
+ * available after a message stream has ended.
7541
+ */
7542
+ type CompletedMessage = Simplify<{
7543
+ messageId: string;
7544
+ contentParts: Array<CompletedContentPart>;
7545
+ toolCalls: Array<CompletedToolCall>;
7546
+ } & Partial<MessageStartEvent> & MessageEndEvent>;
7547
+ /**
7548
+ * Consumer-facing model for message event helpers.
7549
+ *
7550
+ * A message represents a single turn from a user, assistant, or system.
7551
+ * Messages contain content parts (text, audio, images) and tool calls.
7552
+ * The `role` property and convenience booleans (`isUser`, `isAssistant`,
7553
+ * `isSystem`) let you filter by sender.
7554
+ *
7555
+ * @example Streaming text with real-time output
7556
+ * ```typescript
7557
+ * exchange.onMessageStart((message) => {
7558
+ * if (message.isAssistant) {
7559
+ * message.onContentPartStart((part) => {
7560
+ * if (part.isMarkdown) {
7561
+ * part.onChunk((chunk) => {
7562
+ * process.stdout.write(chunk.data ?? '');
7563
+ * });
7564
+ * }
7565
+ * });
7566
+ * }
7567
+ * });
7568
+ * ```
7569
+ *
7570
+ * @example Handling tool calls with confirmation interrupts
7571
+ * ```typescript
7572
+ * exchange.onMessageStart((message) => {
7573
+ * if (message.isAssistant) {
7574
+ * message.onToolCallStart((toolCall) => {
7575
+ * console.log(`Tool: ${toolCall.startEvent.toolName}`);
7576
+ * });
7577
+ *
7578
+ * message.onInterruptStart(({ interruptId, startEvent }) => {
7579
+ * if (startEvent.type === 'uipath_cas_tool_call_confirmation') {
7580
+ * message.sendInterruptEnd(interruptId, { approved: true });
7581
+ * }
7582
+ * });
7583
+ * }
7584
+ * });
7585
+ * ```
7586
+ *
7587
+ * @example Getting the complete message at once (buffered)
7588
+ * ```typescript
7589
+ * exchange.onMessageStart((message) => {
7590
+ * if (message.isAssistant) {
7591
+ * message.onCompleted((completed) => {
7592
+ * console.log(`Message ${completed.messageId} finished`);
7593
+ * for (const part of completed.contentParts) {
7594
+ * console.log(part.data);
7595
+ * }
7596
+ * for (const tool of completed.toolCalls) {
7597
+ * console.log(`${tool.toolName} → ${tool.output}`);
7598
+ * }
7599
+ * });
7600
+ * }
7601
+ * });
7602
+ * ```
7603
+ *
7604
+ * @example Sending a content part with convenience method
7605
+ * ```typescript
7606
+ * const message = exchange.startMessage({ role: MessageRole.User });
7607
+ * await message.sendContentPart({ data: 'Hello!', mimeType: 'text/plain' });
7608
+ * message.sendMessageEnd();
7609
+ * ```
7610
+ */
7611
+ interface MessageStream {
7612
+ /** Unique identifier for this message */
7613
+ readonly messageId: string;
7614
+ /** The role of this message sender, or undefined if start event not yet received */
7615
+ readonly role: MessageRole | undefined;
7616
+ /** Whether this message is from the user */
7617
+ readonly isUser: boolean;
7618
+ /** Whether this message is from the assistant */
7619
+ readonly isAssistant: boolean;
7620
+ /** Whether this message is a system message */
7621
+ readonly isSystem: boolean;
7622
+ /**
7623
+ * The start event, or undefined if not yet received
7624
+ * @internal
7625
+ */
7626
+ readonly startEventMaybe: MessageStartEvent | undefined;
7627
+ /**
7628
+ * The start event (throws if not yet received)
7629
+ * @internal
7630
+ */
7631
+ readonly startEvent: MakeRequired<MessageStartEvent, 'timestamp'>;
7632
+ /** Whether this message has ended */
7633
+ readonly ended: boolean;
7634
+ /**
7635
+ * Registers a handler for error start events
7636
+ *
7637
+ * @param cb - Callback receiving the error event
7638
+ * @returns Cleanup function to remove the handler
7639
+ *
7640
+ * @example Message-level error handling
7641
+ * ```typescript
7642
+ * message.onErrorStart((error) => {
7643
+ * console.error(`Message error [${error.errorId}]: ${error.message}`);
7644
+ * });
7645
+ * ```
7646
+ */
7647
+ onErrorStart(cb: (error: {
7648
+ errorId: string;
7649
+ } & ErrorStartEvent) => void): () => void;
7650
+ /**
7651
+ * Registers a handler for error end events
7652
+ * @param cb - Callback receiving the error end event
7653
+ * @returns Cleanup function to remove the handler
7654
+ */
7655
+ onErrorEnd(cb: (error: {
7656
+ errorId: string;
7657
+ } & ErrorEndEvent) => void): () => void;
7658
+ /**
7659
+ * Registers a handler for content part start events
7660
+ *
7661
+ * Content parts are streamed pieces of content (text, audio, images,
7662
+ * transcripts). Use `part.isMarkdown`, `part.isAudio`, etc. to determine type.
7663
+ *
7664
+ * @param cb - Callback receiving each new content part
7665
+ * @returns Cleanup function to remove the handler
7666
+ *
7667
+ * @example Streaming text and handling different content types
7668
+ * ```typescript
7669
+ * message.onContentPartStart((part) => {
7670
+ * if (part.isMarkdown) {
7671
+ * part.onChunk((chunk) => renderMarkdown(chunk.data ?? ''));
7672
+ * } else if (part.isAudio) {
7673
+ * part.onChunk((chunk) => audioPlayer.enqueue(chunk.data ?? ''));
7674
+ * } else if (part.isImage) {
7675
+ * part.onChunk((chunk) => imageBuffer.append(chunk.data ?? ''));
7676
+ * } else if (part.isTranscript) {
7677
+ * part.onChunk((chunk) => showTranscript(chunk.data ?? ''));
7678
+ * }
7679
+ * });
7680
+ * ```
7681
+ */
7682
+ onContentPartStart(cb: (contentPart: ContentPartStream) => void): () => void;
7683
+ /**
7684
+ * Registers a handler for tool call start events
7685
+ *
7686
+ * Tool calls represent the agent invoking external tools. Each tool call
7687
+ * has a name, input, and eventually an output when it completes.
7688
+ *
7689
+ * @param cb - Callback receiving each new tool call
7690
+ * @returns Cleanup function to remove the handler
7691
+ *
7692
+ * @example Streaming tool call events
7693
+ * ```typescript
7694
+ * message.onToolCallStart((toolCall) => {
7695
+ * const { toolName, input } = toolCall.startEvent;
7696
+ * console.log(`Calling ${toolName}:`, JSON.parse(input ?? '{}'));
7697
+ *
7698
+ * toolCall.onToolCallEnd((end) => {
7699
+ * console.log(`Result:`, JSON.parse(end.output ?? '{}'));
7700
+ * });
7701
+ * });
7702
+ * ```
7703
+ */
7704
+ onToolCallStart(cb: (toolCall: ToolCallStream) => void): () => void;
7705
+ /**
7706
+ * Registers a handler for message end events
7707
+ *
7708
+ * @param cb - Callback receiving the end event
7709
+ * @returns Cleanup function to remove the handler
7710
+ *
7711
+ * @example Tracking message lifecycle
7712
+ * ```typescript
7713
+ * message.onMessageEnd((endEvent) => {
7714
+ * console.log('Message ended');
7715
+ * });
7716
+ * ```
7717
+ */
7718
+ onMessageEnd(cb: (endMessage: MessageEndEvent) => void): () => void;
7719
+ /**
7720
+ * Registers a handler called when a content part finishes
7721
+ *
7722
+ * Convenience method that combines onContentPartStart + onContentPartEnd.
7723
+ * The handler receives the full buffered content part data including
7724
+ * text, citations, and any citation errors.
7725
+ *
7726
+ * @param cb - Callback receiving the completed content part data
7727
+ *
7728
+ * @example Getting completed content parts with citations
7729
+ * ```typescript
7730
+ * message.onContentPartCompleted((completed) => {
7731
+ * console.log(`[${completed.mimeType}] ${completed.data}`);
7732
+ *
7733
+ * // Access citations if present
7734
+ * for (const citation of completed.citations) {
7735
+ * const citedText = completed.data.substring(citation.offset, citation.offset + citation.length);
7736
+ * console.log(`Citation "${citedText}" from:`, citation.sources);
7737
+ * }
7738
+ *
7739
+ * // Check for citation errors
7740
+ * for (const error of completed.citationErrors) {
7741
+ * console.warn(`Citation error [${error.citationId}]: ${error.errorType}`);
7742
+ * }
7743
+ * });
7744
+ * ```
7745
+ */
7746
+ onContentPartCompleted(cb: (completedContentPart: CompletedContentPart) => void): void;
7747
+ /**
7748
+ * Registers a handler called when a tool call finishes
7749
+ *
7750
+ * Convenience method that combines onToolCallStart + onToolCallEnd.
7751
+ * The handler receives the merged start and end event data.
7752
+ *
7753
+ * @param cb - Callback receiving the completed tool call data
7754
+ *
7755
+ * @example Getting completed tool calls
7756
+ * ```typescript
7757
+ * message.onToolCallCompleted((toolCall) => {
7758
+ * console.log(`Tool: ${toolCall.toolName}`);
7759
+ * console.log(`Input: ${toolCall.input}`);
7760
+ * console.log(`Output: ${toolCall.output}`);
7761
+ * });
7762
+ * ```
7763
+ */
7764
+ onToolCallCompleted(cb: (completedToolCall: CompletedToolCall) => void): void;
7765
+ /**
7766
+ * Registers a handler called when the entire message finishes
7767
+ *
7768
+ * The handler receives the aggregated message data including
7769
+ * all completed content parts and tool calls.
7770
+ *
7771
+ * @param cb - Callback receiving the completed message data
7772
+ *
7773
+ * @example Getting the full buffered message
7774
+ * ```typescript
7775
+ * message.onCompleted((completed) => {
7776
+ * console.log(`Message ${completed.messageId} (role: ${completed.role})`);
7777
+ * console.log('Text:', completed.contentParts.map(p => p.data).join(''));
7778
+ * console.log('Tool calls:', completed.toolCalls.length);
7779
+ * });
7780
+ * ```
7781
+ */
7782
+ onCompleted(cb: (completedMessage: CompletedMessage) => void): void;
7783
+ /**
7784
+ * Registers a handler for interrupt start events
7785
+ *
7786
+ * Interrupts represent pause points where the agent needs external input,
7787
+ * such as tool call confirmation requests.
7788
+ *
7789
+ * @param cb - Callback receiving the interrupt ID and start event
7790
+ * @returns Cleanup function to remove the handler
7791
+ *
7792
+ * @example Handling tool call confirmation
7793
+ * ```typescript
7794
+ * message.onInterruptStart(({ interruptId, startEvent }) => {
7795
+ * if (startEvent.type === 'uipath_cas_tool_call_confirmation') {
7796
+ * // Show confirmation UI, then respond
7797
+ * message.sendInterruptEnd(interruptId, { approved: true });
7798
+ * }
7799
+ * });
7800
+ * ```
7801
+ */
7802
+ onInterruptStart(cb: (interrupt: {
7803
+ interruptId: string;
7804
+ startEvent: InterruptStartEvent;
7805
+ }) => void): () => void;
7806
+ /**
7807
+ * Registers a handler for interrupt end events
7808
+ *
7809
+ * @param cb - Callback receiving the interrupt ID and end event
7810
+ * @returns Cleanup function to remove the handler
7811
+ *
7812
+ * @example Tracking interrupt resolution
7813
+ * ```typescript
7814
+ * message.onInterruptEnd(({ interruptId, endEvent }) => {
7815
+ * console.log(`Interrupt ${interruptId} resolved`);
7816
+ * });
7817
+ * ```
7818
+ */
7819
+ onInterruptEnd(cb: (interrupt: {
7820
+ interruptId: string;
7821
+ endEvent: InterruptEndEvent;
7822
+ }) => void): () => void;
7823
+ /**
7824
+ * Sends an interrupt end event to resolve a pending interrupt
7825
+ *
7826
+ * Call this to respond to an interrupt received via onInterruptStart.
7827
+ *
7828
+ * @param interruptId - The interrupt ID to respond to
7829
+ * @param endInterrupt - The response data (e.g., approval for tool call confirmation)
7830
+ *
7831
+ * @example Approving a tool call confirmation
7832
+ * ```typescript
7833
+ * message.sendInterruptEnd(interruptId, { approved: true });
7834
+ * ```
7835
+ */
7836
+ sendInterruptEnd(interruptId: string, endInterrupt: InterruptEndEvent): void;
7837
+ /**
7838
+ * Starts a new content part stream in this message
7839
+ *
7840
+ * Use this for streaming content in chunks. For sending
7841
+ * complete content in one call, prefer {@link sendContentPart}.
7842
+ *
7843
+ * @param args - Content part start options including mime type
7844
+ * @returns The content part stream for sending chunks
7845
+ *
7846
+ * @example Streaming text content in chunks
7847
+ * ```typescript
7848
+ * const part = message.startContentPart({ mimeType: 'text/markdown' });
7849
+ * part.sendChunk({ data: '# Hello\n' });
7850
+ * part.sendChunk({ data: 'This is **markdown** content.' });
7851
+ * part.sendContentPartEnd();
7852
+ * ```
7853
+ */
7854
+ startContentPart(args: {
7855
+ contentPartId?: string;
7856
+ } & ContentPartStartEvent): ContentPartStream;
7857
+ /**
7858
+ * Sends a complete content part with data in one step
7859
+ *
7860
+ * Convenience method that creates a content part, sends the data as a chunk,
7861
+ * and ends the content part. Defaults to mimeType "text/markdown".
7862
+ *
7863
+ * @param args - Content part data and optional mime type
7864
+ *
7865
+ * @example Sending a text content part
7866
+ * ```typescript
7867
+ * await message.sendContentPart({ data: 'Hello world!' });
7868
+ * ```
7869
+ *
7870
+ * @example Sending with explicit mime type
7871
+ * ```typescript
7872
+ * await message.sendContentPart({
7873
+ * data: 'Plain text content',
7874
+ * mimeType: 'text/plain'
7875
+ * });
7876
+ * ```
7877
+ */
7878
+ sendContentPart(args: {
7879
+ data?: string;
7880
+ mimeType?: string;
7881
+ }): Promise<void>;
7882
+ /**
7883
+ * Iterator over all active content parts in this message
7884
+ */
7885
+ readonly contentParts: Iterable<ContentPartStream>;
7886
+ /**
7887
+ * Retrieves a content part by ID
7888
+ * @param contentPartId - The content part ID to look up
7889
+ * @returns The content part stream, or undefined if not found
7890
+ */
7891
+ getContentPart(contentPartId: string): ContentPartStream | undefined;
7892
+ /**
7893
+ * Starts a new tool call in this message
7894
+ *
7895
+ * @param args - Tool call start options including tool name
7896
+ * @returns The tool call stream for managing the tool call lifecycle
7897
+ *
7898
+ * @example Creating and completing a tool call
7899
+ * ```typescript
7900
+ * const toolCall = message.startToolCall({
7901
+ * toolName: 'get-weather',
7902
+ * input: JSON.stringify({ city: 'London' })
7903
+ * });
7904
+ * toolCall.sendToolCallEnd({
7905
+ * output: JSON.stringify({ temperature: 18, condition: 'cloudy' })
7906
+ * });
7907
+ * ```
7908
+ */
7909
+ startToolCall(args: {
7910
+ toolCallId?: string;
7911
+ } & ToolCallStartEvent): ToolCallStream;
7912
+ /**
7913
+ * Iterator over all active tool calls in this message
7914
+ */
7915
+ readonly toolCalls: Iterable<ToolCallStream>;
7916
+ /**
7917
+ * Retrieves a tool call by ID
7918
+ * @param toolCallId - The tool call ID to look up
7919
+ * @returns The tool call stream, or undefined if not found
7920
+ */
7921
+ getToolCall(toolCallId: string): ToolCallStream | undefined;
7922
+ /**
7923
+ * Ends the message
7924
+ *
7925
+ * @param endMessage - Optional end event data
7926
+ *
7927
+ * @example Ending a message
7928
+ * ```typescript
7929
+ * message.sendMessageEnd();
7930
+ * ```
7931
+ */
7932
+ sendMessageEnd(endMessage?: MessageEndEvent): void;
7933
+ /**
7934
+ * Sends an error start event for this message
7935
+ * @param args - Error details including optional error ID and message
7936
+ * @internal
7937
+ */
7938
+ sendErrorStart(args: {
7939
+ errorId?: string;
7940
+ } & ErrorStartEvent): void;
7941
+ /**
7942
+ * Sends an error end event for this message
7943
+ * @param args - Error end details including the error ID
7944
+ * @internal
7945
+ */
7946
+ sendErrorEnd(args: {
7947
+ errorId: string;
7948
+ } & ErrorEndEvent): void;
7949
+ /**
7950
+ * Sends a metadata event for this message
7951
+ * @param metaEvent - Metadata to send
7952
+ * @internal
7953
+ */
7954
+ sendMetaEvent(metaEvent: MetaEvent): void;
7955
+ /**
7956
+ * Emits a raw message event
7957
+ * @param messageEvent - The event to emit (messageId is added automatically)
7958
+ * @internal
7959
+ */
7960
+ emit(messageEvent: Omit<MessageEvent, 'messageId'>): void;
7961
+ /**
7962
+ * Sends an interrupt start event
7963
+ * @param interruptId - The interrupt ID
7964
+ * @param startInterrupt - The interrupt start event data
7965
+ * @internal
7966
+ */
7967
+ sendInterrupt(interruptId: string, startInterrupt: InterruptStartEvent): void;
7968
+ /**
7969
+ * Returns a string representation of this message
7970
+ * @internal
7971
+ */
7972
+ toString(): string;
7973
+ }
7974
+
7975
+ /**
7976
+ * Consumer-facing interface for ExchangeEventHelper
7977
+ *
7978
+ * Defines the public API for interacting with exchange events
7979
+ * within a session. Exchanges represent request-response pairs
7980
+ * containing user and assistant messages.
7981
+ */
7982
+
7983
+ /**
7984
+ * Consumer-facing model for exchange event helpers.
7985
+ *
7986
+ * An exchange represents a single request-response cycle within a session.
7987
+ * Each exchange contains one or more messages (typically a user message
7988
+ * followed by an assistant response). Use exchanges to group related
7989
+ * turns in a multi-turn conversation.
7990
+ *
7991
+ * @example Streaming assistant response
7992
+ * ```typescript
7993
+ * session.onExchangeStart((exchange) => {
7994
+ * exchange.onMessageStart((message) => {
7995
+ * if (message.isAssistant) {
7996
+ * message.onContentPartStart((part) => {
7997
+ * if (part.isMarkdown) {
7998
+ * part.onChunk((chunk) => {
7999
+ * process.stdout.write(chunk.data ?? '');
8000
+ * });
8001
+ * }
8002
+ * });
8003
+ * }
8004
+ * });
8005
+ * });
8006
+ * ```
8007
+ *
8008
+ * @example Getting the completed message at once (no streaming)
8009
+ * ```typescript
8010
+ * session.onExchangeStart((exchange) => {
8011
+ * exchange.onMessageCompleted((completed) => {
8012
+ * for (const part of completed.contentParts) {
8013
+ * console.log(part.data);
8014
+ * }
8015
+ * for (const tool of completed.toolCalls) {
8016
+ * console.log(`${tool.toolName}: ${tool.output}`);
8017
+ * }
8018
+ * });
8019
+ * });
8020
+ * ```
8021
+ *
8022
+ * @example Sending a user message with convenience method
8023
+ * ```typescript
8024
+ * // Call startExchange inside onSessionStarted to ensure the session is ready
8025
+ * session.onSessionStarted(() => {
8026
+ * const exchange = session.startExchange();
8027
+ * exchange.sendMessageWithContentPart({
8028
+ * data: 'Hello, how can you help me?',
8029
+ * role: MessageRole.User
8030
+ * });
8031
+ * });
8032
+ * ```
8033
+ *
8034
+ * @example Sending a user message with streaming parts
8035
+ * ```typescript
8036
+ * // Call startExchange inside onSessionStarted to ensure the session is ready
8037
+ * session.onSessionStarted(() => {
8038
+ * const exchange = session.startExchange();
8039
+ * const message = exchange.startMessage({ role: MessageRole.User });
8040
+ * const part = message.startContentPart({ mimeType: 'text/plain' });
8041
+ * part.sendChunk({ data: 'Hello, ' });
8042
+ * part.sendChunk({ data: 'how can you help me?' });
8043
+ * part.sendContentPartEnd();
8044
+ * message.sendMessageEnd();
8045
+ * });
8046
+ * ```
8047
+ */
8048
+ interface ExchangeStream {
8049
+ /** Unique identifier for this exchange */
8050
+ readonly exchangeId: string;
8051
+ /**
8052
+ * The start event, or undefined if not yet received
8053
+ * @internal
8054
+ */
8055
+ readonly startEventMaybe: ExchangeStartEvent | undefined;
8056
+ /**
8057
+ * The start event (throws if not yet received)
8058
+ * @internal
8059
+ */
8060
+ readonly startEvent: MakeRequired<ExchangeStartEvent, 'timestamp'>;
8061
+ /** Whether this exchange has ended */
8062
+ readonly ended: boolean;
8063
+ /**
8064
+ * Registers a handler for error start events
8065
+ *
8066
+ * @param cb - Callback receiving the error event
8067
+ * @returns Cleanup function to remove the handler
8068
+ *
8069
+ * @example Exchange-level error handling
8070
+ * ```typescript
8071
+ * exchange.onErrorStart((error) => {
8072
+ * console.error(`Exchange error [${error.errorId}]: ${error.message}`);
8073
+ * });
8074
+ * ```
8075
+ */
8076
+ onErrorStart(cb: (error: {
8077
+ errorId: string;
8078
+ } & ErrorStartEvent) => void): () => void;
8079
+ /**
8080
+ * Registers a handler for error end events
8081
+ * @param cb - Callback receiving the error end event
8082
+ * @returns Cleanup function to remove the handler
8083
+ */
8084
+ onErrorEnd(cb: (error: {
8085
+ errorId: string;
8086
+ } & ErrorEndEvent) => void): () => void;
8087
+ /**
8088
+ * Registers a handler for message start events
8089
+ *
8090
+ * Each exchange typically contains a user message and an assistant
8091
+ * response. Use `message.isAssistant` or `message.isUser` to filter.
8092
+ *
8093
+ * @param cb - Callback receiving each new message
8094
+ * @returns Cleanup function to remove the handler
8095
+ *
8096
+ * @example Filtering by message role
8097
+ * ```typescript
8098
+ * exchange.onMessageStart((message) => {
8099
+ * if (message.isAssistant) {
8100
+ * message.onContentPartStart((part) => {
8101
+ * if (part.isMarkdown) {
8102
+ * part.onChunk((chunk) => process.stdout.write(chunk.data ?? ''));
8103
+ * }
8104
+ * });
8105
+ * }
8106
+ * });
8107
+ * ```
8108
+ */
8109
+ onMessageStart(cb: (message: MessageStream) => void): () => void;
8110
+ /**
8111
+ * Registers a handler for exchange end events
8112
+ *
8113
+ * @param cb - Callback receiving the end event
8114
+ * @returns Cleanup function to remove the handler
8115
+ *
8116
+ * @example Tracking exchange lifecycle
8117
+ * ```typescript
8118
+ * exchange.onExchangeEnd((endEvent) => {
8119
+ * console.log('Exchange completed');
8120
+ * });
8121
+ * ```
8122
+ */
8123
+ onExchangeEnd(cb: (endExchange: ExchangeEndEvent) => void): () => void;
8124
+ /**
8125
+ * Registers a handler called when a message finishes
8126
+ *
8127
+ * Convenience method that combines onMessageStart + message.onCompleted.
8128
+ * The handler receives the aggregated message data including all
8129
+ * content parts and tool calls.
8130
+ *
8131
+ * @param cb - Callback receiving the completed message data
8132
+ *
8133
+ * @example Getting buffered message with all content and tool calls
8134
+ * ```typescript
8135
+ * exchange.onMessageCompleted((message) => {
8136
+ * console.log(`Message ${message.messageId} (role: ${message.role})`);
8137
+ * console.log(`Content parts: ${message.contentParts.length}`);
8138
+ * console.log(`Tool calls: ${message.toolCalls.length}`);
8139
+ * });
8140
+ * ```
8141
+ */
8142
+ onMessageCompleted(cb: (completedMessage: CompletedMessage) => void): void;
8143
+ /**
8144
+ * Starts a new message in this exchange
8145
+ *
8146
+ * Use this for fine-grained control over message construction.
8147
+ * For simple text messages, prefer {@link sendMessageWithContentPart}.
8148
+ *
8149
+ * @param args - Optional message start options including role
8150
+ * @returns The message stream for sending content
8151
+ *
8152
+ * @example Building a message with multiple content parts
8153
+ * ```typescript
8154
+ * const message = exchange.startMessage({ role: MessageRole.User });
8155
+ * const part = message.startContentPart({ mimeType: 'text/plain' });
8156
+ * part.sendChunk({ data: 'Analyze this image: ' });
8157
+ * part.sendContentPartEnd();
8158
+ * message.sendMessageEnd();
8159
+ * ```
8160
+ */
8161
+ startMessage(args?: {
8162
+ messageId?: string;
8163
+ } & Partial<MessageStartEvent>): MessageStream;
8164
+ /**
8165
+ * Sends a complete message with a content part in one step
8166
+ *
8167
+ * Convenience method that creates a message, adds a content part with the given data,
8168
+ * and ends both the content part and message.
8169
+ *
8170
+ * @param options - Message content options
8171
+ *
8172
+ * @example Sending a user message
8173
+ * ```typescript
8174
+ * await exchange.sendMessageWithContentPart({
8175
+ * data: 'What is the weather today?',
8176
+ * role: MessageRole.User
8177
+ * });
8178
+ * ```
8179
+ */
8180
+ sendMessageWithContentPart(options: {
8181
+ data: string;
8182
+ role?: MessageRole;
8183
+ mimeType?: string;
8184
+ }): Promise<void>;
8185
+ /**
8186
+ * Iterator over all active messages in this exchange
8187
+ */
8188
+ readonly messages: Iterable<MessageStream>;
8189
+ /**
8190
+ * Retrieves a message by ID
8191
+ * @param messageId - The message ID to look up
8192
+ * @returns The message stream, or undefined if not found
8193
+ */
8194
+ getMessage(messageId: string): MessageStream | undefined;
8195
+ /**
8196
+ * Ends the exchange
8197
+ *
8198
+ * @param endExchange - Optional end event data
8199
+ *
8200
+ * @example Manually ending an exchange
8201
+ * ```typescript
8202
+ * exchange.sendExchangeEnd();
8203
+ * ```
8204
+ */
8205
+ sendExchangeEnd(endExchange?: ExchangeEndEvent): void;
8206
+ /**
8207
+ * Sends an error start event for this exchange
8208
+ * @param args - Error details including optional error ID and message
8209
+ * @internal
8210
+ */
8211
+ sendErrorStart(args: {
8212
+ errorId?: string;
8213
+ } & ErrorStartEvent): void;
8214
+ /**
8215
+ * Sends an error end event for this exchange
8216
+ * @param args - Error end details including the error ID
8217
+ * @internal
8218
+ */
8219
+ sendErrorEnd(args: {
8220
+ errorId: string;
8221
+ } & ErrorEndEvent): void;
8222
+ /**
8223
+ * Sends a metadata event for this exchange
8224
+ * @param metaEvent - Metadata to send
8225
+ * @internal
8226
+ */
8227
+ sendMetaEvent(metaEvent: MetaEvent): void;
8228
+ /**
8229
+ * Emits a raw exchange event
8230
+ * @param exchangeEvent - The event to emit (exchangeId is added automatically)
8231
+ * @internal
8232
+ */
8233
+ emit(exchangeEvent: Omit<ExchangeEvent, 'exchangeId'>): void;
8234
+ /**
8235
+ * Returns a string representation of this exchange
8236
+ * @internal
8237
+ */
8238
+ toString(): string;
8239
+ }
8240
+
8241
+ /**
8242
+ * Consumer-facing interface for SessionEventHelper
8243
+ *
8244
+ * Defines the public API for interacting with a real-time
8245
+ * conversation session. Sessions are the top-level container
8246
+ * for exchanges, messages, and streaming content.
8247
+ */
8248
+
8249
+ /**
8250
+ * Real-time WebSocket session for two-way communication within a {@link ConversationServiceModel | Conversation}.
8251
+ *
8252
+ * Send messages and receive agent responses through a nested stream hierarchy.
8253
+ * The `SessionStream` is the top-level entry point — events flow down through
8254
+ * exchanges, messages, content parts, and tool calls.
8255
+ *
8256
+ * ### Usage
8257
+ *
8258
+ * **Important:** Always wait for `onSessionStarted` before calling
8259
+ * `startExchange`. The session must be fully connected via WebSocket
8260
+ * before exchanges can be sent — calling `startExchange` earlier may
8261
+ * lose events or cause errors.
8262
+ *
8263
+ * ```typescript
8264
+ * const session = conversation.startSession();
8265
+ *
8266
+ * // Set up handlers for incoming assistant responses
8267
+ * session.onExchangeStart((exchange) => {
8268
+ * exchange.onMessageStart((message) => {
8269
+ * if (message.isAssistant) {
8270
+ * message.onContentPartStart((part) => {
8271
+ * if (part.isMarkdown) {
8272
+ * part.onChunk((chunk) => {
8273
+ * process.stdout.write(chunk.data ?? '');
8274
+ * });
8275
+ * }
8276
+ * });
8277
+ * }
8278
+ * });
8279
+ * });
8280
+ *
8281
+ * // Wait for the session to be ready, then send a message
8282
+ * session.onSessionStarted(() => {
8283
+ * const exchange = session.startExchange();
8284
+ * exchange.sendMessageWithContentPart({
8285
+ * data: 'Hello!',
8286
+ * role: MessageRole.User
8287
+ * });
8288
+ * });
8289
+ *
8290
+ * // End the session when done
8291
+ * conversation.endSession();
8292
+ * ```
8293
+ *
8294
+ * ### Related Streams
8295
+ *
8296
+ * | Stream | Description |
8297
+ * | --- | --- |
8298
+ * | {@link ExchangeStream} | A single request-response cycle within a session. Contains user and assistant messages. |
8299
+ * | {@link MessageStream} | A single message (user, assistant, or system). Contains content parts and tool calls. |
8300
+ * | {@link ContentPartStream} | A piece of streamed content (text, audio, image, transcript). Delivers data via `onChunk`. |
8301
+ * | {@link ToolCallStream} | An external tool invocation by the assistant. Has a start event (name, input) and end event (output). |
8302
+ */
8303
+ interface SessionStream {
8304
+ /** The conversation ID this session belongs to */
8305
+ readonly conversationId: string;
8306
+ /**
8307
+ * Whether echo mode is enabled (emitted events are also dispatched to handlers)
8308
+ * @internal
8309
+ */
8310
+ readonly echo: boolean;
8311
+ /**
8312
+ * The start event, or undefined if not yet received
8313
+ * @internal
8314
+ */
8315
+ readonly startEventMaybe: SessionStartEvent | undefined;
8316
+ /**
8317
+ * The start event (throws if not yet received)
8318
+ * @internal
8319
+ */
8320
+ readonly startEvent: SessionStartEvent;
8321
+ /** Whether this session has ended */
8322
+ readonly ended: boolean;
8323
+ /**
8324
+ * Whether event emitting is currently paused
8325
+ * @internal
8326
+ */
8327
+ readonly isEmitPaused: boolean;
8328
+ /**
8329
+ * Pauses emitting events to the WebSocket
8330
+ *
8331
+ * Events are buffered internally and sent when `resumeEmits` is called.
8332
+ * Useful when you need to set up event handlers before events start flowing
8333
+ * (e.g., between starting a session and receiving the session started event).
8334
+ * @internal
8335
+ */
8336
+ pauseEmits(): void;
8337
+ /**
8338
+ * Resumes emitting events and flushes any buffered events
8339
+ *
8340
+ * All events that were buffered while paused are sent in order.
8341
+ * @internal
8342
+ */
8343
+ resumeEmits(): void;
8344
+ /**
8345
+ * Registers a handler for error start events at the session level
8346
+ *
8347
+ * @param cb - Callback receiving the error event
8348
+ * @returns Cleanup function to remove the handler
8349
+ *
8350
+ * @example
8351
+ * ```typescript
8352
+ * session.onErrorStart((error) => {
8353
+ * console.error(`Session error [${error.errorId}]: ${error.message}`);
8354
+ * });
8355
+ * ```
8356
+ */
8357
+ onErrorStart(cb: (error: {
8358
+ errorId: string;
8359
+ } & ErrorStartEvent) => void): () => void;
8360
+ /**
8361
+ * Registers a handler for error end events at the session level
8362
+ *
8363
+ * @param cb - Callback receiving the error end event
8364
+ * @returns Cleanup function to remove the handler
8365
+ *
8366
+ * @example
8367
+ * ```typescript
8368
+ * session.onErrorEnd((error) => {
8369
+ * console.log(`Error ${error.errorId} resolved`);
8370
+ * });
8371
+ * ```
8372
+ */
8373
+ onErrorEnd(cb: (error: {
8374
+ errorId: string;
8375
+ } & ErrorEndEvent) => void): () => void;
8376
+ /**
8377
+ * Registers a handler for exchange start events
8378
+ *
8379
+ * This is the primary entry point for handling agent responses.
8380
+ * Each exchange represents a request-response cycle containing
8381
+ * user and assistant messages.
8382
+ *
8383
+ * @param cb - Callback receiving each new exchange
8384
+ * @returns Cleanup function to remove the handler
8385
+ *
8386
+ * @example Streaming text with content type handling
8387
+ * ```typescript
8388
+ * session.onExchangeStart((exchange) => {
8389
+ * exchange.onMessageStart((message) => {
8390
+ * if (message.isAssistant) {
8391
+ * message.onContentPartStart((part) => {
8392
+ * if (part.isMarkdown) {
8393
+ * part.onChunk((chunk) => renderMarkdown(chunk.data ?? ''));
8394
+ * } else if (part.isAudio) {
8395
+ * part.onChunk((chunk) => audioPlayer.enqueue(chunk.data ?? ''));
8396
+ * } else if (part.isImage) {
8397
+ * part.onChunk((chunk) => imageBuffer.append(chunk.data ?? ''));
8398
+ * } else if (part.isTranscript) {
8399
+ * part.onChunk((chunk) => showTranscript(chunk.data ?? ''));
8400
+ * }
8401
+ * });
8402
+ * }
8403
+ * });
8404
+ * });
8405
+ * ```
8406
+ *
8407
+ * @example Getting the complete response at once (no streaming)
8408
+ * ```typescript
8409
+ * session.onExchangeStart((exchange) => {
8410
+ * exchange.onMessageCompleted((completed) => {
8411
+ * console.log(`Message ${completed.messageId} (role: ${completed.role})`);
8412
+ * for (const part of completed.contentParts) {
8413
+ * console.log(part.data);
8414
+ * }
8415
+ * for (const tool of completed.toolCalls) {
8416
+ * console.log(`${tool.toolName} → ${tool.output}`);
8417
+ * }
8418
+ * });
8419
+ * });
8420
+ * ```
8421
+ *
8422
+ * @example Handling tool calls and confirmation interrupts
8423
+ * ```typescript
8424
+ * session.onExchangeStart((exchange) => {
8425
+ * exchange.onMessageStart((message) => {
8426
+ * if (message.isAssistant) {
8427
+ * // Stream tool call events
8428
+ * message.onToolCallStart((toolCall) => {
8429
+ * const { toolName, input } = toolCall.startEvent;
8430
+ * console.log(`Calling ${toolName}:`, JSON.parse(input ?? '{}'));
8431
+ * toolCall.onToolCallEnd((end) => {
8432
+ * console.log(`Result:`, JSON.parse(end.output ?? '{}'));
8433
+ * });
8434
+ * });
8435
+ *
8436
+ * // Handle confirmation interrupts
8437
+ * message.onInterruptStart(({ interruptId, startEvent }) => {
8438
+ * if (startEvent.type === 'uipath_cas_tool_call_confirmation') {
8439
+ * message.sendInterruptEnd(interruptId, { approved: true });
8440
+ * }
8441
+ * });
8442
+ * }
8443
+ * });
8444
+ * });
8445
+ * ```
8446
+ */
8447
+ onExchangeStart(cb: (exchange: ExchangeStream) => void): () => void;
8448
+ /**
8449
+ * Registers a handler for session started events
8450
+ *
8451
+ * Fired when the WebSocket connection is established and the
8452
+ * session is ready to send and receive events.
8453
+ *
8454
+ * @param cb - Callback receiving the started event
8455
+ * @returns Cleanup function to remove the handler
8456
+ *
8457
+ * @example
8458
+ * ```typescript
8459
+ * session.onSessionStarted(() => {
8460
+ * console.log('Session is ready — now safe to start exchanges');
8461
+ *
8462
+ * const exchange = session.startExchange();
8463
+ * exchange.sendMessageWithContentPart({
8464
+ * data: 'Hello!',
8465
+ * role: MessageRole.User
8466
+ * });
8467
+ * });
8468
+ * ```
8469
+ */
8470
+ onSessionStarted(cb: (event: SessionStartedEvent) => void): () => void;
8471
+ /**
8472
+ * Registers a handler for session ending events
8473
+ *
8474
+ * Fired when the session is about to end. Use this for cleanup
8475
+ * before the session fully closes.
8476
+ *
8477
+ * @param cb - Callback receiving the ending event
8478
+ * @returns Cleanup function to remove the handler
8479
+ *
8480
+ * @example
8481
+ * ```typescript
8482
+ * session.onSessionEnding((event) => {
8483
+ * console.log('Session is ending, performing cleanup...');
8484
+ * });
8485
+ * ```
8486
+ */
8487
+ onSessionEnding(cb: (event: SessionEndingEvent) => void): () => void;
8488
+ /**
8489
+ * Registers a handler for session end events
8490
+ *
8491
+ * Fired when the session has fully closed.
8492
+ *
8493
+ * @param cb - Callback receiving the end event
8494
+ * @returns Cleanup function to remove the handler
8495
+ *
8496
+ * @example
8497
+ * ```typescript
8498
+ * session.onSessionEnd((event) => {
8499
+ * console.log('Session ended');
8500
+ * });
8501
+ * ```
8502
+ */
8503
+ onSessionEnd(cb: (event: SessionEndEvent) => void): () => void;
8504
+ /**
8505
+ * Registers a handler for conversation label updates
8506
+ *
8507
+ * Fired when the conversation label changes, typically when the server
8508
+ * auto-generates a title based on the first message.
8509
+ *
8510
+ * @param cb - Callback receiving the {@link LabelUpdatedEvent} with the new label
8511
+ * @returns Cleanup function to remove the handler
8512
+ *
8513
+ * @example
8514
+ * ```typescript
8515
+ * session.onLabelUpdated((event) => {
8516
+ * console.log(`New label: ${event.label} (auto: ${event.autogenerated})`);
8517
+ * updateConversationTitle(event.label);
8518
+ * });
8519
+ * ```
8520
+ */
8521
+ onLabelUpdated(cb: (event: LabelUpdatedEvent) => void): () => void;
8522
+ /**
8523
+ * Sends a session started event
8524
+ * @param sessionStarted - Optional started event data
8525
+ * @internal
8526
+ */
8527
+ sendSessionStarted(sessionStarted?: SessionStartedEvent): void;
8528
+ /**
8529
+ * Sends a session end event and closes the session
8530
+ *
8531
+ * Prefer using `conversation.endSession()` instead of calling this directly.
8532
+ *
8533
+ * @param endSession - Optional end event data
8534
+ * @internal
8535
+ */
8536
+ sendSessionEnd(endSession?: SessionEndEvent): void;
8537
+ /**
8538
+ * Sends an error start event for this session
8539
+ * @param args - Error details including optional error ID and message
8540
+ * @internal
8541
+ */
8542
+ sendErrorStart(args: {
8543
+ errorId?: string;
8544
+ } & ErrorStartEvent): void;
8545
+ /**
8546
+ * Sends an error end event for this session
8547
+ * @param args - Error end details including the error ID
8548
+ * @internal
8549
+ */
8550
+ sendErrorEnd(args: {
8551
+ errorId: string;
8552
+ } & ErrorEndEvent): void;
8553
+ /**
8554
+ * Sends a metadata event for this session
8555
+ * @param metaEvent - Metadata to send
8556
+ * @internal
8557
+ */
8558
+ sendMetaEvent(metaEvent: MetaEvent): void;
8559
+ /**
8560
+ * Starts a new exchange in this session
8561
+ *
8562
+ * Each exchange is a request-response cycle. Use `sendMessageWithContentPart`
8563
+ * on the returned {@link ExchangeStream} to send a user message, or
8564
+ * `startMessage` for fine-grained control.
8565
+ *
8566
+ * @param args - Optional exchange start options
8567
+ * @returns The exchange stream for sending messages
8568
+ *
8569
+ * @example Multi-exchange conversation
8570
+ * ```typescript
8571
+ * const session = conversation.startSession();
8572
+ *
8573
+ * // Listen for all assistant responses
8574
+ * session.onExchangeStart((exchange) => {
8575
+ * exchange.onMessageCompleted((completed) => {
8576
+ * if (completed.role === MessageRole.Assistant) {
8577
+ * for (const part of completed.contentParts) {
8578
+ * console.log('Assistant:', part.data);
8579
+ * }
8580
+ * }
8581
+ * });
8582
+ * });
8583
+ *
8584
+ * // Wait for session to be ready before starting exchanges
8585
+ * session.onSessionStarted(async () => {
8586
+ * // Send first user message
8587
+ * const exchange1 = session.startExchange();
8588
+ * await exchange1.sendMessageWithContentPart({
8589
+ * data: 'What is the weather today?',
8590
+ * role: MessageRole.User
8591
+ * });
8592
+ *
8593
+ * // Send follow-up in a new exchange
8594
+ * const exchange2 = session.startExchange();
8595
+ * await exchange2.sendMessageWithContentPart({
8596
+ * data: 'And tomorrow?',
8597
+ * role: MessageRole.User
8598
+ * });
8599
+ * });
8600
+ * ```
8601
+ */
8602
+ startExchange(args?: {
8603
+ exchangeId?: string;
8604
+ } & ExchangeStartEvent): ExchangeStream;
8605
+ /**
8606
+ * Iterator over all active exchanges in this session
8607
+ */
8608
+ readonly exchanges: Iterable<ExchangeStream>;
8609
+ /**
8610
+ * Retrieves an exchange by ID
8611
+ * @param exchangeId - The exchange ID to look up
8612
+ * @returns The exchange stream, or undefined if not found
8613
+ */
8614
+ getExchange(exchangeId: string): ExchangeStream | undefined;
8615
+ /**
8616
+ * Starts an async tool call at the session level
8617
+ * @param args - Tool call start options including tool name
8618
+ * @returns The async tool call stream for managing the lifecycle
8619
+ * @internal
8620
+ */
8621
+ startAsyncToolCall(args: {
8622
+ toolCallId?: string;
8623
+ } & ToolCallStartEvent): AsyncToolCallStream;
8624
+ /**
8625
+ * Registers a handler for async tool call start events
8626
+ * @param cb - Callback receiving each new async tool call
8627
+ * @returns Cleanup function to remove the handler
8628
+ * @internal
8629
+ */
8630
+ onAsyncToolCallStart(cb: (asyncToolCall: AsyncToolCallStream) => void): () => void;
8631
+ /**
8632
+ * Iterator over all active async tool calls in this session
8633
+ * @internal
8634
+ */
8635
+ readonly asyncToolCalls: Iterable<AsyncToolCallStream>;
8636
+ /**
8637
+ * Retrieves an async tool call by ID
8638
+ * @param toolCallId - The tool call ID to look up
8639
+ * @returns The async tool call stream, or undefined if not found
8640
+ * @internal
8641
+ */
8642
+ getAsyncToolCall(toolCallId: string): AsyncToolCallStream | undefined;
8643
+ /**
8644
+ * Starts an async input stream at the session level
8645
+ * @param args - Stream start options including MIME type
8646
+ * @returns The async input stream for sending data
8647
+ * @internal
8648
+ */
8649
+ startAsyncInputStream(args: {
8650
+ streamId?: string;
8651
+ } & AsyncInputStreamStartEvent): AsyncInputStream;
8652
+ /**
8653
+ * Registers a handler for async input stream start events
8654
+ * @param cb - Callback receiving each new input stream
8655
+ * @returns Cleanup function to remove the handler
8656
+ * @internal
8657
+ */
8658
+ onInputStreamStart(cb: (inputStream: AsyncInputStream) => void): () => void;
8659
+ /**
8660
+ * Iterator over all active async input streams in this session
8661
+ * @internal
8662
+ */
8663
+ readonly asyncInputStreams: Iterable<AsyncInputStream>;
8664
+ /**
8665
+ * Retrieves an async input stream by ID
8666
+ * @param streamId - The stream ID to look up
8667
+ * @returns The async input stream, or undefined if not found
8668
+ * @internal
8669
+ */
8670
+ getAsyncInputStream(streamId: string): AsyncInputStream | undefined;
8671
+ /**
8672
+ * Emits a raw conversation event
8673
+ * @param conversationEvent - The event to emit (conversationId is added automatically)
8674
+ * @internal
8675
+ */
8676
+ emit(conversationEvent: Omit<ConversationEvent, 'conversationId'>): void;
8677
+ /**
8678
+ * Registers a handler for error start events from any nested helper
8679
+ *
8680
+ * Unlike `onErrorStart` which only catches errors at the session level,
8681
+ * this handler receives errors from all nested helpers (exchanges, messages,
8682
+ * content parts, tool calls, etc.).
8683
+ *
8684
+ * @param cb - Callback receiving the error event with its source
8685
+ * @returns Cleanup function to remove the handler
8686
+ * @internal
8687
+ */
8688
+ onAnyErrorStart(cb: (errorStart: {
8689
+ source: unknown;
8690
+ errorId: string;
8691
+ } & ErrorStartEvent) => void): () => void;
8692
+ /**
8693
+ * Registers a handler for error end events from any nested helper
8694
+ *
8695
+ * Unlike `onErrorEnd` which only catches errors at the session level,
8696
+ * this handler receives error end events from all nested helpers.
8697
+ *
8698
+ * @param cb - Callback receiving the error end event with its source
8699
+ * @returns Cleanup function to remove the handler
8700
+ * @internal
8701
+ */
8702
+ onAnyErrorEnd(cb: (errorEnd: {
8703
+ source: unknown;
8704
+ errorId: string;
8705
+ } & ErrorEndEvent) => void): () => void;
8706
+ /**
8707
+ * Replays persisted exchanges into this session
8708
+ *
8709
+ * Used to restore session state from previously saved exchange data.
8710
+ *
8711
+ * @param exchanges - The exchange data to replay
8712
+ * @internal
8713
+ */
8714
+ replay(exchanges: Exchange[]): void;
8715
+ /**
8716
+ * Returns a string representation of this session
8717
+ * @internal
8718
+ */
8719
+ toString(): string;
8720
+ }
8721
+
8722
+ /**
8723
+ * Types for Exchange Service
8724
+ */
8725
+
8726
+ /**
8727
+ * Response type for Exchange with MessageGetResponse instead of raw Message
8728
+ */
8729
+ interface ExchangeGetResponse extends Omit<Exchange, 'messages'> {
8730
+ messages: MessageGetResponse[];
8731
+ }
8732
+ /**
8733
+ * Response type for Message with ContentPartGetResponse
8734
+ */
8735
+ interface MessageGetResponse extends Omit<Message, 'contentParts'> {
8736
+ contentParts?: ContentPartGetResponse[];
8737
+ }
8738
+ /**
8739
+ * Response interface for ContentPart with convenience methods for accessing data.
8740
+ *
8741
+ * Provides helper properties and methods to determine if content is stored
8742
+ * inline or externally, and to retrieve the data accordingly.
8743
+ *
8744
+ * @example
8745
+ * ```typescript
8746
+ * const contentPart = message.contentParts[0];
8747
+ *
8748
+ * // Check storage type
8749
+ * if (contentPart.isDataInline) {
8750
+ * const data = await contentPart.getData(); // Returns string
8751
+ * } else if (contentPart.isDataExternal) {
8752
+ * const response = await contentPart.getData(); // Returns fetch Response
8753
+ * }
8754
+ * ```
8755
+ */
8756
+ interface ContentPartGetResponse extends ContentPart {
8757
+ /** Returns true if data is stored inline (as a string value) */
8758
+ readonly isDataInline: boolean;
8759
+ /** Returns true if data is stored externally (as a URI reference) */
8760
+ readonly isDataExternal: boolean;
8761
+ /**
8762
+ * Retrieves the content data.
8763
+ * @returns For inline data: the string content. For external data: a fetch Response.
8764
+ */
8765
+ getData(): Promise<string | Response>;
8766
+ }
8767
+ type ExchangeGetAllOptions = PaginationOptions & {
8768
+ /** Sort order for exchanges */
8769
+ exchangeSort?: SortOrder;
8770
+ /** Sort order for messages within each exchange */
8771
+ messageSort?: SortOrder;
8772
+ };
8773
+ interface ExchangeGetByIdOptions {
8774
+ /** Sort order for messages within the exchange */
8775
+ messageSort?: SortOrder;
8776
+ }
8777
+ interface CreateFeedbackOptions {
8778
+ /** Rating for the exchange ('positive' or 'negative') */
8779
+ rating: FeedbackRating;
8780
+ /** Optional text comment for the feedback */
8781
+ comment?: string;
8782
+ }
8783
+ interface FeedbackCreateResponse {
8784
+ }
8785
+
8786
+ /**
8787
+ * Exchange Service Model
8788
+ */
8789
+
8790
+ /**
8791
+ * Service for retrieving exchanges and managing feedback within a {@link ConversationServiceModel | Conversation}
8792
+ *
8793
+ * An exchange represents a single request-response cycle — typically one user
8794
+ * question and the agent's reply. Each exchange response includes its
8795
+ * {@link MessageServiceModel | Messages}, making this the primary way to retrieve
8796
+ * conversation history. For real-time streaming of exchanges, see {@link ExchangeStream}.
8797
+ *
8798
+ * ### Usage
8799
+ *
8800
+ * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize)
8801
+ *
8802
+ * ```typescript
8803
+ * import { Exchanges } from '@uipath/uipath-typescript/conversational-agent';
8804
+ *
8805
+ * const exchanges = new Exchanges(sdk);
8806
+ * const conversationExchanges = await exchanges.getAll(conversationId);
8807
+ * ```
8808
+ */
8809
+ interface ExchangeServiceModel {
8810
+ /**
8811
+ * Gets all exchanges for a conversation with optional filtering and pagination
8812
+ *
8813
+ * @param conversationId - The conversation ID to get exchanges for
8814
+ * @param options - Options for querying exchanges including optional pagination parameters
8815
+ * @returns Promise resolving to either an array of exchanges {@link NonPaginatedResponse}<{@link ExchangeGetResponse}> or a {@link PaginatedResponse}<{@link ExchangeGetResponse}> when pagination options are used
8816
+ * @example
8817
+ * ```typescript
8818
+ * // Get all exchanges (non-paginated)
8819
+ * const conversationExchanges = await exchanges.getAll(conversationId);
8820
+ *
8821
+ * // First page with pagination
8822
+ * const firstPageOfExchanges = await exchanges.getAll(conversationId, { pageSize: 10 });
8823
+ *
8824
+ * // Navigate using cursor
8825
+ * if (firstPageOfExchanges.hasNextPage) {
8826
+ * const nextPageOfExchanges = await exchanges.getAll(conversationId, {
8827
+ * cursor: firstPageOfExchanges.nextCursor
8828
+ * });
8829
+ * }
8830
+ * ```
8831
+ */
8832
+ getAll<T extends ExchangeGetAllOptions = ExchangeGetAllOptions>(conversationId: string, options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<ExchangeGetResponse> : NonPaginatedResponse<ExchangeGetResponse>>;
8833
+ /**
8834
+ * Gets an exchange by ID with its messages
8835
+ *
8836
+ * @param conversationId - The conversation containing the exchange
8837
+ * @param exchangeId - The exchange ID to retrieve
8838
+ * @param options - Optional parameters for message sorting
8839
+ * @returns Promise resolving to {@link ExchangeGetResponse}
8840
+ * @example
8841
+ * ```typescript
8842
+ * const exchange = await exchanges.getById(conversationId, exchangeId);
8843
+ *
8844
+ * // Access messages
8845
+ * for (const message of exchange.messages) {
8846
+ * console.log(message.role, message.contentParts);
8847
+ * }
8848
+ * ```
8849
+ */
8850
+ getById(conversationId: string, exchangeId: string, options?: ExchangeGetByIdOptions): Promise<ExchangeGetResponse>;
8851
+ /**
8852
+ * Creates feedback for an exchange
8853
+ *
8854
+ * @param conversationId - The conversation containing the exchange
8855
+ * @param exchangeId - The exchange to provide feedback for
8856
+ * @param options - Feedback data including rating and optional comment
8857
+ * @returns Promise resolving to the feedback creation response
8858
+ * {@link FeedbackCreateResponse}
8859
+ * @example
8860
+ * ```typescript
8861
+ * await exchanges.createFeedback(
8862
+ * conversationId,
8863
+ * exchangeId,
8864
+ * { rating: FeedbackRating.Positive, comment: 'Very helpful!' }
8865
+ * );
8866
+ * ```
8867
+ */
8868
+ createFeedback(conversationId: string, exchangeId: string, options: CreateFeedbackOptions): Promise<FeedbackCreateResponse>;
8869
+ }
8870
+ /**
8871
+ * Scoped exchange service for a specific conversation.
8872
+ * Auto-fills conversationId from the conversation.
8873
+ */
8874
+ interface ConversationExchangeServiceModel {
8875
+ /**
8876
+ * Gets all exchanges for this conversation with optional filtering and pagination
8877
+ *
8878
+ * @param options - Options for querying exchanges including optional pagination parameters
8879
+ * @returns Promise resolving to either an array of exchanges or a paginated response
8880
+ *
8881
+ * @example
8882
+ * ```typescript
8883
+ * const conversation = await conversationalAgent.conversations.getById(conversationId);
8884
+ *
8885
+ * // Get all exchanges
8886
+ * const allExchanges = await conversation.exchanges.getAll();
8887
+ *
8888
+ * // With pagination
8889
+ * const firstPage = await conversation.exchanges.getAll({ pageSize: 10 });
8890
+ * if (firstPage.hasNextPage) {
8891
+ * const nextPage = await conversation.exchanges.getAll({ cursor: firstPage.nextCursor });
8892
+ * }
8893
+ * ```
8894
+ */
8895
+ getAll<T extends ExchangeGetAllOptions = ExchangeGetAllOptions>(options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<ExchangeGetResponse> : NonPaginatedResponse<ExchangeGetResponse>>;
8896
+ /**
8897
+ * Gets an exchange by ID with its messages
8898
+ *
8899
+ * @param exchangeId - The exchange ID to retrieve
8900
+ * @param options - Optional parameters for message sorting
8901
+ * @returns Promise resolving to the exchange with messages
8902
+ *
8903
+ * @example
8904
+ * ```typescript
8905
+ * const exchange = await conversation.exchanges.getById(exchangeId);
8906
+ * for (const message of exchange.messages) {
8907
+ * console.log(message.role, message.contentParts);
8908
+ * }
8909
+ * ```
8910
+ */
8911
+ getById(exchangeId: string, options?: ExchangeGetByIdOptions): Promise<ExchangeGetResponse>;
8912
+ /**
8913
+ * Creates feedback for an exchange
8914
+ *
8915
+ * @param exchangeId - The exchange to provide feedback for
8916
+ * @param options - Feedback data including rating and optional comment
8917
+ * @returns Promise resolving to the feedback creation response
8918
+ *
8919
+ * @example
8920
+ * ```typescript
8921
+ * await conversation.exchanges.createFeedback(exchangeId, {
8922
+ * rating: FeedbackRating.Positive,
8923
+ * comment: 'Very helpful!'
8924
+ * });
8925
+ * ```
8926
+ */
8927
+ createFeedback(exchangeId: string, options: CreateFeedbackOptions): Promise<FeedbackCreateResponse>;
8928
+ }
8929
+
8930
+ /**
8931
+ * WebSocket Types - Common types for WebSocket infrastructure
8932
+ */
8933
+ /**
8934
+ * Connection status for WebSocket clients
8935
+ */
8936
+ declare enum ConnectionStatus {
8937
+ Disconnected = "Disconnected",
8938
+ Connecting = "Connecting",
8939
+ Connected = "Connected"
8940
+ }
8941
+ /**
8942
+ * Handler for connection status changes
8943
+ */
8944
+ type ConnectionStatusChangedHandler = (status: ConnectionStatus, error: Error | null) => void;
8945
+ /**
8946
+ * Log levels for WebSocket debugging
8947
+ */
8948
+ declare enum LogLevel {
8949
+ Debug = "debug",
8950
+ Info = "info",
8951
+ Warn = "warn",
8952
+ Error = "error"
8953
+ }
8954
+
8955
+ /**
8956
+ * Conversation Service Model
8957
+ *
8958
+ * This interface defines the HTTP CRUD operations for conversations
8959
+ * and real-time WebSocket session management.
8960
+ */
8961
+
8962
+ /**
8963
+ * Methods interface for session operations.
8964
+ * This allows the conversation object to access session methods without
8965
+ * depending on the full ConversationService implementation.
8966
+ */
8967
+ interface ConversationSessionMethods {
8968
+ /**
8969
+ * Starts a real-time chat session for a conversation
8970
+ */
8971
+ startSession(conversationId: string, options?: ConversationSessionOptions): SessionStream;
8972
+ /**
8973
+ * Gets an active session for a conversation
8974
+ */
8975
+ getSession(conversationId: string): SessionStream | undefined;
8976
+ /**
8977
+ * Ends an active session for a conversation
8978
+ */
8979
+ endSession(conversationId: string): void;
8980
+ }
8981
+ /**
8982
+ * Service for creating and managing conversations with UiPath Conversational Agents
8983
+ *
8984
+ * A conversation is a long-lived interaction with a specific agent with shared context.
8985
+ * It persists across sessions and can be resumed at any time. To retrieve the
8986
+ * conversation history, use the {@link ExchangeServiceModel | Exchanges} service.
8987
+ * For real-time chat, see {@link SessionStream | Session}.
8988
+ *
8989
+ * ### Usage
8990
+ *
8991
+ * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize)
8992
+ *
8993
+ * ```typescript
8994
+ * import { ConversationalAgent } from '@uipath/uipath-typescript/conversational-agent';
8995
+ *
8996
+ * const conversationalAgent = new ConversationalAgent(sdk);
8997
+ *
8998
+ * // Access conversations through the main service
8999
+ * const conversation = await conversationalAgent.conversations.create(agentId, folderId);
9000
+ *
9001
+ * // Or through agent objects (agentId/folderId auto-filled)
9002
+ * const agents = await conversationalAgent.getAll();
9003
+ * const agentConversation = await agents[0].conversations.create({ label: 'My Chat' });
9004
+ * ```
9005
+ */
9006
+ interface ConversationServiceModel {
9007
+ /**
9008
+ * Creates a new conversation
9009
+ *
9010
+ * The returned conversation has bound methods for lifecycle management:
9011
+ * `update()`, `delete()`, and `startSession()`.
9012
+ *
9013
+ * @param agentId - The agent ID to create the conversation for
9014
+ * @param folderId - The folder ID containing the agent
9015
+ * @param options - Optional settings for the conversation
9016
+ * @returns Promise resolving to {@link ConversationCreateResponse} with bound methods
9017
+ *
9018
+ * @example
9019
+ * ```typescript
9020
+ * const conversation = await conversationalAgent.conversations.create(
9021
+ * agentId,
9022
+ * folderId,
9023
+ * { label: 'Customer Support Session' }
9024
+ * );
9025
+ *
9026
+ * // Update the conversation
9027
+ * await conversation.update({ label: 'Renamed Chat' });
9028
+ *
9029
+ * // Start a real-time session
9030
+ * const session = conversation.startSession();
9031
+ *
9032
+ * // Delete the conversation
9033
+ * await conversation.delete();
9034
+ * ```
9035
+ */
9036
+ create(agentId: number, folderId: number, options?: ConversationCreateOptions): Promise<ConversationCreateResponse>;
9037
+ /**
9038
+ * Gets all conversations with optional filtering and pagination
9039
+ *
9040
+ * @param options - Options for querying conversations including optional pagination parameters
9041
+ * @returns Promise resolving to either an array of conversations NonPaginatedResponse<ConversationGetResponse> or a PaginatedResponse<ConversationGetResponse> when pagination options are used
9042
+ *
9043
+ * @example Basic usage - get all conversations
9044
+ * ```typescript
9045
+ * const allConversations = await conversationalAgent.conversations.getAll();
9046
+ *
9047
+ * for (const conversation of allConversations.items) {
9048
+ * console.log(`${conversation.label} - created: ${conversation.createdTime}`);
9049
+ * }
9050
+ * ```
9051
+ *
9052
+ * @example With pagination
9053
+ * ```typescript
9054
+ * // First page
9055
+ * const firstPage = await conversationalAgent.conversations.getAll({ pageSize: 10 });
9056
+ *
9057
+ * // Navigate using cursor
9058
+ * if (firstPage.hasNextPage) {
9059
+ * const nextPage = await conversationalAgent.conversations.getAll({
9060
+ * cursor: firstPage.nextCursor
9061
+ * });
9062
+ * }
9063
+ * ```
9064
+ *
9065
+ * @example Sorted with limit
9066
+ * ```typescript
9067
+ * const result = await conversationalAgent.conversations.getAll({
9068
+ * sort: SortOrder.Descending,
9069
+ * pageSize: 20
9070
+ * });
9071
+ * ```
9072
+ */
9073
+ getAll<T extends ConversationGetAllOptions = ConversationGetAllOptions>(options?: T): Promise<T extends HasPaginationOptions<T> ? PaginatedResponse<ConversationGetResponse> : NonPaginatedResponse<ConversationGetResponse>>;
9074
+ /**
9075
+ * Gets a conversation by ID
9076
+ *
9077
+ * The returned conversation has bound methods for lifecycle management:
9078
+ * `update()`, `delete()`, and `startSession()`.
9079
+ *
9080
+ * @param id - The conversation ID to retrieve
9081
+ * @returns Promise resolving to {@link ConversationGetResponse} with bound methods
9082
+ *
9083
+ * @example Resume with a real-time session
9084
+ * ```typescript
9085
+ * const conversation = await conversationalAgent.conversations.getById(conversationId);
9086
+ * const session = conversation.startSession();
9087
+ * ```
9088
+ *
9089
+ * @example
9090
+ * ```typescript
9091
+ * //Retrieve conversation history
9092
+ * const conversation = await conversationalAgent.conversations.getById(conversationId);
9093
+ * const allExchanges = await conversation.exchanges.getAll();
9094
+ * for (const exchange of allExchanges.items) {
9095
+ * for (const message of exchange.messages) {
9096
+ * console.log(`${message.role}: ${message.contentParts.map(p => p.data).join('')}`);
9097
+ * }
9098
+ * }
9099
+ * ```
9100
+ */
9101
+ getById(id: string): Promise<ConversationGetResponse>;
9102
+ /**
9103
+ * Updates a conversation by ID
9104
+ *
9105
+ * @param id - The conversation ID to update
9106
+ * @param options - Fields to update
9107
+ * @returns Promise resolving to {@link ConversationGetResponse} with bound methods
9108
+ * @example
9109
+ * ```typescript
9110
+ * const updatedConversation = await conversationalAgent.conversations.updateById(conversationId, {
9111
+ * label: 'Updated Name'
9112
+ * });
9113
+ * ```
9114
+ */
9115
+ updateById(id: string, options: ConversationUpdateOptions): Promise<ConversationUpdateResponse>;
9116
+ /**
9117
+ * Deletes a conversation by ID
9118
+ *
9119
+ * @param id - The conversation ID to delete
9120
+ * @returns Promise resolving to {@link ConversationDeleteResponse}
9121
+ * @example
9122
+ * ```typescript
9123
+ * await conversationalAgent.conversations.deleteById(conversationId);
9124
+ * ```
9125
+ */
9126
+ deleteById(id: string): Promise<ConversationDeleteResponse>;
9127
+ /**
9128
+ * Uploads a file attachment to a conversation
9129
+ *
9130
+ * @param id - The ID of the conversation to attach the file to
9131
+ * @param file - The file to upload
9132
+ * @returns Promise resolving to attachment metadata with URI
9133
+ * {@link ConversationAttachmentUploadResponse}
9134
+ *
9135
+ * @example
9136
+ * ```typescript
9137
+ * const attachment = await conversationalAgent.conversations.uploadAttachment(conversationId, file);
9138
+ * console.log(`Uploaded: ${attachment.uri}`);
9139
+ * ```
9140
+ */
9141
+ uploadAttachment(id: string, file: File): Promise<ConversationAttachmentUploadResponse>;
9142
+ /**
9143
+ * Starts a real-time chat session for a conversation
9144
+ *
9145
+ * Creates a WebSocket session and returns a SessionStream for sending
9146
+ * and receiving messages in real-time.
9147
+ *
9148
+ * @param conversationId - The conversation ID to start the session for
9149
+ * @param options - Optional session configuration
9150
+ * @returns SessionStream for managing the session
9151
+ *
9152
+ * @example
9153
+ * ```typescript
9154
+ * const session = conversationalAgent.conversations.startSession(conversation.id);
9155
+ *
9156
+ * // Listen for responses using helper methods
9157
+ * session.onExchangeStart((exchange) => {
9158
+ * exchange.onMessageStart((message) => {
9159
+ * // Use message.isAssistant to filter AI responses
9160
+ * if (message.isAssistant) {
9161
+ * message.onContentPartStart((part) => {
9162
+ * // Use part.isMarkdown to handle text content
9163
+ * if (part.isMarkdown) {
9164
+ * part.onChunk((chunk) => console.log(chunk.data));
9165
+ * }
9166
+ * });
9167
+ * }
9168
+ * });
9169
+ * });
9170
+ *
9171
+ * // Wait for session to be ready, then send a message
9172
+ * session.onSessionStarted(() => {
9173
+ * const exchange = session.startExchange();
9174
+ * exchange.sendMessageWithContentPart({ data: 'Hello!' });
9175
+ * });
9176
+ *
9177
+ * // End the session when done
9178
+ * conversationalAgent.conversations.endSession(conversation.id);
9179
+ * ```
9180
+ */
9181
+ startSession(conversationId: string, options?: ConversationSessionOptions): SessionStream;
9182
+ /**
9183
+ * Retrieves an active session by conversation ID
9184
+ *
9185
+ * @param conversationId - The conversation ID to get the session for
9186
+ * @returns The session helper if active, undefined otherwise
9187
+ *
9188
+ * @example
9189
+ * ```typescript
9190
+ * const session = conversationalAgent.conversations.getSession(conversationId);
9191
+ * if (session) {
9192
+ * // Session already started — safe to send exchanges directly
9193
+ * const exchange = session.startExchange();
9194
+ * exchange.sendMessageWithContentPart({ data: 'Hello!' });
9195
+ * }
9196
+ * ```
9197
+ */
9198
+ getSession(conversationId: string): SessionStream | undefined;
9199
+ /**
9200
+ * Ends an active session for a conversation
9201
+ *
9202
+ * Sends a session end event and releases the socket for the conversation.
9203
+ * If no active session exists for the given conversation, this is a no-op.
9204
+ *
9205
+ * @param conversationId - The conversation ID to end the session for
9206
+ *
9207
+ * @example
9208
+ * ```typescript
9209
+ * // End session for a specific conversation
9210
+ * conversationalAgent.conversations.endSession(conversationId);
9211
+ * ```
9212
+ */
9213
+ endSession(conversationId: string): void;
9214
+ /**
9215
+ * Iterator over all active sessions
9216
+ * @internal
9217
+ */
9218
+ readonly sessions: Iterable<SessionStream>;
9219
+ /**
9220
+ * Current connection status
9221
+ * @internal
9222
+ */
9223
+ readonly connectionStatus: ConnectionStatus;
9224
+ /**
9225
+ * Whether WebSocket is connected
9226
+ * @internal
9227
+ */
9228
+ readonly isConnected: boolean;
9229
+ /**
9230
+ * Current connection error, if any
9231
+ * @internal
9232
+ */
9233
+ readonly connectionError: Error | null;
9234
+ /**
9235
+ * Registers a handler for connection status changes
9236
+ * @internal
9237
+ */
9238
+ onConnectionStatusChanged(handler: ConnectionStatusChangedHandler): () => void;
9239
+ }
9240
+ /**
9241
+ * Methods interface that will be added to conversation objects
9242
+ */
9243
+ interface ConversationMethods {
9244
+ /** Scoped exchange operations for this conversation */
9245
+ readonly exchanges: ConversationExchangeServiceModel;
9246
+ /**
9247
+ * Updates this conversation
9248
+ *
9249
+ * @param options - Fields to update
9250
+ * @returns Promise resolving to the updated conversation
9251
+ */
9252
+ update(options: ConversationUpdateOptions): Promise<ConversationUpdateResponse>;
9253
+ /**
9254
+ * Deletes this conversation
9255
+ *
9256
+ * @returns Promise resolving to the deletion response
9257
+ */
9258
+ delete(): Promise<ConversationDeleteResponse>;
9259
+ /**
9260
+ * Starts a real-time chat session for this conversation
9261
+ *
9262
+ * Creates a WebSocket session and returns a SessionStream for sending
9263
+ * and receiving messages in real-time.
9264
+ *
9265
+ * @param options - Optional session options
9266
+ * @returns SessionStream for managing the session
9267
+ *
9268
+ * @example
9269
+ * ```typescript
9270
+ * const conversation = await conversationalAgent.conversations.create(agentId, folderId);
9271
+ *
9272
+ * // Start a real-time session
9273
+ * const session = conversation.startSession();
9274
+ *
9275
+ * // Listen for responses using helper methods
9276
+ * session.onExchangeStart((exchange) => {
9277
+ * exchange.onMessageStart((message) => {
9278
+ * // Filter for assistant messages
9279
+ * if (message.isAssistant) {
9280
+ * message.onContentPartStart((part) => {
9281
+ * // Handle text content
9282
+ * if (part.isMarkdown) {
9283
+ * part.onChunk((chunk) => console.log(chunk.data));
9284
+ * }
9285
+ * });
9286
+ * }
9287
+ * });
9288
+ * });
9289
+ *
9290
+ * // Wait for session to be ready, then send a message
9291
+ * session.onSessionStarted(() => {
9292
+ * const exchange = session.startExchange();
9293
+ * exchange.sendMessageWithContentPart({ data: 'Hello!' });
9294
+ * });
9295
+ * ```
9296
+ */
9297
+ startSession(options?: ConversationSessionOptions): SessionStream;
9298
+ /**
9299
+ * Gets the active session for this conversation
9300
+ *
9301
+ * @returns The session helper if active, undefined otherwise
9302
+ *
9303
+ * @example
9304
+ * ```typescript
9305
+ * const session = conversation.getSession();
9306
+ * if (session) {
9307
+ * // Session already started — safe to send exchanges directly
9308
+ * const exchange = session.startExchange();
9309
+ * exchange.sendMessageWithContentPart({ data: 'Hello!' });
9310
+ * }
9311
+ * ```
9312
+ */
9313
+ getSession(): SessionStream | undefined;
9314
+ /**
9315
+ * Ends the active session for this conversation
9316
+ *
9317
+ * Sends a session end event and cleans up the session resources.
9318
+ *
9319
+ * @example
9320
+ * ```typescript
9321
+ * // End the session when done
9322
+ * conversation.endSession();
9323
+ * ```
9324
+ */
9325
+ endSession(): void;
9326
+ /**
9327
+ * Uploads a file attachment to this conversation
9328
+ *
9329
+ * @param file - The file to upload
9330
+ * @returns Promise resolving to attachment metadata with URI
9331
+ * {@link ConversationAttachmentUploadResponse}
9332
+ *
9333
+ * @example
9334
+ * ```typescript
9335
+ * const attachment = await conversation.uploadAttachment(file);
9336
+ * console.log(`Uploaded: ${attachment.uri}`);
9337
+ * ```
9338
+ */
9339
+ uploadAttachment(file: File): Promise<ConversationAttachmentUploadResponse>;
9340
+ }
9341
+ /**
9342
+ * Conversation combining {@link RawConversationGetResponse} metadata with {@link ConversationMethods} for lifecycle management
9343
+ */
9344
+ type ConversationGetResponse = RawConversationGetResponse & ConversationMethods;
9345
+ /**
9346
+ * Creates an actionable conversation by combining API conversation data with operational methods.
9347
+ *
9348
+ * @param conversationData - The conversation data from API
9349
+ * @param service - The conversation service instance
9350
+ * @param sessionMethods - Optional session methods for WebSocket session operations
9351
+ * @param exchangeService - Optional exchange service for scoped exchange methods
9352
+ * @returns A conversation object with added methods
9353
+ */
9354
+ declare function createConversationWithMethods(conversationData: RawConversationGetResponse, service: ConversationServiceModel, sessionMethods?: ConversationSessionMethods, exchangeService?: ExchangeServiceModel): ConversationGetResponse;
9355
+
9356
+ /**
9357
+ * Types for Conversation Service
9358
+ */
9359
+
9360
+ /**
9361
+ * Options for starting a session on a conversation object.
9362
+ * Unlike SessionStartEventOptions, conversationId is not needed since it's implicit from the conversation.
9363
+ */
9364
+ interface ConversationSessionOptions {
9365
+ /**
9366
+ * When set, causes events emitted to also be dispatched to event handlers.
9367
+ * This option is useful when the event helper objects are bound to UI components
9368
+ * as it allows a single code path for rendering both user and assistant messages.
9369
+ */
9370
+ echo?: boolean;
9371
+ /**
9372
+ * Sets the log level for WebSocket session debugging.
9373
+ * When set, enables logging at the specified level for the underlying WebSocket connection.
9374
+ *
9375
+ * @example
9376
+ * ```typescript
9377
+ * import { LogLevel } from '@uipath/uipath-typescript/conversational-agent';
9378
+ *
9379
+ * const session = conversation.startSession({ logLevel: LogLevel.Debug });
9380
+ * ```
9381
+ */
9382
+ logLevel?: LogLevel;
9383
+ }
9384
+ /** Response for creating a conversation (includes methods) */
9385
+ type ConversationCreateResponse = ConversationGetResponse;
9386
+ /** Response for updating a conversation (includes methods) */
9387
+ type ConversationUpdateResponse = ConversationGetResponse;
9388
+ /** Response for deleting a conversation (raw data, no methods needed) */
9389
+ type ConversationDeleteResponse = RawConversationGetResponse;
9390
+ interface ConversationCreateOptions {
9391
+ /** Human-readable label for the conversation (max 100 chars) */
9392
+ label?: string;
9393
+ /** Whether the label should be auto-generated and updated after exchanges */
9394
+ autogenerateLabel?: boolean;
9395
+ /** Trace identifier for distributed tracing */
9396
+ traceId?: string;
9397
+ /** Optional configuration for job start behavior */
9398
+ jobStartOverrides?: ConversationJobStartOverrides;
9399
+ }
9400
+ interface ConversationUpdateOptions {
9401
+ /** Human-readable label for the conversation */
9402
+ label?: string;
9403
+ /** Whether the label should be auto-generated and updated after exchanges */
9404
+ autogenerateLabel?: boolean;
9405
+ /** The key of the current/latest job serving the conversation */
9406
+ jobKey?: string;
9407
+ /** Whether the conversation's job is running locally */
9408
+ isLocalJobExecution?: boolean;
9409
+ }
9410
+ type ConversationGetAllOptions = PaginationOptions & {
9411
+ /** Sort order for conversations */
9412
+ sort?: SortOrder;
9413
+ };
9414
+ /**
9415
+ * File upload access details for uploading file content to blob storage
9416
+ */
9417
+ interface FileUploadAccess {
9418
+ /** URL to upload the file to */
9419
+ url: string;
9420
+ /** HTTP verb to use (e.g., 'PUT') */
9421
+ verb: string;
9422
+ /** Headers to include in the upload request */
9423
+ headers: {
9424
+ keys: string[];
9425
+ values: string[];
9426
+ };
9427
+ /** Whether authentication is required for the upload */
9428
+ requiresAuth?: boolean;
9429
+ }
9430
+ /**
9431
+ * Response for creating a file attachment entry
9432
+ *
9433
+ * Contains the attachment URI and upload access details for uploading
9434
+ * the file content to blob storage.
9435
+ */
9436
+ interface ConversationAttachmentCreateResponse {
9437
+ /** URI to reference this attachment in messages */
9438
+ uri: string;
9439
+ /** File name */
9440
+ name: string;
9441
+ /** Details for uploading the file content */
9442
+ fileUploadAccess: FileUploadAccess;
9443
+ }
9444
+ /**
9445
+ * Response for uploading an attachment (after file content is uploaded)
9446
+ */
9447
+ interface ConversationAttachmentUploadResponse {
9448
+ /** URI to reference this attachment in messages */
9449
+ uri: string;
9450
+ /** File name */
9451
+ name: string;
9452
+ /** MIME type of the uploaded file */
9453
+ mimeType: string;
9454
+ }
9455
+
9456
+ /**
9457
+ * Message Service Model
9458
+ */
9459
+
9460
+ /**
9461
+ * Service for retrieving individual messages within an {@link ExchangeServiceModel | Exchange}
9462
+ *
9463
+ * A message is a single turn from a user, assistant, or system. Each message includes
9464
+ * a role, contentParts (text, audio, images), toolCalls, and interrupts.
9465
+ * Messages are also returned as part of exchange responses — use this service
9466
+ * when you need to fetch a specific message by ID or retrieve external content parts.
9467
+ * For real-time streaming of messages, see {@link MessageStream}.
9468
+ *
9469
+ * ### Usage
9470
+ *
9471
+ * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize)
9472
+ *
9473
+ * ```typescript
9474
+ * import { Messages } from '@uipath/uipath-typescript/conversational-agent';
9475
+ *
9476
+ * const message = new Messages(sdk);
9477
+ * const messageDetails = await message.getById(conversationId, exchangeId, messageId);
9478
+ * ```
9479
+ */
9480
+ interface MessageServiceModel {
9481
+ /**
9482
+ * Gets a message by ID
9483
+ *
9484
+ * Returns the message including its content parts, tool calls, and interrupts.
9485
+ *
9486
+ * @param conversationId - The conversation containing the message
9487
+ * @param exchangeId - The exchange containing the message
9488
+ * @param messageId - The message ID to retrieve
9489
+ * @returns Promise resolving to {@link MessageGetResponse}
9490
+ * @example
9491
+ * ```typescript
9492
+ * const message = await messages.getById(conversationId, exchangeId, messageId);
9493
+ *
9494
+ * console.log(message.role);
9495
+ * console.log(message.contentParts);
9496
+ * console.log(message.toolCalls);
9497
+ * ```
9498
+ */
9499
+ getById(conversationId: string, exchangeId: string, messageId: string): Promise<MessageGetResponse>;
9500
+ /**
9501
+ * Gets an external content part by ID
9502
+ *
9503
+ * @param conversationId - The conversation containing the content
9504
+ * @param exchangeId - The exchange containing the content
9505
+ * @param messageId - The message containing the content part
9506
+ * @param contentPartId - The content part ID to retrieve
9507
+ * @returns Promise resolving to {@link ContentPartGetResponse}
9508
+ * @example
9509
+ * ```typescript
9510
+ * const contentPart = await messages.getContentPartById(
9511
+ * conversationId,
9512
+ * exchangeId,
9513
+ * messageId,
9514
+ * contentPartId
9515
+ * );
9516
+ * ```
9517
+ */
9518
+ getContentPartById(conversationId: string, exchangeId: string, messageId: string, contentPartId: string): Promise<ContentPartGetResponse>;
9519
+ }
9520
+
9521
+ /**
9522
+ * Types for Agent Service
9523
+ */
9524
+ /**
9525
+ * Starting prompt configuration for an agent
9526
+ */
9527
+ interface AgentStartingPrompt {
9528
+ /** The prompt text displayed to the user */
9529
+ displayPrompt: string;
9530
+ /** The actual prompt sent when selected */
9531
+ actualPrompt: string;
9532
+ /** Unique identifier for the prompt */
9533
+ id: string;
9534
+ }
9535
+ /**
9536
+ * Agent appearance configuration
9537
+ */
9538
+ interface AgentAppearance {
9539
+ /** Welcome title displayed to users */
9540
+ welcomeTitle?: string;
9541
+ /** Welcome description displayed to users */
9542
+ welcomeDescription?: string;
9543
+ /** Starting prompts for users to choose from */
9544
+ startingPrompts?: AgentStartingPrompt[];
9545
+ }
9546
+ /**
9547
+ * Raw API response for getting all agents
9548
+ */
9549
+ interface RawAgentGetResponse {
9550
+ /** Unique ID of the agent */
9551
+ id: number;
9552
+ /** Display name of the agent */
9553
+ name: string;
9554
+ /** Agent description */
9555
+ description: string;
9556
+ /** Process version */
9557
+ processVersion: string;
9558
+ /** Process key identifier */
9559
+ processKey: string;
9560
+ /** Folder ID */
9561
+ folderId: number;
9562
+ /** Feed ID */
9563
+ feedId: string;
9564
+ /** Creation timestamp */
9565
+ createdTime?: string;
9566
+ }
9567
+ /**
9568
+ * Raw API response for getting a single agent by ID - includes appearance configuration
9569
+ */
9570
+ interface RawAgentGetByIdResponse extends RawAgentGetResponse {
9571
+ /** Agent appearance configuration */
9572
+ appearance?: AgentAppearance;
9573
+ }
9574
+
9575
+ /**
9576
+ * Agent Service Models
9577
+ *
9578
+ * Provides fluent API for agent objects returned from getAll() and getById().
9579
+ */
9580
+
9581
+ /**
9582
+ * Options for creating a conversation from an agent
9583
+ */
9584
+ type AgentCreateConversationOptions = ConversationCreateOptions;
9585
+ /**
9586
+ * Scoped conversation service for a specific agent.
9587
+ * Auto-fills agentId and folderId from the agent.
9588
+ */
9589
+ interface AgentConversationServiceModel {
9590
+ /**
9591
+ * Creates a conversation for this agent
9592
+ *
9593
+ * @param options - Optional conversation options (label, etc.)
9594
+ * @returns Promise resolving to the created conversation with methods
9595
+ *
9596
+ * @example
9597
+ * ```typescript
9598
+ * const agent = (await conversationalAgent.getAll())[0];
9599
+ * const conversation = await agent.conversations.create({ label: 'My Chat' });
9600
+ * const session = conversation.startSession();
9601
+ * ```
9602
+ */
9603
+ create(options?: AgentCreateConversationOptions): Promise<ConversationCreateResponse>;
9604
+ }
9605
+ /**
9606
+ * Methods added to agent objects
9607
+ */
9608
+ interface AgentMethods {
9609
+ /** Scoped conversation operations for this agent */
9610
+ readonly conversations: AgentConversationServiceModel;
9611
+ /** Current WebSocket connection status */
9612
+ get connectionStatus(): ConnectionStatus;
9613
+ /** Whether the WebSocket connection is currently active */
9614
+ get isConnected(): boolean;
9615
+ /** Current connection error, or `null` if none */
9616
+ get connectionError(): Error | null;
9617
+ }
9618
+ /**
9619
+ * Agent combining {@link RawAgentGetResponse} metadata with {@link AgentMethods} for conversation and connection management
9620
+ */
9621
+ type AgentGetResponse = RawAgentGetResponse & AgentMethods;
9622
+ /**
9623
+ * Agent combining {@link RawAgentGetByIdResponse} metadata with {@link AgentMethods} for conversation and connection management
9624
+ */
9625
+ type AgentGetByIdResponse = RawAgentGetByIdResponse & AgentMethods;
9626
+ declare function createAgentWithMethods<T extends RawAgentGetResponse>(agentData: T, conversationService: ConversationServiceModel): T & AgentMethods;
9627
+
9628
+ /**
9629
+ * Constants for Agent Service
9630
+ */
9631
+ /**
9632
+ * Maps fields for Agent entities to ensure consistent SDK naming
9633
+ */
9634
+ declare const AgentMap: {
9635
+ [key: string]: string;
9636
+ };
9637
+
9638
+ /**
9639
+ * Types for User Service
9640
+ */
9641
+ /**
9642
+ * Response for getting user settings
9643
+ *
9644
+ * Contains profile and context information that is passed to the agent
9645
+ * for all conversations to provide user context.
9646
+ *
9647
+ * @example
9648
+ * ```typescript
9649
+ * const userSettings = await conversationalAgentService.user.getSettings();
9650
+ * console.log(userSettings.name, userSettings.email);
9651
+ * ```
9652
+ */
9653
+ interface UserSettingsGetResponse {
9654
+ /** Unique identifier of the user (UUID) */
9655
+ userId: string;
9656
+ /** Name of the user (max 100 chars) */
9657
+ name: string | null;
9658
+ /** Email address (max 255 chars, must be valid email) */
9659
+ email: string | null;
9660
+ /** Role of the user (max 100 chars) */
9661
+ role: string | null;
9662
+ /** Department (max 100 chars) */
9663
+ department: string | null;
9664
+ /** Company (max 100 chars) */
9665
+ company: string | null;
9666
+ /** Country (max 100 chars) */
9667
+ country: string | null;
9668
+ /** Timezone (max 50 chars) */
9669
+ timezone: string | null;
9670
+ /** UTC timestamp of creation */
9671
+ createdTime: string;
9672
+ /** UTC timestamp of last update */
9673
+ updatedTime: string;
9674
+ }
9675
+ /** Response for updating user settings */
9676
+ type UserSettingsUpdateResponse = UserSettingsGetResponse;
9677
+ /**
9678
+ * Options for updating user settings
9679
+ *
9680
+ * All fields are optional - only send the fields you want to change.
9681
+ * Set fields to `null` to explicitly clear them.
9682
+ * Omitting fields means no change.
9683
+ *
9684
+ * @example
9685
+ * ```typescript
9686
+ * // Update specific fields
9687
+ * await conversationalAgentService.user.updateSettings({
9688
+ * name: 'John Doe',
9689
+ * timezone: 'America/New_York'
9690
+ * });
9691
+ *
9692
+ * // Clear a field by setting to null
9693
+ * await conversationalAgentService.user.updateSettings({
9694
+ * department: null
9695
+ * });
9696
+ * ```
9697
+ */
9698
+ interface UserSettingsUpdateOptions {
9699
+ /** Name of the user (max 100 chars) */
9700
+ name?: string | null;
9701
+ /** Email address (max 255 chars, must be valid email) */
9702
+ email?: string | null;
9703
+ /** Role of the user (max 100 chars) */
9704
+ role?: string | null;
9705
+ /** Department (max 100 chars) */
9706
+ department?: string | null;
9707
+ /** Company (max 100 chars) */
9708
+ company?: string | null;
9709
+ /** Country (max 100 chars) */
9710
+ country?: string | null;
9711
+ /** Timezone (max 50 chars) */
9712
+ timezone?: string | null;
9713
+ }
9714
+
9715
+ /**
9716
+ * Service for managing UiPath User Settings
9717
+ *
9718
+ * User settings are passed to the agent for all conversations
9719
+ * to provide user context (name, email, role, timezone, etc.).
9720
+ *
9721
+ * @internal
9722
+ */
9723
+ interface UserServiceModel {
9724
+ /**
9725
+ * Gets the current user's profile and context settings
9726
+ *
9727
+ * @returns Promise resolving to user settings object
9728
+ * {@link UserSettingsGetResponse}
9729
+ * @example
9730
+ * ```typescript
9731
+ * const userSettings = await userService.getSettings();
9732
+ * console.log(userSettings.name);
9733
+ * console.log(userSettings.email);
9734
+ * ```
9735
+ */
9736
+ getSettings(): Promise<UserSettingsGetResponse>;
9737
+ /**
9738
+ * Updates the current user's profile and context settings
9739
+ *
9740
+ * @param options - Fields to update
9741
+ * @returns Promise resolving to updated user settings
9742
+ * {@link UserSettingsUpdateResponse}
9743
+ * @example
9744
+ * ```typescript
9745
+ * const updatedUserSettings = await userService.updateSettings({
9746
+ * name: 'John Doe',
9747
+ * timezone: 'America/New_York'
9748
+ * });
9749
+ * ```
9750
+ */
9751
+ updateSettings(options: UserSettingsUpdateOptions): Promise<UserSettingsUpdateResponse>;
9752
+ }
9753
+
9754
+ /**
9755
+ * Constants for User Service
9756
+ */
9757
+ /**
9758
+ * Maps fields for User Settings entities to ensure consistent SDK naming
9759
+ */
9760
+ declare const UserSettingsMap: {
9761
+ [key: string]: string;
9762
+ };
9763
+
9764
+ /**
9765
+ * Types for Feature Flags
9766
+ */
9767
+ /**
9768
+ * Feature flags for conversational agent capabilities
9769
+ *
9770
+ * @internal
9771
+ */
9772
+ type FeatureFlags = Record<string, unknown>;
9773
+
9774
+ /**
9775
+ * Service for managing UiPath Conversational Agents — AI-powered chat interfaces that enable
9776
+ * natural language interactions with UiPath automation. Discover agents, create conversations,
9777
+ * and stream real-time responses over WebSocket. [UiPath Conversational Agents Guide](https://docs.uipath.com/agents/automation-cloud/latest/user-guide/conversational-agents)
9778
+ *
9779
+ * Prerequisites: Initialize the SDK first - see [Getting Started](/uipath-typescript/getting-started/#import-initialize)
9780
+ *
9781
+ * ## How It Works
9782
+ *
9783
+ * ### Lifecycle
9784
+ *
9785
+ * ```mermaid
9786
+ * graph TD
9787
+ * A["Agent"] -->|conversations.create| B["Conversation"]
9788
+ * B -->|startSession| C["Session"]
9789
+ * B -->|exchanges.getAll| F(["History"])
9790
+ * C -->|onSessionStarted| D["Ready"]
9791
+ * D -->|startExchange| E["Exchange"]
9792
+ * E -->|sendMessage| G["Message"]
9793
+ * ```
9794
+ *
9795
+ * ### Real-Time Event Flow
9796
+ *
9797
+ * Once a session is started, events flow through a nested stream hierarchy:
9798
+ *
9799
+ * ```mermaid
9800
+ * graph TD
9801
+ * S["SessionStream"]
9802
+ * S -->|onExchangeStart| E["ExchangeStream"]
9803
+ * S -->|onSessionEnd| SE(["session closed"])
9804
+ * E -->|onMessageStart| M["MessageStream"]
9805
+ * E -->|onExchangeEnd| EE(["exchange complete"])
9806
+ * M -->|onContentPartStart| CP["ContentPartStream"]
9807
+ * M -->|onToolCallStart| TC["ToolCallStream"]
9808
+ * M -->|onInterruptStart| IR(["awaiting approval"])
9809
+ * CP -->|onChunk| CH(["streaming data"])
9810
+ * TC -->|onToolCallEnd| TCE(["tool result"])
9811
+ * ```
9812
+ *
9813
+ * ## Usage
9814
+ *
9815
+ * ```typescript
9816
+ * import { ConversationalAgent } from '@uipath/uipath-typescript/conversational-agent';
9817
+ *
9818
+ * const conversationalAgent = new ConversationalAgent(sdk);
9819
+ *
9820
+ * // 1. Discover agents
9821
+ * const agents = await conversationalAgent.getAll();
9822
+ * const agent = agents[0];
9823
+ *
9824
+ * // 2. Create a conversation
9825
+ * const conversation = await agent.conversations.create({ label: 'My Chat' });
9826
+ *
9827
+ * // 3. Start real-time session and listen for responses
9828
+ * const session = conversation.startSession();
9829
+ *
9830
+ * session.onExchangeStart((exchange) => {
9831
+ * exchange.onMessageStart((message) => {
9832
+ * if (message.isAssistant) {
9833
+ * message.onContentPartStart((part) => {
9834
+ * if (part.isMarkdown) {
9835
+ * part.onChunk((chunk) => process.stdout.write(chunk.data ?? ''));
9836
+ * }
9837
+ * });
9838
+ * }
9839
+ * });
9840
+ * });
9841
+ *
9842
+ * // 4. Wait for session to be ready, then send a message
9843
+ * session.onSessionStarted(() => {
9844
+ * const exchange = session.startExchange();
9845
+ * exchange.sendMessageWithContentPart({ data: 'Hello!' });
9846
+ * });
9847
+ *
9848
+ * // 5. End session when done
9849
+ * conversation.endSession();
9850
+ *
9851
+ * // 6. Retrieve conversation history (offline)
9852
+ * const exchanges = await conversation.exchanges.getAll();
9853
+ * ```
9854
+ */
9855
+ interface ConversationalAgentServiceModel {
9856
+ /**
9857
+ * Gets all available conversational agents
9858
+ *
9859
+ * @param folderId - Optional folder ID to filter agents
9860
+ * @returns Promise resolving to an array of agents
9861
+ * {@link AgentGetResponse}
9862
+ *
9863
+ * @example Basic usage
9864
+ * ```typescript
9865
+ * const agents = await conversationalAgent.getAll();
9866
+ * const agent = agents[0];
9867
+ *
9868
+ * // Create conversation directly from agent (agentId and folderId are auto-filled)
9869
+ * const conversation = await agent.conversations.create({ label: 'My Chat' });
9870
+ * ```
9871
+ *
9872
+ * @example Filter agents by folder
9873
+ * ```typescript
9874
+ * const agents = await conversationalAgent.getAll(folderId);
9875
+ * ```
9876
+ */
9877
+ getAll(folderId?: number): Promise<AgentGetResponse[]>;
9878
+ /**
9879
+ * Gets a specific agent by ID
9880
+ *
9881
+ * @param id - ID of the agent release
9882
+ * @param folderId - ID of the folder containing the agent
9883
+ * @returns Promise resolving to the agent
9884
+ * {@link AgentGetByIdResponse}
9885
+ *
9886
+ * @example Basic usage
9887
+ * ```typescript
9888
+ * const agent = await conversationalAgent.getById(agentId, folderId);
9889
+ *
9890
+ * // Create conversation directly from agent (agentId and folderId are auto-filled)
9891
+ * const conversation = await agent.conversations.create({ label: 'My Chat' });
9892
+ * ```
9893
+ */
9894
+ getById(id: number, folderId: number): Promise<AgentGetByIdResponse>;
9895
+ /**
9896
+ * Registers a handler that is called whenever the WebSocket connection status changes.
9897
+ *
9898
+ * @param handler - Callback receiving a {@link ConnectionStatus} (`'Disconnected'` | `'Connecting'` | `'Connected'`) and an optional `Error`
9899
+ * @returns Cleanup function to remove the handler
9900
+ *
9901
+ * @example
9902
+ * ```typescript
9903
+ * const cleanup = conversationalAgent.onConnectionStatusChanged((status, error) => {
9904
+ * console.log('Connection status:', status);
9905
+ * if (error) {
9906
+ * console.error('Connection error:', error.message);
9907
+ * }
9908
+ * });
9909
+ *
9910
+ * // Later, remove the handler
9911
+ * cleanup();
9912
+ * ```
9913
+ */
9914
+ onConnectionStatusChanged(handler: (status: ConnectionStatus, error: Error | null) => void): () => void;
9915
+ /** Service for creating and managing conversations. See {@link ConversationServiceModel}. */
9916
+ readonly conversations: ConversationServiceModel;
9917
+ /**
9918
+ * Gets feature flags for the current tenant
9919
+ *
9920
+ * @internal
9921
+ */
9922
+ getFeatureFlags(): Promise<FeatureFlags>;
9923
+ }
9924
+
9925
+ /**
9926
+ * Options for ConversationalAgentService constructor
9927
+ */
9928
+ interface ConversationalAgentOptions {
9929
+ /** External User ID (optional) */
9930
+ externalUserId?: string;
9931
+ /** Log level for debugging */
9932
+ logLevel?: LogLevel;
9933
+ }
9934
+
9935
+ /**
9936
+ * Error thrown when authorization fails (403 errors)
9937
+ * Common scenarios:
9938
+ * - Insufficient permissions
9939
+ * - Access denied to resource
9940
+ * - Invalid scope
9941
+ */
9942
+ declare class AuthorizationError extends UiPathError {
9943
+ constructor(params?: Partial<ErrorParams>);
9944
+ }
9945
+
9946
+ /**
9947
+ * Error thrown when validation fails (400 errors or client-side validation)
9948
+ * Common scenarios:
9949
+ * - Invalid input parameters
9950
+ * - Missing required fields
9951
+ * - Invalid data format
9952
+ */
9953
+ declare class ValidationError extends UiPathError {
9954
+ constructor(params?: Partial<ErrorParams>);
9955
+ }
9956
+
9957
+ /**
9958
+ * Error thrown when a resource is not found (404 errors)
9959
+ * Common scenarios:
9960
+ * - Resource doesn't exist
9961
+ * - Invalid ID provided
9962
+ * - Resource deleted
9963
+ */
9964
+ declare class NotFoundError extends UiPathError {
9965
+ constructor(params?: Partial<ErrorParams>);
9966
+ }
9967
+
9968
+ /**
9969
+ * Error thrown when rate limit is exceeded (429 errors)
9970
+ * Common scenarios:
9971
+ * - Too many requests in a time window
9972
+ * - API throttling
9973
+ */
9974
+ declare class RateLimitError extends UiPathError {
9975
+ constructor(params?: Partial<ErrorParams>);
9976
+ }
9977
+
9978
+ /**
9979
+ * Error thrown when server encounters an error (5xx errors)
9980
+ * Common scenarios:
9981
+ * - Internal server error
9982
+ * - Service unavailable
9983
+ * - Gateway timeout
9984
+ */
9985
+ declare class ServerError extends UiPathError {
9986
+ constructor(params?: Partial<ErrorParams>);
9987
+ /**
9988
+ * Checks if this is a temporary error that might succeed on retry
9989
+ */
9990
+ get isRetryable(): boolean;
9991
+ }
9992
+
9993
+ /**
9994
+ * Base error creation parameters - only what's needed
9995
+ */
9996
+ interface ErrorParams {
9997
+ message: string;
9998
+ statusCode?: number;
9999
+ requestId?: string;
10000
+ }
10001
+
10002
+ /**
10003
+ * Base error class for all UiPath SDK errors
10004
+ * Extends Error for standard error handling compatibility
10005
+ */
10006
+ declare abstract class UiPathError extends Error {
10007
+ /**
10008
+ * Error type identifier (e.g., "AuthenticationError", "ValidationError")
10009
+ */
10010
+ readonly type: string;
10011
+ /**
10012
+ * HTTP status code (400, 401, 403, 404, 500, etc.)
10013
+ */
10014
+ readonly statusCode?: number;
10015
+ /**
10016
+ * Request ID for tracking with UiPath support
10017
+ */
10018
+ readonly requestId?: string;
10019
+ /**
10020
+ * Timestamp when the error occurred
10021
+ */
10022
+ readonly timestamp: Date;
5684
10023
  protected constructor(type: string, params: ErrorParams);
5685
10024
  /**
5686
10025
  * Returns a clean JSON representation of the error
@@ -5866,7 +10205,7 @@ declare const telemetryClient: TelemetryClient;
5866
10205
  * SDK Telemetry constants
5867
10206
  */
5868
10207
  declare const CONNECTION_STRING = "InstrumentationKey=a6efa11d-1feb-4508-9738-e13e12dcae5e;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=7c58eb1c-9581-4ba6-839e-11725848a037";
5869
- declare const SDK_VERSION = "1.0.0";
10208
+ declare const SDK_VERSION = "1.1.1";
5870
10209
  declare const VERSION = "Version";
5871
10210
  declare const SERVICE = "Service";
5872
10211
  declare const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
@@ -5881,5 +10220,5 @@ declare const SDK_LOGGER_NAME = "uipath-ts-sdk-telemetry";
5881
10220
  declare const SDK_RUN_EVENT = "Sdk.Run";
5882
10221
  declare const UNKNOWN = "";
5883
10222
 
5884
- export { APP_NAME, AssetValueScope, AssetValueType, AuthenticationError, AuthorizationError, BucketOptions, CLOUD_CLIENT_ID, CLOUD_ORGANIZATION_NAME, CLOUD_REDIRECT_URI, CLOUD_ROLE_NAME, CLOUD_TENANT_NAME, CLOUD_URL, CONNECTION_STRING, DEFAULT_ITEMS_FIELD, DEFAULT_PAGE_SIZE, DEFAULT_TOTAL_COUNT_FIELD, DataDirectionType, DebugMode, EntityFieldDataType, EntityType, ErrorType, EscalationActionType, EscalationRecipientScope, EscalationTriggerType, FieldDisplayType, HttpStatus, JobPriority, JobState, JobType, JoinType, MAX_PAGE_SIZE, NetworkError, NotFoundError, PackageSourceType, PackageType, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, RateLimitError, ReferenceType, RemoteControlAccess, RobotSize, SDK_LOGGER_NAME, SDK_RUN_EVENT, SDK_SERVICE_NAME, SDK_VERSION, SERVICE, SLADurationUnit, ServerError, StageTaskType, StartStrategy, StopStrategy, TargetFramework, TaskActivityType, TaskPriority, TaskSlaCriteria, TaskSlaStatus, TaskSourceName, TaskStatus, TaskType, UNKNOWN, UiPath, UiPathError, VERSION, ValidationError, createCaseInstanceWithMethods, createEntityWithMethods, createProcessInstanceWithMethods, createProcessWithMethods, createTaskWithMethods, getErrorDetails, getLimitedPageSize, isAuthenticationError, isAuthorizationError, isNetworkError, isNotFoundError, isRateLimitError, isServerError, isUiPathError, isValidationError, telemetryClient, track, trackEvent };
5885
- export type { ArgumentMetadata, AssetGetAllOptions, AssetGetByIdOptions, AssetGetResponse, AssetServiceModel, BaseConfig, BaseOptions, BlobItem, BodyOptions, BpmnXmlString, BucketGetAllOptions, BucketGetByIdOptions, BucketGetFileMetaDataOptions, BucketGetFileMetaDataResponse, BucketGetFileMetaDataWithPaginationOptions, BucketGetReadUriOptions, BucketGetResponse, BucketGetUriOptions, BucketGetUriResponse, BucketServiceModel, BucketUploadFileOptions, BucketUploadResponse, CaseAppConfig, CaseAppOverview, CaseGetAllResponse, CaseGetStageResponse, CaseInstanceExecutionHistoryResponse, CaseInstanceGetAllOptions, CaseInstanceGetAllWithPaginationOptions, CaseInstanceGetResponse, CaseInstanceMethods, CaseInstanceOperationOptions, CaseInstanceOperationResponse, CaseInstanceReopenOptions, CaseInstanceRun, CaseInstancesServiceModel, CasesServiceModel, ChoiceSetGetAllResponse, ChoiceSetGetByIdOptions, ChoiceSetGetResponse, ChoiceSetServiceModel, CollectionResponse, CustomKeyValuePair, ElementExecutionMetadata, ElementMetaData, ElementRunMetadata, EntityBatchInsertOptions, EntityBatchInsertResponse, EntityDeleteOptions, EntityDeleteRecordsOptions, EntityDeleteResponse, EntityDownloadAttachmentOptions, EntityGetAllRecordsOptions, EntityGetRecordByIdOptions, EntityGetRecordsByIdOptions, EntityGetResponse, EntityInsertOptions, EntityInsertRecordOptions, EntityInsertRecordsOptions, EntityInsertResponse, EntityMethods, EntityOperationOptions, EntityOperationResponse, EntityRecord, EntityServiceModel, EntityUpdateOptions, EntityUpdateRecordsOptions, EntityUpdateResponse, EscalationAction, EscalationRecipient, EscalationRule, EscalationTriggerMetadata, ExternalConnection, ExternalField, ExternalFieldMapping, ExternalObject, ExternalSourceFields, FailureRecord, Field, FieldDataType, FieldMetaData, FolderProperties, GlobalVariableMetaData, HasPaginationOptions, Headers, HttpMethod, JobAttachment, JobError, Machine, MaestroProcessGetAllResponse, MaestroProcessesServiceModel, NonPaginatedResponse, OAuthFields, OperationResponse, PaginatedResponse, PaginationCursor, PaginationMetadata, PaginationMethodUnion, PaginationOptions, ProcessGetAllOptions, ProcessGetByIdOptions, ProcessGetResponse, ProcessIncidentGetAllResponse, ProcessIncidentGetResponse, ProcessIncidentsServiceModel, ProcessInstanceExecutionHistoryResponse, ProcessInstanceGetAllOptions, ProcessInstanceGetAllWithPaginationOptions, ProcessInstanceGetResponse, ProcessInstanceGetVariablesOptions, ProcessInstanceGetVariablesResponse, ProcessInstanceMethods, ProcessInstanceOperationOptions, ProcessInstanceOperationResponse, ProcessInstanceRun, ProcessInstancesServiceModel, ProcessMethods, ProcessProperties, ProcessServiceModel, ProcessStartRequest, ProcessStartResponse, QueryParams, QueueGetAllOptions, QueueGetByIdOptions, QueueGetResponse, QueueServiceModel, RawCaseInstanceGetResponse, RawEntityGetResponse, RawMaestroProcessGetAllResponse, RawProcessInstanceGetResponse, RawTaskCreateResponse, RawTaskGetResponse, RequestOptions, RequestSpec, ResponseDictionary, ResponseType, RetryOptions, RobotMetadata, SourceJoinCriteria, StageSLA, StageTask, Tag, TaskActivity, TaskAssignOptions, TaskAssignment, TaskAssignmentOptions, TaskAssignmentResponse, TaskBaseResponse, TaskCompleteOptions, TaskCompletionOptions, TaskCreateOptions, TaskCreateResponse, TaskGetAllOptions, TaskGetByIdOptions, TaskGetResponse, TaskGetUsersOptions, TaskMethods, TaskServiceModel, TaskSlaDetail, TaskSource, TasksUnassignOptions, TimeoutOptions, UiPathSDKConfig, UserLoginInfo };
10223
+ export { APP_NAME, AgentMap, AssetValueScope, AssetValueType, AuthenticationError, AuthorizationError, BucketOptions, CLOUD_CLIENT_ID, CLOUD_ORGANIZATION_NAME, CLOUD_REDIRECT_URI, CLOUD_ROLE_NAME, CLOUD_TENANT_NAME, CLOUD_URL, CONNECTION_STRING, CitationErrorType, ConversationMap, DEFAULT_ITEMS_FIELD, DEFAULT_PAGE_SIZE, DEFAULT_TOTAL_COUNT_FIELD, DataDirectionType, DebugMode, EntityFieldDataType, EntityType, ErrorType, EscalationActionType, EscalationRecipientScope, EscalationTriggerType, ExchangeMap, FeedbackRating, FieldDisplayType, HttpStatus, InputStreamSpeechSensitivity, InterruptType, JobPriority, JobState, JobType, JoinType, MAX_PAGE_SIZE, MessageMap, MessageRole, NetworkError, NotFoundError, PackageSourceType, PackageType, ProcessIncidentSeverity, ProcessIncidentStatus, ProcessIncidentType, RateLimitError, ReferenceType, RemoteControlAccess, RobotSize, SDK_LOGGER_NAME, SDK_RUN_EVENT, SDK_SERVICE_NAME, SDK_VERSION, SERVICE, SLADurationUnit, ServerError, SortOrder, StageTaskType, StartStrategy, StopStrategy, TargetFramework, TaskActivityType, TaskPriority, TaskSlaCriteria, TaskSlaStatus, TaskSourceName, TaskStatus, TaskType, UNKNOWN, UiPath, UiPathError, UserSettingsMap, VERSION, ValidationError, createAgentWithMethods, createCaseInstanceWithMethods, createConversationWithMethods, createEntityWithMethods, createProcessInstanceWithMethods, createProcessWithMethods, createTaskWithMethods, getErrorDetails, getLimitedPageSize, isAuthenticationError, isAuthorizationError, isNetworkError, isNotFoundError, isRateLimitError, isServerError, isUiPathError, isValidationError, telemetryClient, track, trackEvent };
10224
+ export type { AgentAppearance, AgentConversationServiceModel, AgentCreateConversationOptions, AgentGetByIdResponse, AgentGetResponse, AgentMethods, AgentStartingPrompt, ArgumentMetadata, AssetGetAllOptions, AssetGetByIdOptions, AssetGetResponse, AssetServiceModel, AsyncInputStream, AsyncInputStreamChunkEvent, AsyncInputStreamEndEvent, AsyncInputStreamEvent, AsyncInputStreamStartEvent, AsyncToolCallStream, BaseConfig, BaseOptions, BaseProcessStartRequest, BlobItem, BodyOptions, BpmnXmlString, BucketGetAllOptions, BucketGetByIdOptions, BucketGetFileMetaDataOptions, BucketGetFileMetaDataResponse, BucketGetFileMetaDataWithPaginationOptions, BucketGetReadUriOptions, BucketGetResponse, BucketGetUriOptions, BucketGetUriResponse, BucketServiceModel, BucketUploadFileOptions, BucketUploadResponse, CaseAppConfig, CaseAppOverview, CaseGetAllResponse, CaseGetStageResponse, CaseInstanceExecutionHistoryResponse, CaseInstanceGetAllOptions, CaseInstanceGetAllWithPaginationOptions, CaseInstanceGetResponse, CaseInstanceMethods, CaseInstanceOperationOptions, CaseInstanceOperationResponse, CaseInstanceReopenOptions, CaseInstanceRun, CaseInstancesServiceModel, CasesServiceModel, ChoiceSetGetAllResponse, ChoiceSetGetByIdOptions, ChoiceSetGetResponse, ChoiceSetServiceModel, Citation, CitationEndEvent, CitationError, CitationEvent, CitationOptions, CitationSource, CitationSourceBase, CitationSourceMedia, CitationSourceUrl, CitationStartEvent, CollectionResponse, CompletedContentPart, CompletedMessage, CompletedToolCall, ContentPart, ContentPartChunkEvent, ContentPartData, ContentPartEndEvent, ContentPartEvent, ContentPartGetResponse, ContentPartInterrupted, ContentPartStartEvent, ContentPartStartMetaData, ContentPartStream, ConversationAttachmentCreateResponse, ConversationAttachmentUploadResponse, ConversationCreateOptions, ConversationCreateResponse, ConversationDeleteResponse, ConversationEvent, ConversationExchangeServiceModel, ConversationGetAllOptions, ConversationGetResponse, ConversationJobStartOverrides, ConversationMethods, ConversationServiceModel, ConversationSessionMethods, ConversationSessionOptions, ConversationUpdateOptions, ConversationUpdateResponse, ConversationalAgentOptions, ConversationalAgentServiceModel, CreateFeedbackOptions, CustomKeyValuePair, ElementExecutionMetadata, ElementMetaData, ElementRunMetadata, EntityBatchInsertOptions, EntityBatchInsertResponse, EntityDeleteOptions, EntityDeleteRecordsOptions, EntityDeleteResponse, EntityDownloadAttachmentOptions, EntityGetAllRecordsOptions, EntityGetRecordByIdOptions, EntityGetRecordsByIdOptions, EntityGetResponse, EntityInsertOptions, EntityInsertRecordOptions, EntityInsertRecordsOptions, EntityInsertResponse, EntityMethods, EntityOperationOptions, EntityOperationResponse, EntityRecord, EntityServiceModel, EntityUpdateOptions, EntityUpdateRecordsOptions, EntityUpdateResponse, ErrorEndEvent, ErrorEvent, ErrorStartEvent, EscalationAction, EscalationRecipient, EscalationRule, EscalationTriggerMetadata, Exchange, ExchangeEndEvent, ExchangeEvent, ExchangeGetAllOptions, ExchangeGetByIdOptions, ExchangeGetResponse, ExchangeServiceModel, ExchangeStartEvent, ExchangeStream, ExternalConnection, ExternalField, ExternalFieldMapping, ExternalObject, ExternalSourceFields, ExternalValue, FailureRecord, FeatureFlags, FeedbackCreateResponse, Field, FieldDataType, FieldMetaData, FileUploadAccess, FolderProperties, GenericInterruptStartEvent, GlobalVariableMetaData, HasPaginationOptions, Headers, HttpMethod, InlineOrExternalValue, InlineValue, Interrupt, InterruptEndEvent, InterruptEvent, InterruptStartEvent, JSONArray, JSONObject, JSONPrimitive, JSONValue, JobAttachment, JobError, LabelUpdatedEvent, Machine, MaestroProcessGetAllResponse, MaestroProcessesServiceModel, MakeOptional, MakeRequired, Message, MessageEndEvent, MessageEvent, MessageGetResponse, MessageServiceModel, MessageStartEvent, MessageStream, MetaData, MetaEvent, NonPaginatedResponse, OAuthFields, OperationResponse, PaginatedResponse, PaginationCursor, PaginationMetadata, PaginationMethodUnion, PaginationOptions, ProcessGetAllOptions, ProcessGetByIdOptions, ProcessGetResponse, ProcessIncidentGetAllResponse, ProcessIncidentGetResponse, ProcessIncidentsServiceModel, ProcessInstanceExecutionHistoryResponse, ProcessInstanceGetAllOptions, ProcessInstanceGetAllWithPaginationOptions, ProcessInstanceGetResponse, ProcessInstanceGetVariablesOptions, ProcessInstanceGetVariablesResponse, ProcessInstanceMethods, ProcessInstanceOperationOptions, ProcessInstanceOperationResponse, ProcessInstanceRun, ProcessInstancesServiceModel, ProcessMethods, ProcessProperties, ProcessServiceModel, ProcessStartRequest, ProcessStartRequestWithKey, ProcessStartRequestWithName, ProcessStartResponse, QueryParams, QueueGetAllOptions, QueueGetByIdOptions, QueueGetResponse, QueueServiceModel, RawAgentGetByIdResponse, RawAgentGetResponse, RawCaseInstanceGetResponse, RawConversationGetResponse, RawEntityGetResponse, RawMaestroProcessGetAllResponse, RawProcessInstanceGetResponse, RawTaskCreateResponse, RawTaskGetResponse, RequestOptions, RequestSpec, ResponseDictionary, ResponseType, RetryOptions, RobotMetadata, SessionCapabilities, SessionEndEvent, SessionEndingEvent, SessionStartEvent, SessionStartedEvent, SessionStream, Simplify, SourceJoinCriteria, StageSLA, StageTask, Tag, TaskActivity, TaskAssignOptions, TaskAssignment, TaskAssignmentOptions, TaskAssignmentResponse, TaskBaseResponse, TaskCompleteOptions, TaskCompletionOptions, TaskCreateOptions, TaskCreateResponse, TaskGetAllOptions, TaskGetByIdOptions, TaskGetResponse, TaskGetUsersOptions, TaskMethods, TaskServiceModel, TaskSlaDetail, TaskSource, TasksUnassignOptions, TimeoutOptions, ToolCall, ToolCallConfirmationEndValue, ToolCallConfirmationInterruptStartEvent, ToolCallConfirmationValue, ToolCallEndEvent, ToolCallEvent, ToolCallInputValue, ToolCallOutputValue, ToolCallResult, ToolCallStartEvent, ToolCallStream, UiPathSDKConfig, UserLoginInfo, UserServiceModel, UserSettingsGetResponse, UserSettingsUpdateOptions, UserSettingsUpdateResponse };