chat 4.27.0 → 4.29.0

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.
Files changed (49) hide show
  1. package/dist/ai/index.d.ts +501 -0
  2. package/dist/ai/index.js +500 -0
  3. package/dist/chat-D9UYaaNO.d.ts +3156 -0
  4. package/dist/chunk-HD375J7S.js +128 -0
  5. package/dist/{chunk-AN7MRAVW.js → chunk-V25FKIIL.js} +5 -1
  6. package/dist/index.d.ts +35 -2934
  7. package/dist/index.js +567 -210
  8. package/dist/{jsx-runtime-Co9uV6l7.d.ts → jsx-runtime-CFq1K_Ve.d.ts} +11 -1
  9. package/dist/jsx-runtime.d.ts +1 -1
  10. package/dist/jsx-runtime.js +1 -1
  11. package/docs/actions.mdx +52 -1
  12. package/docs/adapters.mdx +72 -36
  13. package/docs/ai/ai-sdk-tools.mdx +227 -0
  14. package/docs/ai/index.mdx +63 -0
  15. package/docs/ai/meta.json +4 -0
  16. package/docs/{api → ai}/to-ai-messages.mdx +16 -3
  17. package/docs/ai/types.mdx +243 -0
  18. package/docs/api/cards.mdx +4 -0
  19. package/docs/api/chat.mdx +132 -10
  20. package/docs/api/index.mdx +6 -6
  21. package/docs/api/markdown.mdx +28 -5
  22. package/docs/api/message.mdx +54 -1
  23. package/docs/api/meta.json +1 -0
  24. package/docs/api/modals.mdx +50 -0
  25. package/docs/api/postable-message.mdx +58 -4
  26. package/docs/api/thread.mdx +11 -3
  27. package/docs/api/transcripts.mdx +220 -0
  28. package/docs/cards.mdx +6 -0
  29. package/docs/concurrency.mdx +58 -15
  30. package/docs/contributing/building.mdx +74 -2
  31. package/docs/contributing/testing.mdx +4 -0
  32. package/docs/conversation-history.mdx +137 -0
  33. package/docs/direct-messages.mdx +23 -5
  34. package/docs/ephemeral-messages.mdx +1 -1
  35. package/docs/error-handling.mdx +15 -3
  36. package/docs/files.mdx +21 -1
  37. package/docs/handling-events.mdx +10 -7
  38. package/docs/index.mdx +8 -5
  39. package/docs/meta.json +17 -3
  40. package/docs/modals.mdx +24 -0
  41. package/docs/posting-messages.mdx +10 -4
  42. package/docs/slash-commands.mdx +4 -4
  43. package/docs/streaming.mdx +75 -27
  44. package/docs/subject.mdx +53 -0
  45. package/docs/testing.mdx +142 -0
  46. package/docs/threads-messages-channels.mdx +10 -1
  47. package/docs/usage.mdx +15 -2
  48. package/package.json +23 -2
  49. package/resources/guides/how-to-build-an-ai-agent-for-slack-with-chat-sdk-and-ai-sdk.md +1 -1
package/dist/index.d.ts CHANGED
@@ -1,370 +1,10 @@
1
- import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';
1
+ import { P as PostableObject, A as Adapter, a as PostableObjectContext, S as StreamChunk, T as ThreadHistoryCache, b as ThreadHistoryConfig, c as StreamEvent, E as EmojiMapConfig, d as EmojiValue, W as WellKnownEmoji, e as EmojiFormats, C as CustomEmojiMap, f as AdapterPostableMessage } from './chat-D9UYaaNO.js';
2
+ export { y as ActionEvent, z as ActionHandler, g as AiAssistantMessage, h as AiFilePart, i as AiImagePart, j as AiMessage, k as AiMessagePart, l as AiTextPart, m as AiUserMessage, F as AppHomeOpenedEvent, G as AppHomeOpenedHandler, B as AppendInput, D as AppendOptions, H as AssistantContextChangedEvent, I as AssistantContextChangedHandler, J as AssistantThreadStartedEvent, K as AssistantThreadStartedHandler, L as Attachment, N as Author, O as Channel, o as ChannelImpl, Q as ChannelInfo, R as ChannelVisibility, r as Chat, U as ChatConfig, V as ChatInstance, X as ConcurrencyConfig, Y as ConcurrencyStrategy, b6 as ConsoleLogger, Z as CountQuery, _ as DeleteTarget, $ as DirectMessageHandler, a0 as DurationString, a1 as Emoji, a2 as EphemeralMessage, a3 as FetchDirection, a4 as FetchOptions, a5 as FetchResult, a6 as FileUpload, a7 as FormattedContent, a8 as IdentityContext, a9 as IdentityResolver, aa as LinkPreview, ab as ListQuery, ac as ListThreadsOptions, ad as ListThreadsResult, ae as Lock, af as LockScope, ag as LockScopeContext, ai as LogLevel, ah as Logger, aj as MarkdownTextChunk, ak as MemberJoinedChannelEvent, al as MemberJoinedChannelHandler, am as MentionHandler, M as Message, an as MessageContext, s as MessageData, ao as MessageHandler, ap as MessageMetadata, aq as MessageSubject, ar as ModalClearResponse, as as ModalCloseEvent, at as ModalCloseHandler, au as ModalCloseResponse, av as ModalErrorsResponse, aw as ModalPushResponse, ax as ModalResponse, ay as ModalSubmitEvent, az as ModalSubmitHandler, aA as ModalUpdateResponse, aB as OptionsLoadEvent, aC as OptionsLoadGroup, aD as OptionsLoadHandler, aE as OptionsLoadResult, aF as PlanUpdateChunk, aM as PostEphemeralOptions, aG as Postable, aH as PostableAst, aI as PostableCard, aJ as PostableMarkdown, aK as PostableMessage, aL as PostableRaw, aN as QueueEntry, aO as RawMessage, aP as ReactionEvent, aQ as ReactionHandler, aR as ScheduledMessage, aS as SentMessage, q as SerializedChannel, u as SerializedMessage, w as SerializedThread, aT as SlashCommandEvent, aU as SlashCommandHandler, aV as StateAdapter, aW as StreamOptions, aX as SubscribedMessageHandler, b7 as THREAD_STATE_TTL_MS, aY as TaskUpdateChunk, aZ as Thread, x as ThreadImpl, a_ as ThreadInfo, a$ as ThreadSummary, n as ToAiMessagesOptions, b0 as TranscriptEntry, b1 as TranscriptRole, b2 as TranscriptsApi, b3 as TranscriptsConfig, b4 as UserInfo, b5 as WebhookOptions, p as deriveChannelId, v as isPostableObject, t as toAiMessages } from './chat-D9UYaaNO.js';
2
3
  import { Root, List, Content, Blockquote, Code, Emphasis, InlineCode, Delete, Link, ListItem, Paragraph, Strong, TableCell, Table as Table$1, TableRow, Text } from 'mdast';
3
4
  export { Blockquote, Code, Content, Delete, Emphasis, InlineCode, Link, List, ListItem, Table as MdastTable, Nodes, Paragraph, Root, Strong, TableCell, TableRow, Text } from 'mdast';
4
- import { C as ChatElement, a as CardElement, M as ModalElement, S as SelectOptionElement, b as CardChild, A as ActionsComponent, B as ButtonComponent, c as CardComponent, d as cardChildToFallbackText$1, e as CardLinkComponent, T as TextComponent, D as DividerComponent, F as FieldComponent, f as FieldsComponent, g as fromReactElement$1, I as ImageComponent, i as isCardElement$1, h as isJSX$1, L as LinkButtonComponent, j as SectionComponent, k as Table$2, t as toCardElement$1, l as toModalElement$1, m as fromReactModalElement$1, n as isModalElement$1, E as ExternalSelectComponent, o as ModalComponent, R as RadioSelectComponent, p as SelectComponent, q as SelectOptionComponent, r as TextInputComponent } from './jsx-runtime-Co9uV6l7.js';
5
- export { s as ActionsElement, u as ButtonElement, v as ButtonOptions, X as ButtonProps, w as ButtonStyle, Y as CardJSXElement, Z as CardJSXProps, _ as CardLinkProps, x as CardOptions, $ as CardProps, a0 as ContainerProps, y as DividerElement, a1 as DividerProps, ab as ExternalSelectElement, ac as ExternalSelectOptions, a2 as ExternalSelectProps, z as FieldElement, a3 as FieldProps, G as FieldsElement, H as ImageElement, a4 as ImageProps, J as LinkButtonElement, K as LinkButtonOptions, a5 as LinkButtonProps, N as LinkElement, ad as ModalChild, ae as ModalOptions, a6 as ModalProps, af as RadioSelectElement, ag as RadioSelectOptions, O as SectionElement, ah as SelectElement, a7 as SelectOptionProps, ai as SelectOptions, a8 as SelectProps, P as TableAlignment, Q as TableElement, U as TableOptions, V as TextElement, aj as TextInputElement, ak as TextInputOptions, a9 as TextInputProps, aa as TextProps, W as TextStyle } from './jsx-runtime-Co9uV6l7.js';
6
-
7
- interface MessageHistoryConfig {
8
- /** Maximum messages to keep per thread (default: 100) */
9
- maxMessages?: number;
10
- /** TTL for cached history in milliseconds (default: 7 days) */
11
- ttlMs?: number;
12
- }
13
- /**
14
- * Persistent message history cache backed by the StateAdapter.
15
- *
16
- * Used by adapters that lack server-side message history APIs (e.g., WhatsApp, Telegram).
17
- * Messages are atomically appended via `state.appendToList()`, which is safe
18
- * without holding a thread lock.
19
- */
20
- declare class MessageHistoryCache {
21
- private readonly state;
22
- private readonly maxMessages;
23
- private readonly ttlMs;
24
- constructor(state: StateAdapter, config?: MessageHistoryConfig);
25
- /**
26
- * Atomically append a message to the history for a thread.
27
- * Trims to maxMessages (keeps newest) and refreshes TTL.
28
- */
29
- append(threadId: string, message: Message): Promise<void>;
30
- /**
31
- * Get messages for a thread in chronological order (oldest first).
32
- *
33
- * @param threadId - The thread ID
34
- * @param limit - Optional limit on number of messages to return (returns newest N)
35
- */
36
- getMessages(threadId: string, limit?: number): Promise<Message[]>;
37
- }
38
-
39
- /**
40
- * Serialized channel data for passing to external systems (e.g., workflow engines).
41
- */
42
- interface SerializedChannel {
43
- _type: "chat:Channel";
44
- adapterName: string;
45
- channelVisibility?: ChannelVisibility;
46
- id: string;
47
- isDM: boolean;
48
- }
49
- /**
50
- * Config for creating a ChannelImpl with explicit adapter/state instances.
51
- */
52
- interface ChannelImplConfigWithAdapter {
53
- adapter: Adapter;
54
- channelVisibility?: ChannelVisibility;
55
- id: string;
56
- isDM?: boolean;
57
- messageHistory?: MessageHistoryCache;
58
- stateAdapter: StateAdapter;
59
- }
60
- /**
61
- * Config for creating a ChannelImpl with lazy adapter resolution.
62
- */
63
- interface ChannelImplConfigLazy {
64
- adapterName: string;
65
- channelVisibility?: ChannelVisibility;
66
- id: string;
67
- isDM?: boolean;
68
- }
69
- type ChannelImplConfig = ChannelImplConfigWithAdapter | ChannelImplConfigLazy;
70
- declare class ChannelImpl<TState = Record<string, unknown>> implements Channel<TState> {
71
- readonly id: string;
72
- readonly isDM: boolean;
73
- readonly channelVisibility: ChannelVisibility;
74
- private _adapter?;
75
- private readonly _adapterName?;
76
- private _stateAdapterInstance?;
77
- private _name;
78
- private readonly _messageHistory?;
79
- constructor(config: ChannelImplConfig);
80
- get adapter(): Adapter;
81
- private get _stateAdapter();
82
- get name(): string | null;
83
- get state(): Promise<TState | null>;
84
- setState(newState: Partial<TState>, options?: {
85
- replace?: boolean;
86
- }): Promise<void>;
87
- /**
88
- * Iterate messages newest first (backward from most recent).
89
- * Uses adapter.fetchChannelMessages if available, otherwise falls back
90
- * to adapter.fetchMessages with the channel ID.
91
- */
92
- get messages(): AsyncIterable<Message>;
93
- /**
94
- * Iterate threads in this channel, most recently active first.
95
- */
96
- threads(): AsyncIterable<ThreadSummary>;
97
- fetchMetadata(): Promise<ChannelInfo>;
98
- post<T extends PostableObject>(message: T): Promise<T>;
99
- post(message: string | AdapterPostableMessage | AsyncIterable<string> | ChatElement): Promise<SentMessage>;
100
- private handlePostableObject;
101
- private postSingleMessage;
102
- postEphemeral(user: string | Author, message: AdapterPostableMessage | ChatElement, options: PostEphemeralOptions): Promise<EphemeralMessage | null>;
103
- schedule(message: AdapterPostableMessage | ChatElement, options: {
104
- postAt: Date;
105
- }): Promise<ScheduledMessage>;
106
- startTyping(status?: string): Promise<void>;
107
- mentionUser(userId: string): string;
108
- toJSON(): SerializedChannel;
109
- static fromJSON<TState = Record<string, unknown>>(json: SerializedChannel, adapter?: Adapter): ChannelImpl<TState>;
110
- static [WORKFLOW_SERIALIZE](instance: ChannelImpl): SerializedChannel;
111
- static [WORKFLOW_DESERIALIZE](data: SerializedChannel): ChannelImpl;
112
- private createSentMessage;
113
- }
114
- /**
115
- * Derive the channel ID from a thread ID.
116
- */
117
- declare function deriveChannelId(adapter: Adapter, threadId: string): string;
118
-
119
- /**
120
- * Logger types and implementations for chat-sdk
121
- */
122
- type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
123
- interface Logger {
124
- /** Create a sub-logger with a prefix */
125
- child(prefix: string): Logger;
126
- debug(message: string, ...args: unknown[]): void;
127
- error(message: string, ...args: unknown[]): void;
128
- info(message: string, ...args: unknown[]): void;
129
- warn(message: string, ...args: unknown[]): void;
130
- }
131
- /**
132
- * Default console logger implementation.
133
- */
134
- declare class ConsoleLogger implements Logger {
135
- private readonly prefix;
136
- private readonly level;
137
- constructor(level?: LogLevel, prefix?: string);
138
- private shouldLog;
139
- child(prefix: string): Logger;
140
- debug(message: string, ...args: unknown[]): void;
141
- info(message: string, ...args: unknown[]): void;
142
- warn(message: string, ...args: unknown[]): void;
143
- error(message: string, ...args: unknown[]): void;
144
- }
145
-
146
- /**
147
- * Context provided to a PostableObject after it has been posted.
148
- */
149
- interface PostableObjectContext {
150
- adapter: Adapter;
151
- logger?: Logger;
152
- messageId: string;
153
- threadId: string;
154
- }
155
- /**
156
- * Base interface for objects that can be posted to threads/channels.
157
- * Examples: Plan, Poll, etc.
158
- *
159
- * @template TData - The data type returned by getPostData()
160
- */
161
- interface PostableObject<TData = unknown> {
162
- /** Symbol identifying this as a postable object */
163
- readonly $$typeof: symbol;
164
- /**
165
- * Get a fallback text representation for adapters that don't support this object type.
166
- * This should return a human-readable string representation.
167
- */
168
- getFallbackText(): string;
169
- /** Get the data to send to the adapter */
170
- getPostData(): TData;
171
- /** Check if the adapter supports this object type */
172
- isSupported(adapter: Adapter): boolean;
173
- /** The kind of object - used by adapters to dispatch */
174
- readonly kind: string;
175
- /** Called after successful posting to bind the object to the thread */
176
- onPosted(context: PostableObjectContext): void;
177
- }
178
- /**
179
- * Type guard to check if a value is a PostableObject.
180
- */
181
- declare function isPostableObject(value: unknown): value is PostableObject;
182
-
183
- /**
184
- * Serialized thread data for passing to external systems (e.g., workflow engines).
185
- */
186
- interface SerializedThread {
187
- _type: "chat:Thread";
188
- adapterName: string;
189
- channelId: string;
190
- channelVisibility?: ChannelVisibility;
191
- currentMessage?: SerializedMessage;
192
- id: string;
193
- isDM: boolean;
194
- }
195
- /**
196
- * Config for creating a ThreadImpl with explicit adapter/state instances.
197
- */
198
- interface ThreadImplConfigWithAdapter {
199
- adapter: Adapter;
200
- channelId: string;
201
- channelVisibility?: ChannelVisibility;
202
- currentMessage?: Message;
203
- fallbackStreamingPlaceholderText?: string | null;
204
- id: string;
205
- initialMessage?: Message;
206
- isDM?: boolean;
207
- isSubscribedContext?: boolean;
208
- logger?: Logger;
209
- messageHistory?: MessageHistoryCache;
210
- stateAdapter: StateAdapter;
211
- streamingUpdateIntervalMs?: number;
212
- }
213
- /**
214
- * Config for creating a ThreadImpl with lazy adapter resolution.
215
- * The adapter will be looked up from the Chat singleton on first access.
216
- */
217
- interface ThreadImplConfigLazy {
218
- adapterName: string;
219
- channelId: string;
220
- channelVisibility?: ChannelVisibility;
221
- currentMessage?: Message;
222
- fallbackStreamingPlaceholderText?: string | null;
223
- id: string;
224
- initialMessage?: Message;
225
- isDM?: boolean;
226
- isSubscribedContext?: boolean;
227
- logger?: Logger;
228
- streamingUpdateIntervalMs?: number;
229
- }
230
- type ThreadImplConfig = ThreadImplConfigWithAdapter | ThreadImplConfigLazy;
231
- declare class ThreadImpl<TState = Record<string, unknown>> implements Thread<TState> {
232
- readonly id: string;
233
- readonly channelId: string;
234
- readonly isDM: boolean;
235
- readonly channelVisibility: ChannelVisibility;
236
- /** Direct adapter instance (if provided) */
237
- private _adapter?;
238
- /** Adapter name for lazy resolution */
239
- private readonly _adapterName?;
240
- /** Direct state adapter instance (if provided) */
241
- private _stateAdapterInstance?;
242
- private _recentMessages;
243
- private readonly _isSubscribedContext;
244
- /** Current message context for streaming - provides userId/teamId */
245
- private readonly _currentMessage?;
246
- /** Update interval for fallback streaming */
247
- private readonly _streamingUpdateIntervalMs;
248
- /** Placeholder text for fallback streaming (post + edit) */
249
- private readonly _fallbackStreamingPlaceholderText;
250
- /** Cached channel instance */
251
- private _channel?;
252
- /** Message history cache (set only for adapters with persistMessageHistory) */
253
- private readonly _messageHistory?;
254
- private readonly _logger?;
255
- constructor(config: ThreadImplConfig);
256
- /**
257
- * Get the adapter for this thread.
258
- * If created with lazy config, resolves from Chat singleton on first access.
259
- */
260
- get adapter(): Adapter;
261
- /**
262
- * Get the state adapter for this thread.
263
- * If created with lazy config, resolves from Chat singleton on first access.
264
- */
265
- private get _stateAdapter();
266
- get recentMessages(): Message[];
267
- set recentMessages(messages: Message[]);
268
- /**
269
- * Get the current thread state.
270
- * Returns null if no state has been set.
271
- */
272
- get state(): Promise<TState | null>;
273
- /**
274
- * Set the thread state. Merges with existing state by default.
275
- * State is persisted for 30 days.
276
- */
277
- setState(newState: Partial<TState>, options?: {
278
- replace?: boolean;
279
- }): Promise<void>;
280
- /**
281
- * Get the Channel containing this thread.
282
- * Lazy-created and cached.
283
- */
284
- get channel(): Channel<TState>;
285
- /**
286
- * Iterate messages newest first (backward from most recent).
287
- * Auto-paginates lazily.
288
- */
289
- get messages(): AsyncIterable<Message>;
290
- get allMessages(): AsyncIterable<Message>;
291
- getParticipants(): Promise<Author[]>;
292
- isSubscribed(): Promise<boolean>;
293
- subscribe(): Promise<void>;
294
- unsubscribe(): Promise<void>;
295
- post<T extends PostableObject>(message: T): Promise<T>;
296
- post(message: string | AdapterPostableMessage | AsyncIterable<string> | ChatElement): Promise<SentMessage>;
297
- private handlePostableObject;
298
- postEphemeral(user: string | Author, message: AdapterPostableMessage | ChatElement, options: PostEphemeralOptions): Promise<EphemeralMessage | null>;
299
- schedule(message: AdapterPostableMessage | ChatElement, options: {
300
- postAt: Date;
301
- }): Promise<ScheduledMessage>;
302
- /**
303
- * Handle streaming from an AsyncIterable.
304
- * Normalizes the stream (supports both textStream and fullStream from AI SDK),
305
- * then uses adapter's native streaming if available, otherwise falls back to post+edit.
306
- */
307
- private handleStream;
308
- /**
309
- * Slack payloads carry the workspace ID in a few different shapes depending on
310
- * the webhook type:
311
- * - Message events: `team_id` or `team` as a string
312
- * - `block_actions` payloads: `team.id` (object), with `user.team_id` as a fallback
313
- */
314
- private extractSlackRecipientTeamId;
315
- startTyping(status?: string): Promise<void>;
316
- /**
317
- * Fallback streaming implementation using post + edit.
318
- * Used when adapter doesn't support native streaming.
319
- * Uses recursive setTimeout to send updates every intervalMs (default 500ms).
320
- * Schedules next update only after current edit completes to avoid overwhelming slow services.
321
- */
322
- private fallbackStream;
323
- refresh(): Promise<void>;
324
- mentionUser(userId: string): string;
325
- /**
326
- * Serialize the thread to a plain JSON object.
327
- * Use this to pass thread data to external systems like workflow engines.
328
- *
329
- * @example
330
- * ```typescript
331
- * // Pass to a workflow
332
- * await workflow.start("my-workflow", {
333
- * thread: thread.toJSON(),
334
- * message: serializeMessage(message),
335
- * });
336
- * ```
337
- */
338
- toJSON(): SerializedThread;
339
- /**
340
- * Reconstruct a Thread from serialized JSON data.
341
- *
342
- * Reconstructs a ThreadImpl from serialized data.
343
- * Uses lazy resolution from Chat.getSingleton() for adapter and state.
344
- *
345
- * @param json - Serialized thread data
346
- * @requires Call `chat.registerSingleton()` before deserializing threads
347
- *
348
- * @example
349
- * ```typescript
350
- * const thread = ThreadImpl.fromJSON(serializedThread);
351
- * ```
352
- */
353
- static fromJSON<TState = Record<string, unknown>>(json: SerializedThread, adapter?: Adapter): ThreadImpl<TState>;
354
- /**
355
- * Serialize a ThreadImpl instance for @workflow/serde.
356
- * This static method is automatically called by workflow serialization.
357
- */
358
- static [WORKFLOW_SERIALIZE](instance: ThreadImpl): SerializedThread;
359
- /**
360
- * Deserialize a ThreadImpl from @workflow/serde.
361
- * Uses lazy adapter resolution from Chat.getSingleton().
362
- * Requires chat.registerSingleton() to have been called.
363
- */
364
- static [WORKFLOW_DESERIALIZE](data: SerializedThread): ThreadImpl;
365
- private createSentMessage;
366
- createSentMessageFromMessage(message: Message): SentMessage;
367
- }
5
+ import { C as CardElement, a as CardChild, A as ActionsComponent, B as ButtonComponent, b as CardComponent, c as cardChildToFallbackText$1, d as CardLinkComponent, T as TextComponent, D as DividerComponent, F as FieldComponent, e as FieldsComponent, f as fromReactElement$1, I as ImageComponent, i as isCardElement$1, g as isJSX$1, L as LinkButtonComponent, S as SectionComponent, h as Table$2, t as toCardElement$1, j as toModalElement$1, k as fromReactModalElement$1, l as isModalElement$1, E as ExternalSelectComponent, M as ModalComponent, R as RadioSelectComponent, m as SelectComponent, n as SelectOptionComponent, o as TextInputComponent } from './jsx-runtime-CFq1K_Ve.js';
6
+ export { p as ActionsElement, q as ButtonElement, r as ButtonOptions, U as ButtonProps, s as ButtonStyle, V as CardJSXElement, W as CardJSXProps, X as CardLinkProps, u as CardOptions, Y as CardProps, Z as ChatElement, _ as ContainerProps, v as DividerElement, $ as DividerProps, a9 as ExternalSelectElement, aa as ExternalSelectOptions, a0 as ExternalSelectProps, w as FieldElement, a1 as FieldProps, x as FieldsElement, y as ImageElement, a2 as ImageProps, z as LinkButtonElement, G as LinkButtonOptions, a3 as LinkButtonProps, H as LinkElement, ab as ModalChild, ac as ModalElement, ad as ModalOptions, a4 as ModalProps, ae as RadioSelectElement, af as RadioSelectOptions, J as SectionElement, ag as SelectElement, ah as SelectOptionElement, a5 as SelectOptionProps, ai as SelectOptions, a6 as SelectProps, K as TableAlignment, N as TableElement, O as TableOptions, P as TextElement, aj as TextInputElement, ak as TextInputOptions, a7 as TextInputProps, a8 as TextProps, Q as TextStyle } from './jsx-runtime-CFq1K_Ve.js';
7
+ import '@workflow/serde';
368
8
 
369
9
  /**
370
10
  * Error types for chat-sdk
@@ -468,2579 +108,40 @@ declare class Plan implements PostableObject<PlanModel> {
468
108
  }
469
109
 
470
110
  /**
471
- * Represents the visibility scope of a channel.
111
+ * Normalizes an async iterable stream for use with `thread.post()`.
112
+ *
113
+ * Handles three stream types automatically:
114
+ * - **Text streams** (`AsyncIterable<string>`, e.g. AI SDK `textStream`) —
115
+ * passed through as-is.
116
+ * - **Full streams** (`AsyncIterable<object>`, e.g. AI SDK `fullStream`) —
117
+ * extracts `text-delta` events and injects `"\n\n"` separators between
118
+ * steps so that multi-step agent output reads naturally.
119
+ * - **StreamChunk objects** (`task_update`, `plan_update`, `markdown_text`) —
120
+ * passed through as-is for adapters with native structured chunk support.
472
121
  *
473
- * - `private`: Channel is only visible to invited members (e.g., private Slack channels)
474
- * - `workspace`: Channel is visible to all workspace members (e.g., public Slack channels)
475
- * - `external`: Channel is shared with external organizations (e.g., Slack Connect)
476
- * - `unknown`: Visibility cannot be determined
122
+ * This is used internally by `thread.post()`, so you can pass either stream
123
+ * directly:
124
+ * ```ts
125
+ * await thread.post(result.fullStream); // auto-detected
126
+ * await thread.post(result.textStream); // still works
127
+ * ```
477
128
  */
478
- type ChannelVisibility = "private" | "workspace" | "external" | "unknown";
129
+ declare function fromFullStream(stream: AsyncIterable<unknown>): AsyncIterable<string | StreamChunk>;
479
130
 
480
131
  /**
481
- * Chat configuration with type-safe adapter inference.
482
- * @template TAdapters - Record of adapter name to adapter instance
483
- */
484
- interface ChatConfig<TAdapters extends Record<string, Adapter> = Record<string, Adapter>> {
485
- /** Map of adapter name to adapter instance */
486
- adapters: TAdapters;
487
- /**
488
- * How to handle messages that arrive while a handler is already
489
- * processing on the same thread.
490
- *
491
- * - `'drop'` (default) — discard the message (throw `LockError`)
492
- * - `'queue'` — queue the message; when the current handler finishes,
493
- * process only the latest queued message with `context.skipped` containing
494
- * all intermediate messages
495
- * - `'debounce'` — all messages start/reset a debounce timer; only the
496
- * final message in a burst is processed
497
- * - `'concurrent'` — no locking; all messages processed in parallel
498
- * - `ConcurrencyConfig` — fine-grained control over strategy and parameters
499
- */
500
- concurrency?: ConcurrencyStrategy | ConcurrencyConfig;
501
- /**
502
- * TTL for message deduplication entries in milliseconds.
503
- * Defaults to 300000 (5 minutes). Increase if your webhook cold starts
504
- * cause platform retries that arrive after the default TTL expires.
505
- */
506
- dedupeTtlMs?: number;
507
- /**
508
- * Placeholder text for fallback streaming (post + edit) adapters.
509
- * Defaults to `"..."`.
510
- *
511
- * Set to `null` to avoid posting an initial placeholder message and instead
512
- * wait until some real text has been streamed before creating the message.
513
- */
514
- fallbackStreamingPlaceholderText?: string | null;
515
- /**
516
- * Lock scope determines which messages contend for the same lock.
517
- *
518
- * - `'thread'`: lock per threadId (default for most adapters)
519
- * - `'channel'`: lock per channelId (default for WhatsApp, Telegram)
520
- * - function: resolve scope dynamically per message (async supported)
521
- *
522
- * When not set, falls back to the adapter's `lockScope` property,
523
- * then to `'thread'`.
524
- */
525
- lockScope?: LockScope | ((context: LockScopeContext) => LockScope | Promise<LockScope>);
526
- /**
527
- * Logger instance or log level.
528
- * Pass "silent" to disable all logging.
529
- */
530
- logger?: Logger | LogLevel;
531
- /**
532
- * Configuration for persistent message history.
533
- * Only used by adapters that set `persistMessageHistory: true`.
534
- */
535
- messageHistory?: {
536
- /** Maximum messages to store per thread (default: 100) */
537
- maxMessages?: number;
538
- /** TTL for cached history in milliseconds (default: 7 days) */
539
- ttlMs?: number;
540
- };
541
- /**
542
- * @deprecated Use `concurrency` instead.
543
- *
544
- * Behavior when a thread lock cannot be acquired (another handler is processing).
545
- * - `'drop'` (default) — throw `LockError`, preserving current behavior
546
- * - `'force'` — force-release the existing lock and re-acquire
547
- * - callback — custom logic receiving `(threadId, message)`, return `'force'` or `'drop'`
548
- *
549
- * When `'force'` is used, the previous handler continues executing — only the lock
550
- * is released, not the handler itself. This means two handlers may run concurrently
551
- * on the same thread. The old handler's `releaseLock()` call becomes a no-op since
552
- * the token no longer matches.
553
- */
554
- onLockConflict?: "force" | "drop" | ((threadId: string, message: Message) => "force" | "drop" | Promise<"force" | "drop">);
555
- /** State adapter for subscriptions and locking */
556
- state: StateAdapter;
557
- /**
558
- * Update interval for fallback streaming (post + edit) in milliseconds.
559
- * Defaults to 500ms. Lower values provide smoother updates but may hit rate limits.
560
- */
561
- streamingUpdateIntervalMs?: number;
562
- /** Default bot username across all adapters */
563
- userName: string;
564
- }
565
- /**
566
- * Options for webhook handling.
567
- */
568
- interface WebhookOptions {
569
- /**
570
- * Override the default modal-opening behavior to handle it inline
571
- * within the current webhook response cycle.
572
- * When provided, called instead of adapter.openModal().
573
- * Used by Teams to return modal content in the HTTP invoke response.
574
- *
575
- * The returned `viewId` is platform-specific (e.g. Slack's view ID).
576
- * Adapters that don't produce a view ID may return void.
577
- */
578
- onOpenModal?: (modal: ModalElement, contextId: string) => Promise<{
579
- viewId: string;
580
- } | undefined>;
581
- /**
582
- * Function to run message handling in the background.
583
- * Use this to ensure fast webhook responses while processing continues.
584
- *
585
- * @example
586
- * // Next.js App Router
587
- * import { after } from "next/server";
588
- * chat.webhooks.slack(request, { waitUntil: (p) => after(() => p) });
589
- *
590
- * @example
591
- * // Vercel Functions
592
- * import { waitUntil } from "@vercel/functions";
593
- * chat.webhooks.slack(request, { waitUntil });
594
- */
595
- waitUntil?: (task: Promise<unknown>) => void;
596
- }
597
- /**
598
- * Adapter interface with generics for platform-specific types.
599
- * @template TThreadId - Platform-specific thread ID data type
600
- * @template TRawMessage - Platform-specific raw message type
601
- */
602
- interface Adapter<TThreadId = unknown, TRawMessage = unknown> {
603
- /** Add a reaction to a message */
604
- addReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
605
- /** Bot user ID for platforms that use IDs in mentions (e.g., Slack's <@U123>) */
606
- readonly botUserId?: string;
607
- /**
608
- * Derive channel ID from a thread ID.
609
- * Default fallback: first two colon-separated parts (e.g., "slack:C123").
610
- * Adapters with different structures should override this.
611
- */
612
- channelIdFromThreadId(threadId: string): string;
613
- /** Decode thread ID string back to platform-specific data */
614
- decodeThreadId(threadId: string): TThreadId;
615
- /** Delete a message */
616
- deleteMessage(threadId: string, messageId: string): Promise<void>;
617
- /** Cleanup hook called when Chat instance is shutdown */
618
- disconnect?(): Promise<void>;
619
- /** Edit an existing message */
620
- editMessage(threadId: string, messageId: string, message: AdapterPostableMessage): Promise<RawMessage<TRawMessage>>;
621
- /**
622
- * Edit a previously posted object (Plan, Poll, etc.).
623
- * If not implemented, object updates will throw PlanNotSupportedError.
624
- *
625
- * @param threadId - The thread containing the message
626
- * @param messageId - The message ID to edit
627
- * @param kind - The object kind (e.g., "plan")
628
- * @param data - The object data (type depends on kind)
629
- */
630
- editObject?(threadId: string, messageId: string, kind: string, data: unknown): Promise<RawMessage<TRawMessage>>;
631
- /** Encode platform-specific data into a thread ID string */
632
- encodeThreadId(platformData: TThreadId): string;
633
- /**
634
- * Fetch channel info/metadata.
635
- */
636
- fetchChannelInfo?(channelId: string): Promise<ChannelInfo>;
637
- /**
638
- * Fetch channel-level messages (top-level, not thread replies).
639
- * For example, Slack's conversations.history vs conversations.replies.
640
- */
641
- fetchChannelMessages?(channelId: string, options?: FetchOptions): Promise<FetchResult<TRawMessage>>;
642
- /**
643
- * Fetch a single message by ID.
644
- * Optional - adapters that don't implement this will return null.
645
- *
646
- * @param threadId - The thread ID containing the message
647
- * @param messageId - The platform-specific message ID
648
- * @returns The message, or null if not found/not supported
649
- */
650
- fetchMessage?(threadId: string, messageId: string): Promise<Message<TRawMessage> | null>;
651
- /**
652
- * Fetch messages from a thread.
653
- *
654
- * **Direction behavior:**
655
- * - `backward` (default): Fetches the most recent messages. Use this for loading
656
- * a chat view. The `nextCursor` points to older messages.
657
- * - `forward`: Fetches the oldest messages first. Use this for iterating through
658
- * message history. The `nextCursor` points to newer messages.
659
- *
660
- * **Message ordering:**
661
- * Messages within each page are always returned in chronological order (oldest first),
662
- * regardless of direction. This is the natural reading order for chat messages.
663
- *
664
- * @example
665
- * ```typescript
666
- * // Load most recent 50 messages for display
667
- * const recent = await adapter.fetchMessages(threadId, { limit: 50 });
668
- * // recent.messages: [older, ..., newest] in chronological order
669
- *
670
- * // Paginate backward to load older messages
671
- * const older = await adapter.fetchMessages(threadId, {
672
- * limit: 50,
673
- * cursor: recent.nextCursor,
674
- * });
675
- *
676
- * // Iterate through all history from the beginning
677
- * const history = await adapter.fetchMessages(threadId, {
678
- * limit: 100,
679
- * direction: 'forward',
680
- * });
681
- * ```
682
- */
683
- fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<TRawMessage>>;
684
- /** Fetch thread metadata */
685
- fetchThread(threadId: string): Promise<ThreadInfo>;
686
- /**
687
- * Get the visibility scope of a channel containing the thread.
688
- *
689
- * This distinguishes between private channels, workspace-visible channels,
690
- * and externally shared channels (e.g., Slack Connect).
691
- *
692
- * @param threadId - The thread ID to check
693
- * @returns The channel visibility scope
694
- */
695
- getChannelVisibility?(threadId: string): ChannelVisibility;
696
- /**
697
- * Look up user information by user ID.
698
- * Optional — not all platforms support this.
699
- *
700
- * @param userId - Platform-specific user ID
701
- * @returns User info, or null if user not found
702
- */
703
- getUser?(userId: string): Promise<UserInfo | null>;
704
- /** Handle incoming webhook request */
705
- handleWebhook(request: Request, options?: WebhookOptions): Promise<Response>;
706
- /** Called when Chat instance is created (internal use) */
707
- initialize(chat: ChatInstance): Promise<void>;
708
- /**
709
- * Check if a thread is a direct message conversation.
710
- *
711
- * @param threadId - The thread ID to check
712
- * @returns True if the thread is a DM, false otherwise
713
- */
714
- isDM?(threadId: string): boolean;
715
- /**
716
- * List threads in a channel.
717
- */
718
- listThreads?(channelId: string, options?: ListThreadsOptions): Promise<ListThreadsResult<TRawMessage>>;
719
- /**
720
- * Default lock scope for this adapter.
721
- * - `'thread'` (default): lock per threadId
722
- * - `'channel'`: lock per channelId (for channel-based platforms like WhatsApp, Telegram)
723
- *
724
- * Can be overridden by `ChatConfig.lockScope`.
725
- */
726
- readonly lockScope?: LockScope;
727
- /** Unique name for this adapter (e.g., "slack", "teams") */
728
- readonly name: string;
729
- /**
730
- * Optional hook called when a thread is subscribed to.
731
- * Adapters can use this to set up platform-specific subscriptions
732
- * (e.g., Google Chat Workspace Events).
733
- */
734
- onThreadSubscribe?(threadId: string): Promise<void>;
735
- /**
736
- * Open a direct message conversation with a user.
737
- *
738
- * @param userId - The platform-specific user ID
739
- * @returns The thread ID for the DM conversation
740
- *
741
- * @example
742
- * ```typescript
743
- * const dmThreadId = await adapter.openDM("U123456");
744
- * await adapter.postMessage(dmThreadId, "Hello!");
745
- * ```
746
- */
747
- openDM?(userId: string): Promise<string>;
748
- /**
749
- * Open a modal/dialog form.
750
- *
751
- * @param triggerId - Platform-specific trigger ID from the action event
752
- * @param modal - The modal element to display
753
- * @param contextId - Optional context ID for server-side stored thread/message context
754
- * @returns The view/dialog ID
755
- */
756
- openModal?(triggerId: string, modal: ModalElement, contextId?: string): Promise<{
757
- viewId: string;
758
- }>;
759
- /** Parse platform message format to normalized format */
760
- parseMessage(raw: TRawMessage): Message<TRawMessage>;
761
- /**
762
- * When true, the SDK persists message history in the state adapter for this platform.
763
- * Use this for platforms that lack server-side message history APIs (e.g., WhatsApp, Telegram).
764
- */
765
- readonly persistMessageHistory?: boolean;
766
- /**
767
- * Post a message to channel top-level (not in a thread).
768
- */
769
- postChannelMessage?(channelId: string, message: AdapterPostableMessage): Promise<RawMessage<TRawMessage>>;
770
- /**
771
- * Post an ephemeral message visible only to a specific user.
772
- *
773
- * This is optional - if not implemented, Thread.postEphemeral will
774
- * fall back to openDM + postMessage when fallbackToDM is true.
775
- *
776
- * @param threadId - The thread to post in
777
- * @param userId - The user who should see the message
778
- * @param message - The message content
779
- * @returns EphemeralMessage with usedFallback: false
780
- */
781
- postEphemeral?(threadId: string, userId: string, message: AdapterPostableMessage): Promise<EphemeralMessage<TRawMessage>>;
782
- /** Post a message to a thread */
783
- postMessage(threadId: string, message: AdapterPostableMessage): Promise<RawMessage<TRawMessage>>;
784
- /**
785
- * Post a special object (Plan, Poll, etc.) as a single message.
786
- * If not implemented, posting such objects will throw PlanNotSupportedError.
787
- *
788
- * @param threadId - The thread to post to
789
- * @param kind - The object kind (e.g., "plan")
790
- * @param data - The object data (type depends on kind)
791
- */
792
- postObject?(threadId: string, kind: string, data: unknown): Promise<RawMessage<TRawMessage>>;
793
- /**
794
- * Reconstruct fetchData on an attachment after deserialization.
795
- * Called during message rehydration for queue/debounce strategies.
796
- * Uses fetchMetadata and adapter auth context to rebuild the download closure.
797
- */
798
- rehydrateAttachment?(attachment: Attachment): Attachment;
799
- /** Remove a reaction from a message */
800
- removeReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
801
- /** Render formatted content to platform-specific string */
802
- renderFormatted(content: FormattedContent): string;
803
- /**
804
- * Schedule a message for future delivery.
805
- *
806
- * Optional — only supported by adapters with native scheduling APIs (e.g., Slack).
807
- * Thread.schedule() will throw NotImplementedError if this method is absent.
808
- *
809
- * @param threadId - The thread to post in
810
- * @param message - The message content
811
- * @param options - Scheduling options including the target delivery time
812
- * @returns A ScheduledMessage with cancel() capability
813
- */
814
- scheduleMessage?(threadId: string, message: AdapterPostableMessage, options: {
815
- postAt: Date;
816
- }): Promise<ScheduledMessage<TRawMessage>>;
817
- /** Show typing indicator */
818
- startTyping(threadId: string, status?: string): Promise<void>;
819
- /**
820
- * Stream a message using platform-native streaming APIs.
821
- *
822
- * The adapter consumes the async iterable and handles the entire streaming lifecycle.
823
- * Only available on platforms with native streaming support (e.g., Slack).
824
- *
825
- * The stream can yield plain strings (text chunks) or {@link StreamChunk} objects
826
- * for rich content like task progress cards. Adapters that don't support structured
827
- * chunks will extract text from `markdown_text` chunks and ignore other types.
828
- *
829
- * @param threadId - The thread to stream to
830
- * @param textStream - Async iterable of text chunks or structured StreamChunk objects
831
- * @param options - Platform-specific streaming options
832
- * @returns The raw message after streaming completes
833
- */
834
- stream?(threadId: string, textStream: AsyncIterable<string | StreamChunk>, options?: StreamOptions): Promise<RawMessage<TRawMessage>>;
835
- /** Bot username (can override global userName) */
836
- readonly userName: string;
837
- }
838
- /**
839
- * A structured streaming chunk for platform-native rich content.
132
+ * @deprecated Renamed import from `./thread-history` instead.
840
133
  *
841
- * On Slack, these map directly to streaming chunk types:
842
- * - `markdown_text`: Streamed text content
843
- * - `task_update`: Tool/step progress cards (pending → in_progress → complete → error)
844
- * - `plan_update`: Plan title updates
845
- *
846
- * Adapters that don't support structured chunks will extract `text` from
847
- * `markdown_text` chunks and ignore other types gracefully.
848
- */
849
- type StreamChunk = MarkdownTextChunk | TaskUpdateChunk | PlanUpdateChunk;
850
- interface MarkdownTextChunk {
851
- text: string;
852
- type: "markdown_text";
853
- }
854
- interface TaskUpdateChunk {
855
- details?: string;
856
- id: string;
857
- output?: string;
858
- status: "pending" | "in_progress" | "complete" | "error";
859
- title: string;
860
- type: "task_update";
861
- }
862
- interface PlanUpdateChunk {
863
- title: string;
864
- type: "plan_update";
865
- }
866
- /**
867
- * Options for streaming messages.
868
- * Platform-specific options are passed through to the adapter.
134
+ * This module is preserved for backwards compatibility and re-exports the
135
+ * new names under the old identifiers. New code should use `ThreadHistoryCache`
136
+ * and `ThreadHistoryConfig` directly.
869
137
  */
870
- interface StreamOptions {
871
- /** Slack: The team/workspace ID */
872
- recipientTeamId?: string;
873
- /** Slack: The user ID to stream to (for AI assistant context) */
874
- recipientUserId?: string;
875
- /** Block Kit elements to attach when stopping the stream (Slack only, via chat.stopStream) */
876
- stopBlocks?: unknown[];
877
- /**
878
- * Slack: Controls how task_update chunks are displayed.
879
- * - `"timeline"` — individual task cards shown inline with text (default)
880
- * - `"plan"` — all tasks grouped into a single plan block
881
- */
882
- taskDisplayMode?: "timeline" | "plan";
883
- /** Minimum interval between updates in ms (default: 1000). Used for fallback mode (GChat/Teams). */
884
- updateIntervalMs?: number;
885
- }
886
- /** Internal interface for Chat instance passed to adapters */
887
- interface ChatInstance {
888
- /** Get the configured logger, optionally with a child prefix */
889
- getLogger(prefix?: string): Logger;
890
- getState(): StateAdapter;
891
- getUserName(): string;
892
- /**
893
- * @deprecated Use processMessage instead. This method is for internal use.
894
- */
895
- handleIncomingMessage(adapter: Adapter, threadId: string, message: Message): Promise<void>;
896
- /**
897
- * Process an incoming action event (button click) from an adapter.
898
- * Handles waitUntil registration and error catching internally.
899
- *
900
- * @param event - The action event (without thread field, will be added)
901
- * @param options - Webhook options including waitUntil
902
- */
903
- processAction(event: Omit<ActionEvent, "thread" | "openModal"> & {
904
- adapter: Adapter;
905
- }, options: WebhookOptions | undefined): Promise<void>;
906
- processAppHomeOpened(event: AppHomeOpenedEvent, options?: WebhookOptions): void;
907
- processAssistantContextChanged(event: AssistantContextChangedEvent, options?: WebhookOptions): void;
908
- processAssistantThreadStarted(event: AssistantThreadStartedEvent, options?: WebhookOptions): void;
909
- processMemberJoinedChannel(event: MemberJoinedChannelEvent, options?: WebhookOptions): void;
910
- /**
911
- * Process an incoming message from an adapter.
912
- * Handles waitUntil registration and error catching internally.
913
- *
914
- * @param adapter - The adapter that received the message
915
- * @param threadId - The thread ID
916
- * @param message - Either a parsed message, or a factory function for lazy async parsing
917
- * @param options - Webhook options including waitUntil
918
- */
919
- processMessage(adapter: Adapter, threadId: string, message: Message | (() => Promise<Message>), options?: WebhookOptions): void;
920
- /**
921
- * Process a modal close event from an adapter.
922
- *
923
- * @param event - The modal close event (without relatedThread/relatedMessage/relatedChannel)
924
- * @param contextId - Context ID for retrieving stored thread/message/channel context
925
- * @param options - Webhook options
926
- */
927
- processModalClose(event: Omit<ModalCloseEvent, "relatedThread" | "relatedMessage" | "relatedChannel">, contextId?: string, options?: WebhookOptions): void;
928
- /**
929
- * Process a modal submit event from an adapter.
930
- *
931
- * @param event - The modal submit event (without relatedThread/relatedMessage/relatedChannel)
932
- * @param contextId - Context ID for retrieving stored thread/message/channel context
933
- * @param options - Webhook options
934
- */
935
- processModalSubmit(event: Omit<ModalSubmitEvent, "relatedThread" | "relatedMessage" | "relatedChannel">, contextId?: string, options?: WebhookOptions): Promise<ModalResponse | undefined>;
936
- /**
937
- * Process an interactive options load event from an adapter.
938
- * Returns normalized select options for the adapter to render.
939
- */
940
- processOptionsLoad(event: OptionsLoadEvent, options?: WebhookOptions): Promise<OptionsLoadResult | undefined>;
941
- /**
942
- * Process an incoming reaction event from an adapter.
943
- * Handles waitUntil registration and error catching internally.
944
- *
945
- * @param event - The reaction event (without adapter field, will be added)
946
- * @param options - Webhook options including waitUntil
947
- */
948
- processReaction(event: Omit<ReactionEvent, "adapter" | "thread"> & {
949
- adapter?: Adapter;
950
- }, options?: WebhookOptions): void;
951
- /**
952
- * Process an incoming slash command from an adapter.
953
- * Handles waitUntil registration and error catching internally.
954
- *
955
- * @param event - The slash command event
956
- * @param options - Webhook options including waitUntil
957
- */
958
- processSlashCommand(event: Omit<SlashCommandEvent, "channel" | "openModal"> & {
959
- adapter: Adapter;
960
- channelId: string;
961
- }, options: WebhookOptions | undefined): void;
962
- }
963
- /** Lock scope determines which messages contend for the same lock. */
964
- type LockScope = "thread" | "channel";
965
- /** Context provided to the lockScope resolver function. */
966
- interface LockScopeContext {
967
- adapter: Adapter;
968
- channelId: string;
969
- isDM: boolean;
970
- threadId: string;
971
- }
972
- /** Concurrency strategy for overlapping messages on the same thread. */
973
- type ConcurrencyStrategy = "drop" | "queue" | "debounce" | "concurrent";
974
- /** Fine-grained concurrency configuration. */
975
- interface ConcurrencyConfig {
976
- /** Debounce window in milliseconds (debounce strategy). Default: 1500. */
977
- debounceMs?: number;
978
- /** Max concurrent handlers per thread (concurrent strategy). Default: Infinity. */
979
- maxConcurrent?: number;
980
- /** Max queued messages per thread (queue/debounce strategy). Default: 10. */
981
- maxQueueSize?: number;
982
- /** What to do when queue is full. Default: 'drop-oldest'. */
983
- onQueueFull?: "drop-oldest" | "drop-newest";
984
- /** TTL for queued entries in milliseconds. Default: 90000 (90s). */
985
- queueEntryTtlMs?: number;
986
- /** The concurrency strategy to use. */
987
- strategy: ConcurrencyStrategy;
988
- }
989
- /**
990
- * An entry in the per-thread message queue.
991
- * Used by the `queue` and `debounce` concurrency strategies.
992
- */
993
- interface QueueEntry {
994
- /** When this entry was enqueued (Unix ms). */
995
- enqueuedAt: number;
996
- /** When this entry expires (Unix ms). Stale entries are discarded on dequeue. */
997
- expiresAt: number;
998
- /** The queued message. */
999
- message: Message;
1000
- }
1001
- /**
1002
- * Context provided to message handlers when messages were queued
1003
- * while a previous handler was running.
1004
- */
1005
- interface MessageContext {
1006
- /**
1007
- * Messages that arrived while the previous handler was running,
1008
- * in chronological order, excluding the current message (which is the latest).
1009
- */
1010
- skipped: Message[];
1011
- /** Total messages received since last handler ran (skipped.length + 1). */
1012
- totalSinceLastHandler: number;
1013
- }
1014
- interface StateAdapter {
1015
- /** Acquire a lock on a thread (returns null if already locked) */
1016
- acquireLock(threadId: string, ttlMs: number): Promise<Lock | null>;
1017
- /** Atomically append a value to a list. Trims to maxLength (keeping newest). Refreshes TTL. */
1018
- appendToList(key: string, value: unknown, options?: {
1019
- maxLength?: number;
1020
- ttlMs?: number;
1021
- }): Promise<void>;
1022
- /** Connect to the state backend */
1023
- connect(): Promise<void>;
1024
- /** Delete a cached value */
1025
- delete(key: string): Promise<void>;
1026
- /** Pop the next message from the thread's queue. Returns null if empty. */
1027
- dequeue(threadId: string): Promise<QueueEntry | null>;
1028
- /** Disconnect from the state backend */
1029
- disconnect(): Promise<void>;
1030
- /** Atomically append a message to the thread's pending queue. Returns new queue depth. */
1031
- enqueue(threadId: string, entry: QueueEntry, maxSize: number): Promise<number>;
1032
- /** Extend a lock's TTL */
1033
- extendLock(lock: Lock, ttlMs: number): Promise<boolean>;
1034
- /**
1035
- * Force-release a lock on a thread, regardless of ownership token.
1036
- * The previous lock holder's handler continues running — only the lock is released.
1037
- * The old handler's `releaseLock()` becomes a no-op (token mismatch).
1038
- */
1039
- forceReleaseLock(threadId: string): Promise<void>;
1040
- /** Get a cached value by key */
1041
- get<T = unknown>(key: string): Promise<T | null>;
1042
- /** Read all values from a list in insertion order. Returns empty array if key does not exist. */
1043
- getList<T = unknown>(key: string): Promise<T[]>;
1044
- /** Check if subscribed to a thread */
1045
- isSubscribed(threadId: string): Promise<boolean>;
1046
- /** Get the current queue depth for a thread. */
1047
- queueDepth(threadId: string): Promise<number>;
1048
- /** Release a lock */
1049
- releaseLock(lock: Lock): Promise<void>;
1050
- /** Set a cached value with optional TTL in milliseconds */
1051
- set<T = unknown>(key: string, value: T, ttlMs?: number): Promise<void>;
1052
- /** Atomically set a value only if the key does not already exist. Returns true if set, false if key existed. */
1053
- setIfNotExists(key: string, value: unknown, ttlMs?: number): Promise<boolean>;
1054
- /** Subscribe to a thread (persists across restarts) */
1055
- subscribe(threadId: string): Promise<void>;
1056
- /** Unsubscribe from a thread */
1057
- unsubscribe(threadId: string): Promise<void>;
1058
- }
1059
- interface Lock {
1060
- expiresAt: number;
1061
- threadId: string;
1062
- token: string;
1063
- }
1064
- /**
1065
- * Base interface for entities that can receive messages.
1066
- * Both Thread and Channel extend this interface.
1067
- *
1068
- * @template TState - Custom state type stored per entity
1069
- * @template TRawMessage - Platform-specific raw message type
1070
- */
1071
- interface Postable<TState = Record<string, unknown>, TRawMessage = unknown> {
1072
- /** The adapter this entity belongs to */
1073
- readonly adapter: Adapter;
1074
- /** The visibility scope of this channel */
1075
- readonly channelVisibility: ChannelVisibility;
1076
- /** Unique ID */
1077
- readonly id: string;
1078
- /** Whether this is a direct message conversation */
1079
- readonly isDM: boolean;
1080
- /**
1081
- * Get a platform-specific mention string for a user.
1082
- */
1083
- mentionUser(userId: string): string;
1084
- /**
1085
- * Iterate messages newest first (backward from most recent).
1086
- * Auto-paginates lazily — only fetches pages as consumed.
1087
- */
1088
- readonly messages: AsyncIterable<Message<TRawMessage>>;
1089
- /**
1090
- * Post a message.
1091
- */
1092
- post<T extends PostableObject>(message: T): Promise<T>;
1093
- post(message: string | PostableMessage | ChatElement): Promise<SentMessage<TRawMessage>>;
1094
- /**
1095
- * Post an ephemeral message visible only to a specific user.
1096
- */
1097
- postEphemeral(user: string | Author, message: AdapterPostableMessage | ChatElement, options: PostEphemeralOptions): Promise<EphemeralMessage<TRawMessage> | null>;
1098
- /**
1099
- * Schedule a message for future delivery.
1100
- *
1101
- * Currently only supported by the Slack adapter. Other adapters
1102
- * will throw NotImplementedError.
1103
- *
1104
- * @param message - The message content (streaming not supported)
1105
- * @param options - Scheduling options including the target delivery time
1106
- * @returns A ScheduledMessage with cancel() capability
1107
- *
1108
- * @example
1109
- * ```typescript
1110
- * const scheduled = await thread.schedule("Reminder: standup!", {
1111
- * postAt: new Date("2026-03-09T09:00:00Z"),
1112
- * });
1113
- *
1114
- * // Cancel before it's sent
1115
- * await scheduled.cancel();
1116
- * ```
1117
- */
1118
- schedule(message: AdapterPostableMessage | ChatElement, options: {
1119
- postAt: Date;
1120
- }): Promise<ScheduledMessage<TRawMessage>>;
1121
- /**
1122
- * Set the state. Merges with existing state by default.
1123
- */
1124
- setState(state: Partial<TState>, options?: {
1125
- replace?: boolean;
1126
- }): Promise<void>;
1127
- /** Show typing indicator */
1128
- startTyping(status?: string): Promise<void>;
1129
- /**
1130
- * Get the current state.
1131
- * Returns null if no state has been set.
1132
- */
1133
- readonly state: Promise<TState | null>;
1134
- }
1135
- /**
1136
- * Represents a channel/conversation container that holds threads.
1137
- * Extends Postable for message posting capabilities.
1138
- *
1139
- * @template TState - Custom state type stored per channel
1140
- * @template TRawMessage - Platform-specific raw message type
1141
- */
1142
- interface Channel<TState = Record<string, unknown>, TRawMessage = unknown> extends Postable<TState, TRawMessage> {
1143
- /** Fetch channel metadata from the platform */
1144
- fetchMetadata(): Promise<ChannelInfo>;
1145
- /** Channel name (e.g., "#general"). Null until fetchInfo() is called. */
1146
- readonly name: string | null;
1147
- /**
1148
- * Iterate threads in this channel, most recently active first.
1149
- * Returns ThreadSummary (lightweight) for efficiency.
1150
- * Empty iterable on threadless platforms.
1151
- */
1152
- threads(): AsyncIterable<ThreadSummary<TRawMessage>>;
1153
- /**
1154
- * Serialize the channel to a plain JSON object.
1155
- * Use this to pass channel data to external systems like workflow engines.
1156
- */
1157
- toJSON(): SerializedChannel;
1158
- }
1159
- /**
1160
- * Lightweight summary of a thread within a channel.
1161
- */
1162
- interface ThreadSummary<TRawMessage = unknown> {
1163
- /** Full thread ID */
1164
- id: string;
1165
- /** Timestamp of most recent reply */
1166
- lastReplyAt?: Date;
1167
- /** Reply count (if available) */
1168
- replyCount?: number;
1169
- /** Root/first message of the thread */
1170
- rootMessage: Message<TRawMessage>;
1171
- }
1172
- /**
1173
- * Channel metadata returned by fetchInfo().
1174
- */
1175
- interface ChannelInfo {
1176
- /** The visibility scope of this channel */
1177
- channelVisibility?: ChannelVisibility;
1178
- id: string;
1179
- isDM?: boolean;
1180
- memberCount?: number;
1181
- metadata: Record<string, unknown>;
1182
- name?: string;
1183
- }
1184
- /**
1185
- * Options for listing threads in a channel.
1186
- */
1187
- interface ListThreadsOptions {
1188
- cursor?: string;
1189
- limit?: number;
1190
- }
1191
- /**
1192
- * Result of listing threads in a channel.
1193
- */
1194
- interface ListThreadsResult<TRawMessage = unknown> {
1195
- nextCursor?: string;
1196
- threads: ThreadSummary<TRawMessage>[];
1197
- }
1198
- /** Default TTL for thread state (30 days in milliseconds) */
1199
- declare const THREAD_STATE_TTL_MS: number;
1200
- /**
1201
- * Thread interface with support for custom state.
1202
- * Extends Postable for shared message posting capabilities.
1203
- *
1204
- * @template TState - Custom state type stored per-thread (default: Record<string, unknown>)
1205
- * @template TRawMessage - Platform-specific raw message type
1206
- */
1207
- interface Thread<TState = Record<string, unknown>, TRawMessage = unknown> extends Postable<TState, TRawMessage> {
1208
- /**
1209
- * Async iterator for all messages in the thread.
1210
- * Messages are yielded in chronological order (oldest first).
1211
- * Automatically handles pagination.
1212
- */
1213
- allMessages: AsyncIterable<Message<TRawMessage>>;
1214
- /** Get the Channel containing this thread */
1215
- readonly channel: Channel<TState, TRawMessage>;
1216
- /** Channel/conversation ID */
1217
- readonly channelId: string;
1218
- /**
1219
- * Wrap a Message object as a SentMessage with edit/delete capabilities.
1220
- * Used internally for reconstructing messages from serialized data.
1221
- */
1222
- createSentMessageFromMessage(message: Message<TRawMessage>): SentMessage<TRawMessage>;
1223
- /**
1224
- * Get the unique human participants in this thread.
1225
- *
1226
- * Scans all messages in the thread and returns deduplicated authors,
1227
- * excluding the bot itself. Useful for deciding whether to subscribe
1228
- * based on how many humans are participating — subscribe when it's a
1229
- * 1:1 conversation, unsubscribe when others join so humans can talk
1230
- * without the bot replying to every message.
1231
- *
1232
- * @returns Array of unique non-bot authors
1233
- *
1234
- * @example
1235
- * ```typescript
1236
- * // Subscribe only when one person is talking to the bot
1237
- * bot.onNewMention(async (thread, message) => {
1238
- * const participants = await thread.getParticipants();
1239
- * if (participants.length === 1) {
1240
- * await thread.subscribe();
1241
- * await thread.post("I'm here to help!");
1242
- * }
1243
- * });
1244
- *
1245
- * // Unsubscribe when the thread becomes a group conversation
1246
- * bot.onSubscribedMessage(async (thread, message) => {
1247
- * const participants = await thread.getParticipants();
1248
- * if (participants.length > 1) {
1249
- * await thread.unsubscribe();
1250
- * return;
1251
- * }
1252
- * await thread.post("Still here to help!");
1253
- * });
1254
- * ```
1255
- */
1256
- getParticipants(): Promise<Author[]>;
1257
- /**
1258
- * Check if this thread is currently subscribed.
1259
- *
1260
- * In subscribed message handlers, this is optimized to return true immediately
1261
- * without a state lookup, since we already know we're in a subscribed context.
1262
- *
1263
- * @returns Promise resolving to true if subscribed, false otherwise
1264
- */
1265
- isSubscribed(): Promise<boolean>;
1266
- /**
1267
- * Get a platform-specific mention string for a user.
1268
- * Use this to @-mention a user in a message.
1269
- * @example
1270
- * await thread.post(`Hey ${thread.mentionUser(userId)}, check this out!`);
1271
- */
1272
- mentionUser(userId: string): string;
1273
- /**
1274
- * Post a message to this thread.
1275
- *
1276
- * Supports text, markdown, cards, and streaming from async iterables.
1277
- * When posting a stream (e.g., from AI SDK), uses platform-native streaming
1278
- * APIs when available (Slack), or falls back to post + edit with throttling.
1279
- *
1280
- * @param message - String, PostableMessage, JSX Card, or AsyncIterable<string>
1281
- * @returns A SentMessage with methods to edit, delete, or add reactions
1282
- *
1283
- * @example
1284
- * ```typescript
1285
- * // Simple string
1286
- * await thread.post("Hello!");
1287
- *
1288
- * // Markdown
1289
- * await thread.post({ markdown: "**Bold** and _italic_" });
1290
- *
1291
- * // With emoji
1292
- * await thread.post(`${emoji.thumbs_up} Great job!`);
1293
- *
1294
- * // JSX Card (with @jsxImportSource chat)
1295
- * await thread.post(
1296
- * <Card title="Welcome!">
1297
- * <Text>Hello world</Text>
1298
- * </Card>
1299
- * );
1300
- *
1301
- * // Stream from AI SDK
1302
- * const result = await agent.stream({ prompt: message.text });
1303
- * await thread.post(result.textStream);
1304
- *
1305
- * // Stream with options via StreamingPlan PostableObject
1306
- * const stream = new StreamingPlan(result.fullStream, {
1307
- * groupTasks: "plan",
1308
- * endWith: [feedbackBlocks],
1309
- * });
1310
- * await thread.post(stream);
1311
- *
1312
- * // Plan with live updates
1313
- * const plan = new Plan({ initialMessage: "Working..." });
1314
- * await thread.post(plan);
1315
- * await plan.addTask({ title: "Step 1" });
1316
- * await plan.complete({ completeMessage: "Done!" });
1317
- * ```
1318
- */
1319
- post<T extends PostableObject>(message: T): Promise<T>;
1320
- post(message: string | PostableMessage | ChatElement): Promise<SentMessage<TRawMessage>>;
1321
- /**
1322
- * Post an ephemeral message visible only to a specific user.
1323
- *
1324
- * **Platform Behavior:**
1325
- * - **Slack**: Native ephemeral (session-dependent, disappears on reload)
1326
- * - **Google Chat**: Native private message (persists, only target user sees it)
1327
- * - **Discord**: No native support - requires fallbackToDM: true
1328
- * - **Teams**: No native support - requires fallbackToDM: true
1329
- *
1330
- * @param user - User ID string or Author object (from message.author or event.user)
1331
- * @param message - Message content (string, markdown, card, etc.). Streaming is not supported.
1332
- * @param options.fallbackToDM - Required. If true, falls back to DM when native
1333
- * ephemeral is not supported. If false, returns null when unsupported.
1334
- * @returns EphemeralMessage with `usedFallback: true` if DM was used, or null
1335
- * if native ephemeral not supported and fallbackToDM is false
1336
- *
1337
- * @example
1338
- * ```typescript
1339
- * // Always send (DM fallback on Discord/Teams)
1340
- * await thread.postEphemeral(user, 'Only you can see this!', { fallbackToDM: true })
1341
- *
1342
- * // Only send if native ephemeral supported (Slack/GChat)
1343
- * const result = await thread.postEphemeral(user, 'Secret!', { fallbackToDM: false })
1344
- * if (!result) {
1345
- * // Platform doesn't support native ephemeral - handle accordingly
1346
- * }
1347
- * ```
1348
- */
1349
- postEphemeral(user: string | Author, message: AdapterPostableMessage | ChatElement, options: PostEphemeralOptions): Promise<EphemeralMessage<TRawMessage> | null>;
1350
- /** Recently fetched messages (cached) */
1351
- recentMessages: Message<TRawMessage>[];
1352
- /**
1353
- * Refresh `recentMessages` from the API.
1354
- *
1355
- * Fetches the latest 50 messages and updates `recentMessages`.
1356
- */
1357
- refresh(): Promise<void>;
1358
- /**
1359
- * Show typing indicator in the thread.
1360
- *
1361
- * Some platforms support persistent typing indicators, others just send once.
1362
- * Optional status (e.g. "Typing...", "Searching documents...") is shown where supported.
1363
- */
1364
- startTyping(status?: string): Promise<void>;
1365
- /**
1366
- * Subscribe to future messages in this thread.
1367
- *
1368
- * Once subscribed, all messages in this thread will trigger `onSubscribedMessage` handlers.
1369
- * The initial message that triggered subscription will NOT fire the handler.
1370
- *
1371
- * @example
1372
- * ```typescript
1373
- * chat.onNewMention(async (thread, message) => {
1374
- * await thread.subscribe(); // Subscribe to follow-up messages
1375
- * await thread.post("I'm now watching this thread!");
1376
- * });
1377
- * ```
1378
- */
1379
- subscribe(): Promise<void>;
1380
- /**
1381
- * Serialize the thread to a plain JSON object.
1382
- * Use this to pass thread data to external systems like workflow engines.
1383
- */
1384
- toJSON(): SerializedThread;
1385
- /**
1386
- * Unsubscribe from this thread.
1387
- *
1388
- * Future messages will no longer trigger `onSubscribedMessage` handlers.
1389
- */
1390
- unsubscribe(): Promise<void>;
1391
- }
1392
-
1393
- interface ThreadInfo {
1394
- channelId: string;
1395
- channelName?: string;
1396
- /** The visibility scope of this channel */
1397
- channelVisibility?: ChannelVisibility;
1398
- id: string;
1399
- /** Whether this is a direct message conversation */
1400
- isDM?: boolean;
1401
- /** Platform-specific metadata */
1402
- metadata: Record<string, unknown>;
1403
- }
1404
- /**
1405
- * Direction for fetching messages.
1406
- *
1407
- * - `backward`: Fetch most recent messages first. Pagination moves toward older messages.
1408
- * This is the default, suitable for loading a chat view (show latest messages first).
1409
- *
1410
- * - `forward`: Fetch oldest messages first. Pagination moves toward newer messages.
1411
- * Suitable for iterating through message history from the beginning.
1412
- *
1413
- * In both directions, messages within each page are returned in chronological order
1414
- * (oldest first), which is the natural reading order for chat messages.
1415
- *
1416
- * @example
1417
- * ```typescript
1418
- * // Load most recent 50 messages (default)
1419
- * const recent = await adapter.fetchMessages(threadId, { limit: 50 });
1420
- * // recent.messages: [older, ..., newest] (chronological within page)
1421
- * // recent.nextCursor: points to older messages
1422
- *
1423
- * // Iterate through all history from beginning
1424
- * const history = await adapter.fetchMessages(threadId, {
1425
- * limit: 50,
1426
- * direction: 'forward',
1427
- * });
1428
- * // history.messages: [oldest, ..., newer] (chronological within page)
1429
- * // history.nextCursor: points to even newer messages
1430
- * ```
1431
- */
1432
- type FetchDirection = "forward" | "backward";
1433
- /**
1434
- * Options for fetching messages from a thread.
1435
- */
1436
- interface FetchOptions {
1437
- /**
1438
- * Pagination cursor for fetching the next page of messages.
1439
- * Pass the `nextCursor` from a previous `FetchResult`.
1440
- */
1441
- cursor?: string;
1442
- /**
1443
- * Direction to fetch messages.
1444
- *
1445
- * - `backward` (default): Fetch most recent messages. Cursor moves to older messages.
1446
- * - `forward`: Fetch oldest messages. Cursor moves to newer messages.
1447
- *
1448
- * Messages within each page are always returned in chronological order (oldest first).
1449
- */
1450
- direction?: FetchDirection;
1451
- /** Maximum number of messages to fetch. Default varies by adapter (50-100). */
1452
- limit?: number;
1453
- }
1454
- /**
1455
- * Result of fetching messages from a thread.
1456
- */
1457
- interface FetchResult<TRawMessage = unknown> {
1458
- /**
1459
- * Messages in chronological order (oldest first within this page).
1460
- *
1461
- * For `direction: 'backward'` (default): These are the N most recent messages.
1462
- * For `direction: 'forward'`: These are the N oldest messages (or next N after cursor).
1463
- */
1464
- messages: Message<TRawMessage>[];
1465
- /**
1466
- * Cursor for fetching the next page.
1467
- * Pass this as `cursor` in the next `fetchMessages` call.
1468
- *
1469
- * - For `direction: 'backward'`: Points to older messages.
1470
- * - For `direction: 'forward'`: Points to newer messages.
1471
- *
1472
- * Undefined if there are no more messages in that direction.
1473
- */
1474
- nextCursor?: string;
1475
- }
1476
- /**
1477
- * Formatted content using mdast AST.
1478
- * This is the canonical representation of message formatting.
1479
- */
1480
- type FormattedContent = Root;
1481
- /** Raw message returned from adapter (before wrapping as SentMessage) */
1482
- interface RawMessage<TRawMessage = unknown> {
1483
- id: string;
1484
- raw: TRawMessage;
1485
- threadId: string;
1486
- }
1487
- interface Author {
1488
- /** Display name */
1489
- fullName: string;
1490
- /** Whether the author is a bot */
1491
- isBot: boolean | "unknown";
1492
- /** Whether the author is this bot */
1493
- isMe: boolean;
1494
- /** Unique user ID */
1495
- userId: string;
1496
- /** Username/handle for @-mentions */
1497
- userName: string;
1498
- }
1499
- /** User information returned by adapter.getUser() */
1500
- interface UserInfo {
1501
- /** URL to the user's avatar/profile image */
1502
- avatarUrl?: string;
1503
- /** User's email address (requires appropriate scopes on some platforms) */
1504
- email?: string;
1505
- /** User's display name / full name */
1506
- fullName: string;
1507
- /** Whether the user is a bot */
1508
- isBot: boolean;
1509
- /** Platform-specific user ID */
1510
- userId: string;
1511
- /** Username/handle */
1512
- userName: string;
1513
- }
1514
- interface MessageMetadata {
1515
- /** When the message was sent */
1516
- dateSent: Date;
1517
- /** Whether the message has been edited */
1518
- edited: boolean;
1519
- /** When the message was last edited */
1520
- editedAt?: Date;
1521
- }
1522
- interface SentMessage<TRawMessage = unknown> extends Message<TRawMessage> {
1523
- /** Add a reaction to this message */
1524
- addReaction(emoji: EmojiValue | string): Promise<void>;
1525
- /** Delete this message */
1526
- delete(): Promise<void>;
1527
- /** Edit this message with text, a PostableMessage, or a JSX Card element */
1528
- edit(newContent: string | PostableMessage | ChatElement): Promise<SentMessage<TRawMessage>>;
1529
- /** Remove a reaction from this message */
1530
- removeReaction(emoji: EmojiValue | string): Promise<void>;
1531
- }
1532
- /**
1533
- * Result of posting an ephemeral message.
1534
- *
1535
- * Ephemeral messages are visible only to a specific user and typically
1536
- * cannot be edited or deleted (platform-dependent).
1537
- */
1538
- interface EphemeralMessage<TRawMessage = unknown> {
1539
- /** Message ID (may be empty for some platforms) */
1540
- id: string;
1541
- /** Platform-specific raw response */
1542
- raw: TRawMessage;
1543
- /** Thread ID where message was sent (or DM thread if fallback was used) */
1544
- threadId: string;
1545
- /** Whether this used native ephemeral or fell back to DM */
1546
- usedFallback: boolean;
1547
- }
1548
- /**
1549
- * Options for posting ephemeral messages.
1550
- */
1551
- interface PostEphemeralOptions {
1552
- /**
1553
- * Controls behavior when native ephemeral is not supported by the platform.
1554
- *
1555
- * - `true`: Falls back to sending a DM to the user
1556
- * - `false`: Returns `null` if native ephemeral is not supported
1557
- */
1558
- fallbackToDM: boolean;
1559
- }
1560
- /**
1561
- * Result of scheduling a message for future delivery.
1562
- *
1563
- * Currently only supported by the Slack adapter via `chat.scheduleMessage`.
1564
- * Other adapters will throw `NotImplementedError` when `schedule()` is called.
1565
- */
1566
- interface ScheduledMessage<TRawMessage = unknown> {
1567
- /** Cancel the scheduled message before it's sent */
1568
- cancel(): Promise<void>;
1569
- /** Channel ID where the message will be posted */
1570
- channelId: string;
1571
- /** When the message will be sent */
1572
- postAt: Date;
1573
- /** Platform-specific raw response */
1574
- raw: TRawMessage;
1575
- /** Platform-specific scheduled message ID */
1576
- scheduledMessageId: string;
1577
- }
1578
- /**
1579
- * Input type for adapter postMessage/editMessage methods.
1580
- * This excludes streams since adapters handle content synchronously.
1581
- */
1582
- type AdapterPostableMessage = string | PostableRaw | PostableMarkdown | PostableAst | PostableCard | CardElement;
1583
- /**
1584
- * A message that can be posted to a thread.
1585
- *
1586
- * - `string` - Raw text, passed through as-is to the platform
1587
- * - `{ raw: string }` - Explicit raw text, passed through as-is
1588
- * - `{ markdown: string }` - Markdown text, converted to platform format
1589
- * - `{ ast: Root }` - mdast AST, converted to platform format
1590
- * - `{ card: CardElement }` - Rich card with buttons (Block Kit / Adaptive Cards / GChat Cards)
1591
- * - `CardElement` - Direct card element
1592
- * - `AsyncIterable<string>` - Streaming text (e.g., from AI SDK's textStream)
1593
- * - `AsyncIterable<string | StreamEvent>` - AI SDK fullStream (auto-detected, extracts text with step separators)
1594
- */
1595
- type PostableMessage = AdapterPostableMessage | AsyncIterable<string | StreamChunk | StreamEvent> | PostableObject;
1596
- /**
1597
- * Duck-typed stream event compatible with AI SDK's `fullStream`.
1598
- * - `text-delta` events are extracted as text output.
1599
- * - `step-finish` events trigger paragraph separators between steps.
1600
- * - All other event types (tool-call, tool-result, etc.) are silently skipped.
1601
- */
1602
- type StreamEvent = {
1603
- textDelta: string;
1604
- type: "text-delta";
1605
- } | {
1606
- type: "step-finish";
1607
- } | {
1608
- type: string;
1609
- };
1610
- interface PostableRaw {
1611
- /** File/image attachments */
1612
- attachments?: Attachment[];
1613
- /** Files to upload */
1614
- files?: FileUpload[];
1615
- /** Raw text passed through as-is to the platform */
1616
- raw: string;
1617
- }
1618
- interface PostableMarkdown {
1619
- /** File/image attachments */
1620
- attachments?: Attachment[];
1621
- /** Files to upload */
1622
- files?: FileUpload[];
1623
- /** Markdown text, converted to platform format */
1624
- markdown: string;
1625
- }
1626
- interface PostableAst {
1627
- /** mdast AST, converted to platform format */
1628
- ast: Root;
1629
- /** File/image attachments */
1630
- attachments?: Attachment[];
1631
- /** Files to upload */
1632
- files?: FileUpload[];
1633
- }
1634
- interface PostableCard {
1635
- /** Rich card element */
1636
- card: CardElement;
1637
- /** Fallback text for platforms/clients that can't render cards */
1638
- fallbackText?: string;
1639
- /** Files to upload */
1640
- files?: FileUpload[];
1641
- }
1642
- interface Attachment {
1643
- /** Binary data (for uploading or if already fetched) */
1644
- data?: Buffer | Blob;
1645
- /**
1646
- * Fetch the attachment data.
1647
- * For platforms that require authentication (like Slack private URLs),
1648
- * this method handles the auth automatically.
1649
- */
1650
- fetchData?: () => Promise<Buffer>;
1651
- /**
1652
- * Platform-specific metadata needed to reconstruct fetchData after serialization.
1653
- * Adapters store IDs here (e.g. WhatsApp mediaId, Telegram fileId) so that
1654
- * fetchData can be rebuilt when a message is rehydrated from the queue.
1655
- */
1656
- fetchMetadata?: Record<string, string>;
1657
- /** Image/video height (if applicable) */
1658
- height?: number;
1659
- /** MIME type */
1660
- mimeType?: string;
1661
- /** Filename */
1662
- name?: string;
1663
- /** File size in bytes */
1664
- size?: number;
1665
- /** Type of attachment */
1666
- type: "image" | "file" | "video" | "audio";
1667
- /** URL to the file (for linking/downloading) */
1668
- url?: string;
1669
- /** Image/video width (if applicable) */
1670
- width?: number;
1671
- }
1672
- /**
1673
- * A link found in a message, with optional unfurl metadata.
1674
- *
1675
- * On the initial message event, only `url` is available (unfurl metadata
1676
- * arrives later via `message_changed`). The `fetchMessage` callback is
1677
- * provided when the URL points to another chat message on the same platform.
1678
- */
1679
- interface LinkPreview {
1680
- /** Description from unfurl metadata (if available) */
1681
- description?: string;
1682
- /** If this links to a chat message, fetch the full Message */
1683
- fetchMessage?: () => Promise<Message>;
1684
- /** Preview image URL (if available) */
1685
- imageUrl?: string;
1686
- /** Site name (e.g., "Vercel") */
1687
- siteName?: string;
1688
- /** Title from unfurl metadata (if available) */
1689
- title?: string;
1690
- /** The URL */
1691
- url: string;
1692
- }
1693
- /**
1694
- * File to upload with a message.
1695
- */
1696
- interface FileUpload {
1697
- /** Binary data */
1698
- data: Buffer | Blob | ArrayBuffer;
1699
- /** Filename */
1700
- filename: string;
1701
- /** MIME type (optional, will be inferred from filename if not provided) */
1702
- mimeType?: string;
1703
- }
1704
- /**
1705
- * Handler for new @-mentions of the bot.
1706
- *
1707
- * **Important**: This handler is ONLY called for mentions in **unsubscribed** threads.
1708
- * Once a thread is subscribed (via `thread.subscribe()`), subsequent messages
1709
- * including @-mentions go to `onSubscribedMessage` handlers instead.
1710
- *
1711
- * To detect mentions in subscribed threads, check `message.isMention`:
1712
- *
1713
- * @example
1714
- * ```typescript
1715
- * // Handle new mentions (unsubscribed threads only)
1716
- * chat.onNewMention(async (thread, message) => {
1717
- * await thread.subscribe(); // Subscribe to follow-up messages
1718
- * await thread.post("Hello! I'll be watching this thread.");
1719
- * });
1720
- *
1721
- * // Handle all messages in subscribed threads
1722
- * chat.onSubscribedMessage(async (thread, message) => {
1723
- * if (message.isMention) {
1724
- * // User @-mentioned us in a thread we're already watching
1725
- * await thread.post("You mentioned me again!");
1726
- * }
1727
- * });
1728
- * ```
1729
- */
1730
- type MentionHandler<TState = Record<string, unknown>> = (thread: Thread<TState>, message: Message, context?: MessageContext) => void | Promise<void>;
1731
- /**
1732
- * Handler for direct messages (1:1 conversations with the bot).
1733
- *
1734
- * Registered via `chat.onDirectMessage(handler)`. Called when a message
1735
- * is received in a DM thread that is not subscribed. If no `onDirectMessage`
1736
- * handlers are registered, DMs fall through to `onNewMention` for backward
1737
- * compatibility.
1738
- */
1739
- type DirectMessageHandler<TState = Record<string, unknown>> = (thread: Thread<TState>, message: Message, channel: Channel<TState>, context?: MessageContext) => void | Promise<void>;
1740
- /**
1741
- * Handler for messages matching a regex pattern.
1742
- *
1743
- * Registered via `chat.onNewMessage(pattern, handler)`. Called when a message
1744
- * matches the pattern in an unsubscribed thread.
1745
- */
1746
- type MessageHandler<TState = Record<string, unknown>> = (thread: Thread<TState>, message: Message, context?: MessageContext) => void | Promise<void>;
1747
- /**
1748
- * Handler for messages in subscribed threads.
1749
- *
1750
- * Called for all messages in threads that have been subscribed via `thread.subscribe()`.
1751
- * This includes:
1752
- * - Follow-up messages from users
1753
- * - Messages that @-mention the bot (check `message.isMention`)
1754
- *
1755
- * Does NOT fire for:
1756
- * - The message that triggered the subscription (e.g., the initial @mention)
1757
- * - Messages sent by the bot itself
1758
- *
1759
- * @example
1760
- * ```typescript
1761
- * chat.onSubscribedMessage(async (thread, message) => {
1762
- * // Handle all follow-up messages
1763
- * if (message.isMention) {
1764
- * // User @-mentioned us in a subscribed thread
1765
- * }
1766
- * await thread.post(`Got your message: ${message.text}`);
1767
- * });
1768
- * ```
1769
- */
1770
- type SubscribedMessageHandler<TState = Record<string, unknown>> = (thread: Thread<TState>, message: Message, context?: MessageContext) => void | Promise<void>;
1771
- /**
1772
- * Well-known emoji that work across platforms (Slack and Google Chat).
1773
- * These are normalized to a common format regardless of platform.
1774
- */
1775
- type WellKnownEmoji = "thumbs_up" | "thumbs_down" | "clap" | "wave" | "pray" | "muscle" | "ok_hand" | "point_up" | "point_down" | "point_left" | "point_right" | "raised_hands" | "shrug" | "facepalm" | "heart" | "smile" | "laugh" | "thinking" | "sad" | "cry" | "angry" | "love_eyes" | "cool" | "wink" | "surprised" | "worried" | "confused" | "neutral" | "sleeping" | "sick" | "mind_blown" | "relieved" | "grimace" | "rolling_eyes" | "hug" | "zany" | "check" | "x" | "question" | "exclamation" | "warning" | "stop" | "info" | "100" | "fire" | "star" | "sparkles" | "lightning" | "boom" | "eyes" | "green_circle" | "yellow_circle" | "red_circle" | "blue_circle" | "white_circle" | "black_circle" | "rocket" | "party" | "confetti" | "balloon" | "gift" | "trophy" | "medal" | "lightbulb" | "gear" | "wrench" | "hammer" | "bug" | "link" | "lock" | "unlock" | "key" | "pin" | "memo" | "clipboard" | "calendar" | "clock" | "hourglass" | "bell" | "megaphone" | "speech_bubble" | "email" | "inbox" | "outbox" | "package" | "folder" | "file" | "chart_up" | "chart_down" | "coffee" | "pizza" | "beer" | "arrow_up" | "arrow_down" | "arrow_left" | "arrow_right" | "refresh" | "sun" | "cloud" | "rain" | "snow" | "rainbow";
1776
- /**
1777
- * Platform-specific emoji formats for a single emoji.
1778
- */
1779
- interface EmojiFormats {
1780
- /** Google Chat unicode emoji, e.g., "👍", "❤️" */
1781
- gchat: string | string[];
1782
- /** Slack emoji name (without colons), e.g., "+1", "heart" */
1783
- slack: string | string[];
1784
- }
1785
- /**
1786
- * Emoji map type - can be extended by users to add custom emoji.
1787
- *
1788
- * @example
1789
- * ```typescript
1790
- * // Extend with custom emoji
1791
- * declare module "chat" {
1792
- * interface CustomEmojiMap {
1793
- * "custom_emoji": EmojiFormats;
1794
- * }
1795
- * }
1796
- *
1797
- * const myEmojiMap: EmojiMapConfig = {
1798
- * custom_emoji: { slack: "custom", gchat: "🎯" },
1799
- * };
1800
- * ```
1801
- */
1802
- interface CustomEmojiMap {
1803
- }
1804
- /**
1805
- * Full emoji type including well-known and custom emoji.
1806
- */
1807
- type Emoji = WellKnownEmoji | keyof CustomEmojiMap;
1808
- /**
1809
- * Configuration for emoji mapping.
1810
- */
1811
- type EmojiMapConfig = Partial<Record<Emoji, EmojiFormats>>;
1812
- /**
1813
- * Immutable emoji value object with object identity.
1814
- *
1815
- * These objects are singletons - the same emoji name always returns
1816
- * the same frozen object instance, enabling `===` comparison.
1817
- *
1818
- * @example
1819
- * ```typescript
1820
- * // Object identity comparison works
1821
- * if (event.emoji === emoji.thumbs_up) {
1822
- * console.log("User gave a thumbs up!");
1823
- * }
1824
- *
1825
- * // Works in template strings via toString()
1826
- * await thread.post(`${emoji.thumbs_up} Great job!`);
1827
- * ```
1828
- */
1829
- interface EmojiValue {
1830
- /** The normalized emoji name (e.g., "thumbs_up") */
1831
- readonly name: string;
1832
- /** Returns the placeholder string (for JSON.stringify) */
1833
- toJSON(): string;
1834
- /** Returns the placeholder string for message formatting */
1835
- toString(): string;
1836
- }
1837
- /**
1838
- * Reaction event fired when a user adds or removes a reaction.
1839
- */
1840
- interface ReactionEvent<TRawMessage = unknown> {
1841
- /** The adapter that received the event */
1842
- adapter: Adapter;
1843
- /** Whether the reaction was added (true) or removed (false) */
1844
- added: boolean;
1845
- /** The normalized emoji as an EmojiValue singleton (enables `===` comparison) */
1846
- emoji: EmojiValue;
1847
- /** The message that was reacted to (if available) */
1848
- message?: Message<TRawMessage>;
1849
- /** The message ID that was reacted to */
1850
- messageId: string;
1851
- /** Platform-specific raw event data */
1852
- raw: unknown;
1853
- /** The raw platform-specific emoji (e.g., "+1" for Slack, "👍" for GChat) */
1854
- rawEmoji: string;
1855
- /**
1856
- * The thread where the reaction occurred.
1857
- * Use this to post replies or check subscription status.
1858
- *
1859
- * @example
1860
- * ```typescript
1861
- * chat.onReaction([emoji.thumbs_up], async (event) => {
1862
- * await event.thread.post(`Thanks for the ${event.emoji}!`);
1863
- * });
1864
- * ```
1865
- */
1866
- thread: Thread<TRawMessage>;
1867
- /** The thread ID */
1868
- threadId: string;
1869
- /** The user who added/removed the reaction */
1870
- user: Author;
1871
- }
1872
- /**
1873
- * Handler for reaction events.
1874
- *
1875
- * @example
1876
- * ```typescript
1877
- * // Handle specific emoji
1878
- * chat.onReaction(["thumbs_up", "heart"], async (event) => {
1879
- * console.log(`${event.user.userName} ${event.added ? "added" : "removed"} ${event.emoji}`);
1880
- * });
1881
- *
1882
- * // Handle all reactions
1883
- * chat.onReaction(async (event) => {
1884
- * // ...
1885
- * });
1886
- * ```
1887
- */
1888
- type ReactionHandler = (event: ReactionEvent) => void | Promise<void>;
1889
- /**
1890
- * Action event fired when a user clicks a button in a card.
1891
- *
1892
- * @example
1893
- * ```typescript
1894
- * chat.onAction("approve", async (event) => {
1895
- * await event.thread.post(`Order ${event.value} approved by ${event.user.userName}`);
1896
- * });
1897
- * ```
1898
- */
1899
- interface ActionEvent<TRawMessage = unknown> {
1900
- /** The action ID from the button (matches Button's `id` prop) */
1901
- actionId: string;
1902
- /** The adapter that received the event */
1903
- adapter: Adapter;
1904
- /** The message ID containing the card */
1905
- messageId: string;
1906
- /**
1907
- * Open a modal/dialog form in response to this action.
1908
- *
1909
- * @param modal - The modal element to display (JSX or ModalElement)
1910
- * @returns The view/dialog ID, or undefined if modals are not supported
1911
- */
1912
- openModal(modal: ModalElement | ChatElement): Promise<{
1913
- viewId: string;
1914
- } | undefined>;
1915
- /** Platform-specific raw event data */
1916
- raw: unknown;
1917
- /** The thread where the action occurred (null for view-based actions like home tab buttons) */
1918
- thread: Thread<TRawMessage> | null;
1919
- /** The thread ID */
1920
- threadId: string;
1921
- /** Trigger ID for opening modals (required by some platforms, may expire quickly) */
1922
- triggerId?: string;
1923
- /** User who clicked the button */
1924
- user: Author;
1925
- /** Optional value/payload from the button */
1926
- value?: string;
1927
- }
1928
- /**
1929
- * Handler for action events (button clicks in cards).
1930
- *
1931
- * @example
1932
- * ```typescript
1933
- * // Handle specific action
1934
- * chat.onAction("approve", async (event) => {
1935
- * await event.thread.post("Approved!");
1936
- * });
1937
- *
1938
- * // Handle multiple actions
1939
- * chat.onAction(["approve", "reject"], async (event) => {
1940
- * if (event.actionId === "approve") {
1941
- * // ...
1942
- * }
1943
- * });
1944
- *
1945
- * // Handle all actions (catch-all)
1946
- * chat.onAction(async (event) => {
1947
- * console.log(`Action: ${event.actionId}`);
1948
- * });
1949
- * ```
1950
- */
1951
- type ActionHandler = (event: ActionEvent) => void | Promise<void>;
1952
- /**
1953
- * Event emitted when an adapter needs dynamic options for an external select.
1954
- */
1955
- interface OptionsLoadEvent {
1956
- /** The action ID of the select requesting options */
1957
- actionId: string;
1958
- /** The adapter that received this event */
1959
- adapter: Adapter;
1960
- /** The current user-entered query text */
1961
- query: string;
1962
- /** Raw platform-specific payload */
1963
- raw: unknown;
1964
- /** The user requesting options */
1965
- user: Author;
1966
- }
1967
- interface OptionsLoadGroup {
1968
- label: string;
1969
- options: SelectOptionElement[];
1970
- }
1971
- type OptionsLoadResult = SelectOptionElement[] | OptionsLoadGroup[];
1972
- type OptionsLoadHandler = (event: OptionsLoadEvent) => OptionsLoadResult | Promise<OptionsLoadResult | undefined> | undefined;
1973
- /**
1974
- * Event emitted when a user submits a modal form.
1975
- */
1976
- interface ModalSubmitEvent<TRawMessage = unknown> {
1977
- /** The adapter that received this event */
1978
- adapter: Adapter;
1979
- /** The callback ID specified when creating the modal */
1980
- callbackId: string;
1981
- /**
1982
- * The private metadata string set when the modal was created.
1983
- * Use this to pass arbitrary context (e.g., JSON) through the modal lifecycle.
1984
- */
1985
- privateMetadata?: string;
1986
- /** Raw platform-specific payload */
1987
- raw: unknown;
1988
- /**
1989
- * The channel where the modal was originally triggered from.
1990
- * Available when the modal was opened via SlashCommandEvent.openModal().
1991
- */
1992
- relatedChannel?: Channel<Record<string, unknown>, TRawMessage>;
1993
- /**
1994
- * The message that contained the action which opened the modal.
1995
- * Available when the modal was opened from a message action via ActionEvent.openModal().
1996
- * This is a SentMessage with edit/delete capabilities.
1997
- */
1998
- relatedMessage?: SentMessage<TRawMessage>;
1999
- /**
2000
- * The thread where the modal was originally triggered from.
2001
- * Available when the modal was opened via ActionEvent.openModal().
2002
- */
2003
- relatedThread?: Thread<Record<string, unknown>, TRawMessage>;
2004
- /** The user who submitted the modal */
2005
- user: Author;
2006
- /** Form field values keyed by input ID */
2007
- values: Record<string, string>;
2008
- /** Platform-specific view/dialog ID */
2009
- viewId: string;
2010
- }
2011
- /**
2012
- * Event emitted when a user closes/cancels a modal (requires notifyOnClose).
2013
- */
2014
- interface ModalCloseEvent<TRawMessage = unknown> {
2015
- /** The adapter that received this event */
2016
- adapter: Adapter;
2017
- /** The callback ID specified when creating the modal */
2018
- callbackId: string;
2019
- /**
2020
- * The private metadata string set when the modal was created.
2021
- * Use this to pass arbitrary context (e.g., JSON) through the modal lifecycle.
2022
- */
2023
- privateMetadata?: string;
2024
- /** Raw platform-specific payload */
2025
- raw: unknown;
2026
- /**
2027
- * The channel where the modal was originally triggered from.
2028
- * Available when the modal was opened via SlashCommandEvent.openModal().
2029
- */
2030
- relatedChannel?: Channel<Record<string, unknown>, TRawMessage>;
2031
- /**
2032
- * The message that contained the action which opened the modal.
2033
- * Available when the modal was opened from a message action via ActionEvent.openModal().
2034
- * This is a SentMessage with edit/delete capabilities.
2035
- */
2036
- relatedMessage?: SentMessage<TRawMessage>;
2037
- /**
2038
- * The thread where the modal was originally triggered from.
2039
- * Available when the modal was opened via ActionEvent.openModal().
2040
- */
2041
- relatedThread?: Thread<Record<string, unknown>, TRawMessage>;
2042
- /** The user who closed the modal */
2043
- user: Author;
2044
- /** Platform-specific view/dialog ID */
2045
- viewId: string;
2046
- }
2047
- interface ModalErrorsResponse {
2048
- action: "errors";
2049
- errors: Record<string, string>;
2050
- }
2051
- interface ModalUpdateResponse {
2052
- action: "update";
2053
- modal: ModalElement;
2054
- }
2055
- interface ModalPushResponse {
2056
- action: "push";
2057
- modal: ModalElement;
2058
- }
2059
- interface ModalCloseResponse {
2060
- action: "close";
2061
- }
2062
- interface ModalClearResponse {
2063
- action: "clear";
2064
- }
2065
- type ModalResponse = ModalCloseResponse | ModalClearResponse | ModalErrorsResponse | ModalUpdateResponse | ModalPushResponse;
2066
- type ModalSubmitHandler = (event: ModalSubmitEvent) => void | Promise<ModalResponse | void | undefined>;
2067
- type ModalCloseHandler = (event: ModalCloseEvent) => void | Promise<void>;
2068
- /**
2069
- * Event emitted when a user invokes a slash command.
2070
- *
2071
- * Slash commands are triggered when a user types `/command` in the message composer.
2072
- * The event provides access to the channel where the command was invoked, allowing
2073
- * you to post responses using standard SDK methods.
2074
- *
2075
- * @example
2076
- * ```typescript
2077
- * chat.onSlashCommand("/help", async (event) => {
2078
- * // Post visible to everyone in the channel
2079
- * await event.channel.post("Here are the available commands...");
2080
- * });
2081
- *
2082
- * chat.onSlashCommand("/secret", async (event) => {
2083
- * // Post ephemeral (only the invoking user sees it)
2084
- * await event.channel.postEphemeral(
2085
- * event.user,
2086
- * "This is just for you!",
2087
- * { fallbackToDM: false }
2088
- * );
2089
- * });
2090
- *
2091
- * chat.onSlashCommand("/feedback", async (event) => {
2092
- * // Open a modal
2093
- * await event.openModal({
2094
- * type: "modal",
2095
- * callbackId: "feedback_modal",
2096
- * title: "Submit Feedback",
2097
- * children: [{ type: "text_input", id: "feedback", label: "Your feedback" }],
2098
- * });
2099
- * });
2100
- * ```
2101
- */
2102
- interface SlashCommandEvent<TState = Record<string, unknown>> {
2103
- /** The adapter that received this event */
2104
- adapter: Adapter;
2105
- /** The channel where the command was invoked */
2106
- channel: Channel<TState>;
2107
- /** The slash command name (e.g., "/help") */
2108
- command: string;
2109
- /**
2110
- * Open a modal/dialog form in response to this slash command.
2111
- *
2112
- * @param modal - The modal element to display (JSX or ModalElement)
2113
- * @returns The view/dialog ID, or undefined if modals are not supported
2114
- */
2115
- openModal(modal: ModalElement | ChatElement): Promise<{
2116
- viewId: string;
2117
- } | undefined>;
2118
- /** Platform-specific raw payload */
2119
- raw: unknown;
2120
- /** Arguments text after the command (e.g., "topic search" from "/help topic search") */
2121
- text: string;
2122
- /** Trigger ID for opening modals (time-limited, typically ~3 seconds) */
2123
- triggerId?: string;
2124
- /** The user who invoked the command */
2125
- user: Author;
2126
- }
2127
- /**
2128
- * Handler for slash command events.
2129
- *
2130
- * @example
2131
- * ```typescript
2132
- * // Handle a specific command
2133
- * chat.onSlashCommand("/status", async (event) => {
2134
- * await event.channel.post("All systems operational!");
2135
- * });
2136
- *
2137
- * // Handle multiple commands
2138
- * chat.onSlashCommand(["/help", "/info"], async (event) => {
2139
- * await event.channel.post(`You invoked ${event.command}`);
2140
- * });
2141
- *
2142
- * // Catch-all handler
2143
- * chat.onSlashCommand(async (event) => {
2144
- * console.log(`Command: ${event.command}, Args: ${event.text}`);
2145
- * });
2146
- * ```
2147
- */
2148
- type SlashCommandHandler<TState = Record<string, unknown>> = (event: SlashCommandEvent<TState>) => void | Promise<void>;
2149
- interface AssistantThreadStartedEvent {
2150
- adapter: Adapter;
2151
- channelId: string;
2152
- context: {
2153
- channelId?: string;
2154
- teamId?: string;
2155
- enterpriseId?: string;
2156
- threadEntryPoint?: string;
2157
- forceSearch?: boolean;
2158
- };
2159
- threadId: string;
2160
- threadTs: string;
2161
- userId: string;
2162
- }
2163
- type AssistantThreadStartedHandler = (event: AssistantThreadStartedEvent) => void | Promise<void>;
2164
- interface AssistantContextChangedEvent {
2165
- adapter: Adapter;
2166
- channelId: string;
2167
- context: {
2168
- channelId?: string;
2169
- teamId?: string;
2170
- enterpriseId?: string;
2171
- threadEntryPoint?: string;
2172
- forceSearch?: boolean;
2173
- };
2174
- threadId: string;
2175
- threadTs: string;
2176
- userId: string;
2177
- }
2178
- type AssistantContextChangedHandler = (event: AssistantContextChangedEvent) => void | Promise<void>;
2179
- interface AppHomeOpenedEvent {
2180
- adapter: Adapter;
2181
- channelId: string;
2182
- userId: string;
2183
- }
2184
- type AppHomeOpenedHandler = (event: AppHomeOpenedEvent) => void | Promise<void>;
2185
- interface MemberJoinedChannelEvent {
2186
- adapter: Adapter;
2187
- channelId: string;
2188
- inviterId?: string;
2189
- userId: string;
2190
- }
2191
- type MemberJoinedChannelHandler = (event: MemberJoinedChannelEvent) => void | Promise<void>;
2192
-
2193
- /**
2194
- * Message class with serialization support for workflow engines.
2195
- */
2196
-
2197
- /**
2198
- * Input data for creating a Message instance.
2199
- * Use this interface when constructing Message objects.
2200
- */
2201
- interface MessageData<TRawMessage = unknown> {
2202
- /** Attachments */
2203
- attachments: Attachment[];
2204
- /** Message author */
2205
- author: Author;
2206
- /** Structured formatting as an AST (mdast Root) */
2207
- formatted: FormattedContent;
2208
- /** Unique message ID */
2209
- id: string;
2210
- /** Whether the bot is @-mentioned in this message */
2211
- isMention?: boolean;
2212
- /** Links found in the message */
2213
- links?: LinkPreview[];
2214
- /** Message metadata */
2215
- metadata: MessageMetadata;
2216
- /** Platform-specific raw payload (escape hatch) */
2217
- raw: TRawMessage;
2218
- /** Plain text content (all formatting stripped) */
2219
- text: string;
2220
- /** Thread this message belongs to */
2221
- threadId: string;
2222
- }
2223
- /**
2224
- * Serialized message data for passing to external systems (e.g., workflow engines).
2225
- * Dates are converted to ISO strings, and non-serializable fields are omitted.
2226
- */
2227
- interface SerializedMessage {
2228
- _type: "chat:Message";
2229
- attachments: Array<{
2230
- type: "image" | "file" | "video" | "audio";
2231
- url?: string;
2232
- name?: string;
2233
- mimeType?: string;
2234
- size?: number;
2235
- width?: number;
2236
- height?: number;
2237
- fetchMetadata?: Record<string, string>;
2238
- }>;
2239
- author: {
2240
- userId: string;
2241
- userName: string;
2242
- fullName: string;
2243
- isBot: boolean | "unknown";
2244
- isMe: boolean;
2245
- };
2246
- formatted: Root;
2247
- id: string;
2248
- isMention?: boolean;
2249
- links?: Array<{
2250
- url: string;
2251
- title?: string;
2252
- description?: string;
2253
- imageUrl?: string;
2254
- siteName?: string;
2255
- }>;
2256
- metadata: {
2257
- dateSent: string;
2258
- edited: boolean;
2259
- editedAt?: string;
2260
- };
2261
- raw: unknown;
2262
- text: string;
2263
- threadId: string;
2264
- }
2265
- /**
2266
- * A chat message with serialization support for workflow engines.
2267
- *
2268
- * @example
2269
- * ```typescript
2270
- * // Create a message
2271
- * const message = new Message({
2272
- * id: "msg-1",
2273
- * threadId: "slack:C123:1234.5678",
2274
- * text: "Hello world",
2275
- * formatted: parseMarkdown("Hello world"),
2276
- * raw: {},
2277
- * author: { userId: "U123", userName: "user", fullName: "User", isBot: false, isMe: false },
2278
- * metadata: { dateSent: new Date(), edited: false },
2279
- * attachments: [],
2280
- * });
2281
- *
2282
- * // Serialize for workflow
2283
- * const serialized = message.toJSON();
2284
- * ```
2285
- */
2286
- declare class Message<TRawMessage = unknown> {
2287
- /** Unique message ID */
2288
- readonly id: string;
2289
- /** Thread this message belongs to */
2290
- readonly threadId: string;
2291
- /** Plain text content (all formatting stripped) */
2292
- text: string;
2293
- /**
2294
- * Structured formatting as an AST (mdast Root).
2295
- * This is the canonical representation - use this for processing.
2296
- * Use `stringifyMarkdown(message.formatted)` to get markdown string.
2297
- */
2298
- formatted: FormattedContent;
2299
- /** Platform-specific raw payload (escape hatch) */
2300
- raw: TRawMessage;
2301
- /** Message author */
2302
- author: Author;
2303
- /** Message metadata */
2304
- metadata: MessageMetadata;
2305
- /** Attachments */
2306
- attachments: Attachment[];
2307
- /**
2308
- * Whether the bot is @-mentioned in this message.
2309
- *
2310
- * This is set by the Chat SDK before passing the message to handlers.
2311
- * It checks for `@username` in the message text using the adapter's
2312
- * configured `userName` and optional `botUserId`.
2313
- *
2314
- * @example
2315
- * ```typescript
2316
- * chat.onSubscribedMessage(async (thread, message) => {
2317
- * if (message.isMention) {
2318
- * await thread.post("You mentioned me!");
2319
- * }
2320
- * });
2321
- * ```
2322
- */
2323
- isMention?: boolean;
2324
- /** Links found in the message */
2325
- links: LinkPreview[];
2326
- constructor(data: MessageData<TRawMessage>);
2327
- /**
2328
- * Serialize the message to a plain JSON object.
2329
- * Use this to pass message data to external systems like workflow engines.
2330
- *
2331
- * Note: Attachment `data` (Buffer) and `fetchData` (function) are omitted
2332
- * as they're not serializable.
2333
- */
2334
- toJSON(): SerializedMessage;
2335
- /**
2336
- * Reconstruct a Message from serialized JSON data.
2337
- * Converts ISO date strings back to Date objects.
2338
- */
2339
- static fromJSON<TRawMessage = unknown>(json: SerializedMessage): Message<TRawMessage>;
2340
- /**
2341
- * Serialize a Message instance for @workflow/serde.
2342
- * This static method is automatically called by workflow serialization.
2343
- */
2344
- static [WORKFLOW_SERIALIZE](instance: Message): SerializedMessage;
2345
- /**
2346
- * Deserialize a Message from @workflow/serde.
2347
- * This static method is automatically called by workflow deserialization.
2348
- */
2349
- static [WORKFLOW_DESERIALIZE](data: SerializedMessage): Message;
2350
- }
2351
-
2352
- /**
2353
- * Content part types structurally identical to AI SDK's TextPart, ImagePart,
2354
- * FilePart so that AiMessage[] is directly assignable to ModelMessage[].
2355
- * @see https://ai-sdk.dev/docs/reference/ai-sdk-core/model-message
2356
- */
2357
- /** Matches AI SDK's DataContent */
2358
- type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
2359
- interface AiTextPart {
2360
- text: string;
2361
- type: "text";
2362
- }
2363
- interface AiImagePart {
2364
- image: DataContent | URL;
2365
- mediaType?: string;
2366
- type: "image";
2367
- }
2368
- interface AiFilePart {
2369
- data: DataContent | URL;
2370
- filename?: string;
2371
- mediaType: string;
2372
- type: "file";
2373
- }
2374
- type AiMessagePart = AiTextPart | AiImagePart | AiFilePart;
2375
- /**
2376
- * A message formatted for AI SDK consumption.
2377
- *
2378
- * This is a discriminated union matching AI SDK's ModelMessage type:
2379
- * - User messages can have text, image, and file parts
2380
- * - Assistant messages have string content only
2381
- */
2382
- type AiMessage = AiUserMessage | AiAssistantMessage;
2383
- interface AiUserMessage {
2384
- content: string | AiMessagePart[];
2385
- role: "user";
2386
- }
2387
- interface AiAssistantMessage {
2388
- content: string;
2389
- role: "assistant";
2390
- }
2391
- /**
2392
- * Options for converting messages to AI SDK format.
2393
- */
2394
- interface ToAiMessagesOptions {
2395
- /** When true, prefixes user messages with "[username]: " for multi-user context */
2396
- includeNames?: boolean;
2397
- /**
2398
- * Called when an attachment type is not supported (video, audio).
2399
- * Defaults to `console.warn`.
2400
- */
2401
- onUnsupportedAttachment?: (attachment: Attachment, message: Message) => void;
2402
- /**
2403
- * Called for each message after default processing (text, links, attachments).
2404
- * Return the message (modified or as-is) to include it, or `null` to skip it.
2405
- *
2406
- * @param aiMessage - The processed AI message
2407
- * @param source - The original chat Message
2408
- * @returns The message to include, or null to skip
2409
- */
2410
- transformMessage?: (aiMessage: AiMessage, source: Message) => AiMessage | null | Promise<AiMessage | null>;
2411
- }
2412
- /**
2413
- * Convert chat SDK messages to AI SDK conversation format.
2414
- *
2415
- * - Filters out messages with empty/whitespace-only text
2416
- * - Maps `author.isMe === true` to `"assistant"`, otherwise `"user"`
2417
- * - Uses `message.text` for content
2418
- * - Appends link metadata when available
2419
- * - Includes image attachments and text files as `FilePart`
2420
- * - Uses `fetchData()` when available to include attachment data inline (base64)
2421
- * - Warns on unsupported attachment types (video, audio)
2422
- *
2423
- * Works with `FetchResult.messages`, `thread.recentMessages`, or collected iterables.
2424
- *
2425
- * @example
2426
- * ```typescript
2427
- * const result = await thread.adapter.fetchMessages(thread.id, { limit: 20 });
2428
- * const history = await toAiMessages(result.messages);
2429
- * const response = await agent.stream({ prompt: history });
2430
- * ```
2431
- */
2432
- declare function toAiMessages(messages: Message[], options?: ToAiMessagesOptions): Promise<AiMessage[]>;
2433
-
2434
- /** Filter can be EmojiValue objects, emoji names, or raw emoji formats */
2435
- type EmojiFilter = EmojiValue | string;
2436
- /**
2437
- * Type-safe webhook handler that is available for each adapter.
2438
- */
2439
- type WebhookHandler = (request: Request, options?: WebhookOptions) => Promise<Response>;
2440
- /**
2441
- * Creates a type-safe webhooks object based on the adapter names.
2442
- */
2443
- type Webhooks<TAdapters extends Record<string, Adapter>> = {
2444
- [K in keyof TAdapters]: WebhookHandler;
2445
- };
2446
- /**
2447
- * Main Chat class with type-safe adapter inference and custom thread state.
2448
- *
2449
- * @template TAdapters - Map of adapter names to Adapter instances
2450
- * @template TState - Custom state type stored per-thread (default: Record<string, unknown>)
2451
- *
2452
- * @example
2453
- * // Define custom thread state type
2454
- * interface MyThreadState {
2455
- * aiMode?: boolean;
2456
- * userName?: string;
2457
- * }
2458
- *
2459
- * const chat = new Chat<typeof adapters, MyThreadState>({
2460
- * userName: "mybot",
2461
- * adapters: {
2462
- * slack: createSlackAdapter({ ... }),
2463
- * teams: createTeamsAdapter({ ... }),
2464
- * },
2465
- * state: createMemoryState(),
2466
- * });
2467
- *
2468
- * // Type-safe thread state
2469
- * chat.onNewMention(async (thread, message) => {
2470
- * await thread.setState({ aiMode: true });
2471
- * const state = await thread.state; // Type: MyThreadState | null
2472
- * });
2473
- */
2474
- declare class Chat<TAdapters extends Record<string, Adapter> = Record<string, Adapter>, TState = Record<string, unknown>> implements ChatInstance {
2475
- /**
2476
- * Register this Chat instance as the global singleton.
2477
- * Required for Thread deserialization via @workflow/serde.
2478
- *
2479
- * @example
2480
- * ```typescript
2481
- * const chat = new Chat({ ... });
2482
- * chat.registerSingleton();
2483
- *
2484
- * // Now threads can be deserialized without passing chat explicitly
2485
- * const thread = ThreadImpl.fromJSON(serializedThread);
2486
- * ```
2487
- */
2488
- registerSingleton(): this;
2489
- /**
2490
- * Get the registered singleton Chat instance.
2491
- * Throws if no singleton has been registered.
2492
- */
2493
- static getSingleton(): Chat;
2494
- /**
2495
- * Check if a singleton has been registered.
2496
- */
2497
- static hasSingleton(): boolean;
2498
- private readonly adapters;
2499
- private readonly _stateAdapter;
2500
- private readonly userName;
2501
- private readonly logger;
2502
- private readonly _streamingUpdateIntervalMs;
2503
- private readonly _fallbackStreamingPlaceholderText;
2504
- private readonly _dedupeTtlMs;
2505
- private readonly _onLockConflict;
2506
- private readonly _messageHistory;
2507
- private readonly _concurrencyStrategy;
2508
- private readonly _concurrencyConfig;
2509
- private readonly _concurrentSlots;
2510
- private readonly _lockScope;
2511
- private readonly mentionHandlers;
2512
- private readonly directMessageHandlers;
2513
- private readonly messagePatterns;
2514
- private readonly subscribedMessageHandlers;
2515
- private readonly reactionHandlers;
2516
- private readonly actionHandlers;
2517
- private readonly optionsLoadHandlers;
2518
- private readonly modalSubmitHandlers;
2519
- private readonly modalCloseHandlers;
2520
- private readonly slashCommandHandlers;
2521
- private readonly assistantThreadStartedHandlers;
2522
- private readonly assistantContextChangedHandlers;
2523
- private readonly appHomeOpenedHandlers;
2524
- private readonly memberJoinedChannelHandlers;
2525
- /** Initialization state */
2526
- private initPromise;
2527
- private initialized;
2528
- /**
2529
- * Type-safe webhook handlers keyed by adapter name.
2530
- * @example
2531
- * chat.webhooks.slack(request, { backgroundTask: waitUntil });
2532
- */
2533
- readonly webhooks: Webhooks<TAdapters>;
2534
- constructor(config: ChatConfig<TAdapters>);
2535
- /**
2536
- * Handle a webhook request for a specific adapter.
2537
- * Automatically initializes adapters on first call.
2538
- */
2539
- private handleWebhook;
2540
- /**
2541
- * Ensure the chat instance is initialized.
2542
- * This is called automatically before handling webhooks.
2543
- */
2544
- private ensureInitialized;
2545
- private doInitialize;
2546
- /**
2547
- * Gracefully shut down the chat instance.
2548
- */
2549
- shutdown(): Promise<void>;
2550
- /**
2551
- * Initialize the chat instance and all adapters.
2552
- * This is called automatically when handling webhooks, but can be called
2553
- * manually for non-webhook use cases (e.g., Gateway listeners).
2554
- */
2555
- initialize(): Promise<void>;
2556
- /**
2557
- * Register a handler for new @-mentions of the bot.
2558
- *
2559
- * **Important**: This handler is ONLY called for mentions in **unsubscribed** threads.
2560
- * Once a thread is subscribed (via `thread.subscribe()`), subsequent messages
2561
- * including @-mentions go to `onSubscribedMessage` handlers instead.
2562
- *
2563
- * To detect mentions in subscribed threads, check `message.isMention`:
2564
- *
2565
- * @example
2566
- * ```typescript
2567
- * // Handle new mentions (unsubscribed threads only)
2568
- * chat.onNewMention(async (thread, message) => {
2569
- * await thread.subscribe(); // Subscribe to follow-up messages
2570
- * await thread.post("Hello! I'll be watching this thread.");
2571
- * });
2572
- *
2573
- * // Handle all messages in subscribed threads
2574
- * chat.onSubscribedMessage(async (thread, message) => {
2575
- * if (message.isMention) {
2576
- * // User @-mentioned us in a thread we're already watching
2577
- * await thread.post("You mentioned me again!");
2578
- * }
2579
- * });
2580
- * ```
2581
- */
2582
- onNewMention(handler: MentionHandler<TState>): void;
2583
- /**
2584
- * Register a handler for direct messages.
2585
- *
2586
- * Called when a message is received in a DM thread that is not subscribed.
2587
- * If no `onDirectMessage` handlers are registered, DMs fall through to
2588
- * `onNewMention` for backward compatibility.
2589
- *
2590
- * @param handler - Handler called for DM messages
2591
- *
2592
- * @example
2593
- * ```typescript
2594
- * chat.onDirectMessage(async (thread, message) => {
2595
- * await thread.subscribe();
2596
- * await thread.post("Thanks for the DM!");
2597
- * });
2598
- * ```
2599
- */
2600
- onDirectMessage(handler: DirectMessageHandler<TState>): void;
2601
- /**
2602
- * Register a handler for messages matching a regex pattern.
2603
- *
2604
- * @param pattern - Regular expression to match against message text
2605
- * @param handler - Handler called when pattern matches
2606
- *
2607
- * @example
2608
- * ```typescript
2609
- * // Match messages starting with "!help"
2610
- * chat.onNewMessage(/^!help/, async (thread, message) => {
2611
- * await thread.post("Available commands: !help, !status, !ping");
2612
- * });
2613
- * ```
2614
- */
2615
- onNewMessage(pattern: RegExp, handler: MessageHandler<TState>): void;
2616
- /**
2617
- * Register a handler for messages in subscribed threads.
2618
- *
2619
- * Called for all messages in threads that have been subscribed via `thread.subscribe()`.
2620
- * This includes:
2621
- * - Follow-up messages from users
2622
- * - Messages that @-mention the bot (check `message.isMention`)
2623
- *
2624
- * Does NOT fire for:
2625
- * - The message that triggered the subscription (e.g., the initial @mention)
2626
- * - Messages sent by the bot itself
2627
- *
2628
- * @example
2629
- * ```typescript
2630
- * chat.onSubscribedMessage(async (thread, message) => {
2631
- * // Handle all follow-up messages
2632
- * if (message.isMention) {
2633
- * // User @-mentioned us in a subscribed thread
2634
- * }
2635
- * await thread.post(`Got your message: ${message.text}`);
2636
- * });
2637
- * ```
2638
- */
2639
- onSubscribedMessage(handler: SubscribedMessageHandler<TState>): void;
2640
- /**
2641
- * Register a handler for reaction events.
2642
- *
2643
- * @example
2644
- * ```typescript
2645
- * // Handle specific emoji using EmojiValue objects (recommended)
2646
- * chat.onReaction([emoji.thumbs_up, emoji.heart], async (event) => {
2647
- * if (event.emoji === emoji.thumbs_up) {
2648
- * console.log("Thumbs up!");
2649
- * }
2650
- * });
2651
- *
2652
- * // Handle all reactions
2653
- * chat.onReaction(async (event) => {
2654
- * console.log(`${event.added ? "Added" : "Removed"} ${event.emoji.name}`);
2655
- * });
2656
- * ```
2657
- *
2658
- * @param emojiOrHandler - Either an array of emoji to filter (EmojiValue or string), or the handler
2659
- * @param handler - The handler (if emoji filter is provided)
2660
- */
2661
- onReaction(handler: ReactionHandler): void;
2662
- onReaction(emoji: EmojiFilter[], handler: ReactionHandler): void;
2663
- /**
2664
- * Register a handler for action events (button clicks in cards).
2665
- *
2666
- * @example
2667
- * ```typescript
2668
- * // Handle specific action
2669
- * chat.onAction("approve", async (event) => {
2670
- * await event.thread.post("Approved!");
2671
- * });
2672
- *
2673
- * // Handle multiple actions
2674
- * chat.onAction(["approve", "reject"], async (event) => {
2675
- * if (event.actionId === "approve") {
2676
- * await event.thread.post("Approved!");
2677
- * } else {
2678
- * await event.thread.post("Rejected!");
2679
- * }
2680
- * });
2681
- *
2682
- * // Handle all actions (catch-all)
2683
- * chat.onAction(async (event) => {
2684
- * console.log(`Action: ${event.actionId}`);
2685
- * });
2686
- * ```
2687
- *
2688
- * @param actionIdOrHandler - Either an action ID, array of action IDs, or the handler
2689
- * @param handler - The handler (if action ID filter is provided)
2690
- */
2691
- onAction(handler: ActionHandler): void;
2692
- onAction(actionIds: string[] | string, handler: ActionHandler): void;
2693
- /**
2694
- * Register a handler for loading dynamic options for external selects.
2695
- * Specific action IDs run before catch-all handlers.
2696
- */
2697
- onOptionsLoad(handler: OptionsLoadHandler): void;
2698
- onOptionsLoad(actionIds: string[] | string, handler: OptionsLoadHandler): void;
2699
- /**
2700
- * Register a handler for modal form submissions.
2701
- *
2702
- * @example
2703
- * ```typescript
2704
- * // Handle specific modal
2705
- * chat.onModalSubmit("settings-modal", async (event) => {
2706
- * const name = event.values["name"];
2707
- * await event.relatedThread?.post(`Updated name to ${name}`);
2708
- * });
2709
- *
2710
- * // Handle all modal submissions
2711
- * chat.onModalSubmit(async (event) => {
2712
- * console.log(`Modal ${event.callbackId} submitted`);
2713
- * });
2714
- * ```
2715
- *
2716
- * @param callbackIdOrHandler - Either a callback ID, array of callback IDs, or the handler
2717
- * @param handler - The handler (if callback ID filter is provided)
2718
- */
2719
- onModalSubmit(handler: ModalSubmitHandler): void;
2720
- onModalSubmit(callbackIds: string[] | string, handler: ModalSubmitHandler): void;
2721
- /**
2722
- * Register a handler for modal close/cancel events.
2723
- * Only fires when the modal was created with `notifyOnClose: true`.
2724
- *
2725
- * @example
2726
- * ```typescript
2727
- * // Handle specific modal close
2728
- * chat.onModalClose("settings-modal", async (event) => {
2729
- * console.log("User cancelled settings");
2730
- * });
2731
- *
2732
- * // Handle all modal close events
2733
- * chat.onModalClose(async (event) => {
2734
- * console.log(`Modal ${event.callbackId} closed`);
2735
- * });
2736
- * ```
2737
- *
2738
- * @param callbackIdOrHandler - Either a callback ID, array of callback IDs, or the handler
2739
- * @param handler - The handler (if callback ID filter is provided)
2740
- */
2741
- onModalClose(handler: ModalCloseHandler): void;
2742
- onModalClose(callbackIds: string[] | string, handler: ModalCloseHandler): void;
2743
- /**
2744
- * Register a handler for slash command events.
2745
- *
2746
- * Slash commands are triggered when a user types `/command` in the message composer.
2747
- * Use `event.channel.post()` or `event.channel.postEphemeral()` to respond.
2748
- *
2749
- * @example
2750
- * ```typescript
2751
- * // Handle a specific command
2752
- * chat.onSlashCommand("/help", async (event) => {
2753
- * await event.channel.post("Here are the available commands...");
2754
- * });
2755
- *
2756
- * // Handle multiple commands
2757
- * chat.onSlashCommand(["/status", "/health"], async (event) => {
2758
- * await event.channel.post("All systems operational!");
2759
- * });
2760
- *
2761
- * // Handle all commands (catch-all)
2762
- * chat.onSlashCommand(async (event) => {
2763
- * console.log(`Received command: ${event.command} ${event.text}`);
2764
- * });
2765
- *
2766
- * // Open a modal from a slash command
2767
- * chat.onSlashCommand("/feedback", async (event) => {
2768
- * await event.openModal({
2769
- * callbackId: "feedback_modal",
2770
- * title: "Submit Feedback",
2771
- * inputs: [{ id: "feedback", type: "text_input", label: "Your feedback" }],
2772
- * });
2773
- * });
2774
- * ```
2775
- *
2776
- * @param commandOrHandler - Either a command, array of commands, or the handler
2777
- * @param handler - The handler (if command filter is provided)
2778
- */
2779
- onSlashCommand(handler: SlashCommandHandler<TState>): void;
2780
- onSlashCommand(commands: string[] | string, handler: SlashCommandHandler<TState>): void;
2781
- onAssistantThreadStarted(handler: AssistantThreadStartedHandler): void;
2782
- onAssistantContextChanged(handler: AssistantContextChangedHandler): void;
2783
- onAppHomeOpened(handler: AppHomeOpenedHandler): void;
2784
- onMemberJoinedChannel(handler: MemberJoinedChannelHandler): void;
2785
- /**
2786
- * Get an adapter by name with type safety.
2787
- */
2788
- getAdapter<K extends keyof TAdapters>(name: K): TAdapters[K];
2789
- /**
2790
- * Get a JSON.parse reviver function that automatically deserializes
2791
- * chat:Thread and chat:Message objects.
2792
- *
2793
- * Use this when parsing JSON that contains serialized Thread or Message objects
2794
- * (e.g., from workflow engine payloads).
2795
- *
2796
- * @returns A reviver function for JSON.parse
2797
- *
2798
- * @example
2799
- * ```typescript
2800
- * // Parse workflow payload with automatic deserialization
2801
- * const data = JSON.parse(payload, chat.reviver());
2802
- *
2803
- * // data.thread is now a ThreadImpl instance
2804
- * // data.message is now a Message object with Date fields restored
2805
- * await data.thread.post("Hello from workflow!");
2806
- * ```
2807
- */
2808
- reviver(): (key: string, value: unknown) => unknown;
2809
- /**
2810
- * Process an incoming message from an adapter.
2811
- * Handles waitUntil registration and error catching internally.
2812
- * Adapters should call this instead of handleIncomingMessage directly.
2813
- */
2814
- processMessage(adapter: Adapter, threadId: string, messageOrFactory: Message | (() => Promise<Message>), options?: WebhookOptions): void;
2815
- /**
2816
- * Process an incoming reaction event from an adapter.
2817
- * Handles waitUntil registration and error catching internally.
2818
- */
2819
- processReaction(event: Omit<ReactionEvent, "adapter" | "thread"> & {
2820
- adapter?: Adapter;
2821
- }, options?: WebhookOptions): void;
2822
- /**
2823
- * Process an incoming action event (button click) from an adapter.
2824
- * Handles waitUntil registration and error catching internally.
2825
- */
2826
- processAction(event: Omit<ActionEvent, "thread" | "openModal"> & {
2827
- adapter: Adapter;
2828
- }, options: WebhookOptions | undefined): Promise<void>;
2829
- processOptionsLoad(event: OptionsLoadEvent, _options?: WebhookOptions): Promise<OptionsLoadResult | undefined>;
2830
- processModalSubmit(event: Omit<ModalSubmitEvent, "relatedThread" | "relatedMessage" | "relatedChannel">, contextId?: string, _options?: WebhookOptions): Promise<ModalResponse | undefined>;
2831
- processModalClose(event: Omit<ModalCloseEvent, "relatedThread" | "relatedMessage" | "relatedChannel">, contextId?: string, options?: WebhookOptions): void;
2832
- /**
2833
- * Process an incoming slash command from an adapter.
2834
- * Handles waitUntil registration and error catching internally.
2835
- */
2836
- processSlashCommand(event: Omit<SlashCommandEvent, "channel" | "openModal"> & {
2837
- adapter: Adapter;
2838
- channelId: string;
2839
- }, options: WebhookOptions | undefined): void;
2840
- processAssistantThreadStarted(event: AssistantThreadStartedEvent, options?: WebhookOptions): void;
2841
- processAssistantContextChanged(event: AssistantContextChangedEvent, options?: WebhookOptions): void;
2842
- processAppHomeOpened(event: AppHomeOpenedEvent, options?: WebhookOptions): void;
2843
- processMemberJoinedChannel(event: MemberJoinedChannelEvent, options?: WebhookOptions): void;
2844
- /**
2845
- * Handle a slash command event internally.
2846
- */
2847
- private handleSlashCommandEvent;
2848
- /**
2849
- * Store modal context server-side with a context ID.
2850
- * Called when opening a modal to preserve thread/message/channel for the submit handler.
2851
- */
2852
- private storeModalContext;
2853
- /**
2854
- * Retrieve and delete modal context from server-side storage.
2855
- * Called when processing modal submit/close to reconstruct thread/message/channel.
2856
- */
2857
- private retrieveModalContext;
2858
- /**
2859
- * Handle an action event internally.
2860
- */
2861
- private handleActionEvent;
2862
- /**
2863
- * Handle a reaction event internally.
2864
- */
2865
- private handleReactionEvent;
2866
- getState(): StateAdapter;
2867
- getUserName(): string;
2868
- getLogger(prefix?: string): Logger;
2869
- /**
2870
- * Open a direct message conversation with a user.
2871
- *
2872
- * Accepts either a user ID string or an Author object (from message.author or event.user).
2873
- *
2874
- * The adapter is automatically inferred from the userId format:
2875
- * - Slack: `U...` (e.g., "U00FAKEUSER1")
2876
- * - Teams: `29:...` (e.g., "29:198PbJuw...")
2877
- * - Google Chat: `users/...` (e.g., "users/100000000000000000001")
2878
- * - Discord: numeric snowflake (e.g., "1033044521375764530")
2879
- *
2880
- * @param user - Platform-specific user ID string, or an Author object
2881
- * @returns A Thread that can be used to post messages
2882
- *
2883
- * @example
2884
- * ```ts
2885
- * // Using user ID directly
2886
- * const dmThread = await chat.openDM("U123456");
2887
- * await dmThread.post("Hello via DM!");
2888
- *
2889
- * // Using Author object from a message
2890
- * chat.onSubscribedMessage(async (thread, message) => {
2891
- * const dmThread = await chat.openDM(message.author);
2892
- * await dmThread.post("Hello via DM!");
2893
- * });
2894
- * ```
2895
- */
2896
- openDM(user: string | Author): Promise<Thread<TState>>;
2897
- /**
2898
- * Look up user information by user ID.
2899
- *
2900
- * The adapter is automatically inferred from the user ID format.
2901
- * Returns user details including email (where available — requires
2902
- * appropriate scopes on some platforms, e.g. `users:read.email` on Slack).
2903
- *
2904
- * @param user - Platform-specific user ID string, or an Author object
2905
- * @returns User info, or null if user not found
2906
- *
2907
- * @example
2908
- * ```typescript
2909
- * const user = await chat.getUser("U123456");
2910
- * console.log(user?.email); // "alice@company.com"
2911
- * ```
2912
- */
2913
- getUser(user: string | Author): Promise<UserInfo | null>;
2914
- /**
2915
- * Get a Channel by its channel ID.
2916
- *
2917
- * The adapter is automatically inferred from the channel ID prefix.
2918
- *
2919
- * @param channelId - Channel ID (e.g., "slack:C123ABC", "gchat:spaces/ABC123")
2920
- * @returns A Channel that can be used to list threads, post messages, iterate messages, etc.
2921
- *
2922
- * @example
2923
- * ```typescript
2924
- * const channel = chat.channel("slack:C123ABC");
2925
- *
2926
- * // Iterate messages newest first
2927
- * for await (const msg of channel.messages) {
2928
- * console.log(msg.text);
2929
- * }
2930
- *
2931
- * // List threads
2932
- * for await (const t of channel.threads()) {
2933
- * console.log(t.rootMessage.text, t.replyCount);
2934
- * }
2935
- *
2936
- * // Post to channel
2937
- * await channel.post("Hello channel!");
2938
- * ```
2939
- */
2940
- channel(channelId: string): Channel<TState>;
2941
- /**
2942
- * Get a Thread handle by its thread ID.
2943
- *
2944
- * The adapter is automatically inferred from the thread ID prefix.
2945
- *
2946
- * @param threadId - Full thread ID (e.g., "slack:C123ABC:1234567890.123456")
2947
- * @returns A Thread that can be used to post messages, subscribe, etc.
2948
- *
2949
- * @example
2950
- * ```typescript
2951
- * const thread = chat.thread("slack:C123ABC:1234567890.123456");
2952
- * await thread.post("Hello from outside a webhook!");
2953
- * ```
2954
- */
2955
- thread(threadId: string): Thread<TState>;
2956
- /**
2957
- * Infer which adapter to use based on the userId format.
2958
- */
2959
- private inferAdapterFromUserId;
2960
- /**
2961
- * Resolve the lock key for a message based on lock scope.
2962
- * With 'thread' scope, returns threadId. With 'channel' scope,
2963
- * returns channelId (derived via adapter.channelIdFromThreadId).
2964
- */
2965
- private getLockKey;
2966
- /**
2967
- * Handle an incoming message from an adapter.
2968
- * This is called by adapters when they receive a webhook.
2969
- *
2970
- * The Chat class handles common concerns centrally:
2971
- * - Deduplication: Same message may arrive multiple times (e.g., Slack sends
2972
- * both `message` and `app_mention` events, GChat sends direct webhook + Pub/Sub)
2973
- * - Bot filtering: Messages from the bot itself are skipped
2974
- * - Concurrency: Controlled by `concurrency` config (drop, queue, debounce, concurrent)
2975
- */
2976
- handleIncomingMessage(adapter: Adapter, threadId: string, message: Message): Promise<void>;
2977
- /**
2978
- * Drop strategy: acquire lock or fail. Original behavior.
2979
- */
2980
- private handleDrop;
2981
- /**
2982
- * Queue/Debounce strategy: enqueue if lock is busy, drain after processing.
2983
- */
2984
- private handleQueueOrDebounce;
2985
- /**
2986
- * Debounce loop: wait for debounceMs, check if newer message arrived,
2987
- * repeat until no new messages, then process the final message.
2988
- */
2989
- private debounceLoop;
2990
- /**
2991
- * Drain queue: collect all pending messages, dispatch the latest with
2992
- * skipped context, then check for more.
2993
- */
2994
- private drainQueue;
2995
- /**
2996
- * Concurrent strategy: no locking, process immediately — but cap
2997
- * simultaneous handlers per thread at `maxConcurrent` (default Infinity).
2998
- */
2999
- private handleConcurrent;
3000
- private acquireConcurrentSlot;
3001
- private releaseConcurrentSlot;
3002
- /**
3003
- * Dispatch a message to the appropriate handler chain based on
3004
- * subscription status, mention detection, and pattern matching.
3005
- */
3006
- private dispatchToHandlers;
3007
- private createThread;
3008
- /**
3009
- * Detect if the bot was mentioned in the message.
3010
- * All adapters normalize mentions to @name format, so we just check for @username.
3011
- */
3012
- private detectMention;
3013
- private escapeRegex;
3014
- /**
3015
- * Reconstruct a proper Message instance from a dequeued entry.
3016
- * After JSON roundtrip through the state adapter, the message is a plain
3017
- * object (not a Message instance). This restores class invariants like
3018
- * `links` defaulting to `[]` and `metadata.dateSent` being a Date.
3019
- */
3020
- private rehydrateMessage;
3021
- private runHandlers;
3022
- }
3023
138
 
3024
- /**
3025
- * Normalizes an async iterable stream for use with `thread.post()`.
3026
- *
3027
- * Handles three stream types automatically:
3028
- * - **Text streams** (`AsyncIterable<string>`, e.g. AI SDK `textStream`) —
3029
- * passed through as-is.
3030
- * - **Full streams** (`AsyncIterable<object>`, e.g. AI SDK `fullStream`) —
3031
- * extracts `text-delta` events and injects `"\n\n"` separators between
3032
- * steps so that multi-step agent output reads naturally.
3033
- * - **StreamChunk objects** (`task_update`, `plan_update`, `markdown_text`) —
3034
- * passed through as-is for adapters with native structured chunk support.
3035
- *
3036
- * This is used internally by `thread.post()`, so you can pass either stream
3037
- * directly:
3038
- * ```ts
3039
- * await thread.post(result.fullStream); // auto-detected
3040
- * await thread.post(result.textStream); // still works
3041
- * ```
3042
- */
3043
- declare function fromFullStream(stream: AsyncIterable<unknown>): AsyncIterable<string | StreamChunk>;
139
+ /** @deprecated Use `ThreadHistoryConfig` from `./thread-history` instead. */
140
+ type MessageHistoryConfig = ThreadHistoryConfig;
141
+ /** @deprecated Use `ThreadHistoryCache` from `./thread-history` instead. */
142
+ declare const MessageHistoryCache: typeof ThreadHistoryCache;
143
+ /** @deprecated Use `ThreadHistoryCache` from `./thread-history` instead. */
144
+ type MessageHistoryCache = ThreadHistoryCache;
3044
145
 
3045
146
  /**
3046
147
  * Standalone JSON reviver for Chat SDK objects.
@@ -3128,7 +229,7 @@ interface StreamingPlanOptions {
3128
229
  groupTasks?: "plan" | "timeline";
3129
230
  /**
3130
231
  * Minimum interval between updates in ms (default: 500).
3131
- * Used for fallback mode (post+edit on adapters without native streaming).
232
+ * Used by post+edit streaming paths.
3132
233
  */
3133
234
  updateIntervalMs?: number;
3134
235
  }
@@ -3250,7 +351,7 @@ declare const defaultEmojiResolver: EmojiResolver;
3250
351
  * // Returns: "Thanks! 👍"
3251
352
  * ```
3252
353
  */
3253
- declare function convertEmojiPlaceholders(text: string, platform: "slack" | "gchat" | "teams" | "discord" | "github" | "linear" | "whatsapp", resolver?: EmojiResolver): string;
354
+ declare function convertEmojiPlaceholders(text: string, platform: "slack" | "gchat" | "teams" | "discord" | "messenger" | "github" | "linear" | "whatsapp", resolver?: EmojiResolver): string;
3254
355
  /** Base emoji object with well-known emoji as EmojiValue singletons */
3255
356
  type BaseEmojiHelper = {
3256
357
  [K in WellKnownEmoji]: EmojiValue;
@@ -3610,4 +711,4 @@ declare const Select: SelectComponent;
3610
711
  declare const SelectOption: SelectOptionComponent;
3611
712
  declare const TextInput: TextInputComponent;
3612
713
 
3613
- export { type ActionEvent, type ActionHandler, Actions, ActionsComponent, type Adapter, type AdapterPostableMessage, type AddTaskOptions, type AiAssistantMessage, type AiFilePart, type AiImagePart, type AiMessage, type AiMessagePart, type AiTextPart, type AiUserMessage, type AppHomeOpenedEvent, type AppHomeOpenedHandler, type AssistantContextChangedEvent, type AssistantContextChangedHandler, type AssistantThreadStartedEvent, type AssistantThreadStartedHandler, type Attachment, type Author, BaseFormatConverter, Button, ButtonComponent, Card, CardChild, CardComponent, CardElement, CardLink, CardLinkComponent, CardText, type Channel, ChannelImpl, type ChannelInfo, type ChannelVisibility, Chat, type ChatConfig, ChatElement, ChatError, type ChatInstance, type CompletePlanOptions, type ConcurrencyConfig, type ConcurrencyStrategy, ConsoleLogger, type CustomEmojiMap, DEFAULT_EMOJI_MAP, type DirectMessageHandler, Divider, DividerComponent, type Emoji, type EmojiFormats, type EmojiMapConfig, EmojiResolver, type EmojiValue, type EphemeralMessage, ExternalSelect, ExternalSelectComponent, type FetchDirection, type FetchOptions, type FetchResult, Field, FieldComponent, Fields, FieldsComponent, type FileUpload, type FormatConverter, type FormattedContent, Image, ImageComponent, LinkButton, LinkButtonComponent, type LinkPreview, type ListThreadsOptions, type ListThreadsResult, type Lock, LockError, type LockScope, type LockScopeContext, type LogLevel, type Logger, type MarkdownConverter, type MarkdownTextChunk, type MemberJoinedChannelEvent, type MemberJoinedChannelHandler, type MentionHandler, Message, type MessageContext, type MessageData, type MessageHandler, MessageHistoryCache, type MessageHistoryConfig, type MessageMetadata, Modal, type ModalClearResponse, type ModalCloseEvent, type ModalCloseHandler, type ModalCloseResponse, ModalComponent, ModalElement, type ModalErrorsResponse, type ModalPushResponse, type ModalResponse, type ModalSubmitEvent, type ModalSubmitHandler, type ModalUpdateResponse, NotImplementedError, type OptionsLoadEvent, type OptionsLoadGroup, type OptionsLoadHandler, type OptionsLoadResult, Plan, type PlanContent, type PlanModel, type PlanModelTask, type PlanTask, type PlanTaskStatus, type PlanUpdateChunk, type PostEphemeralOptions, type Postable, type PostableAst, type PostableCard, type PostableMarkdown, type PostableMessage, type PostableObject, type PostableObjectContext, type PostableRaw, type QueueEntry, RadioSelect, RadioSelectComponent, RateLimitError, type RawMessage, type ReactionEvent, type ReactionHandler, type ScheduledMessage, Section, SectionComponent, Select, SelectComponent, SelectOption, SelectOptionComponent, SelectOptionElement, type SentMessage, type SerializedChannel, type SerializedMessage, type SerializedThread, type SlashCommandEvent, type SlashCommandHandler, type StartPlanOptions, type StateAdapter, type StreamChunk, type StreamEvent, type StreamOptions, StreamingMarkdownRenderer, StreamingPlan, type StreamingPlanData, type StreamingPlanOptions, type SubscribedMessageHandler, THREAD_STATE_TTL_MS, Table, type TaskUpdateChunk, TextComponent, TextInput, TextInputComponent, type Thread, ThreadImpl, type ThreadInfo, type ThreadSummary, type UpdateTaskInput, type UserInfo, type WebhookOptions, type WellKnownEmoji, blockquote, cardChildToFallbackText, codeBlock, convertEmojiPlaceholders, createEmoji, defaultEmojiResolver, deriveChannelId, emoji, emphasis, fromFullStream, fromReactElement, fromReactModalElement, getEmoji, getNodeChildren, getNodeValue, inlineCode, isBlockquoteNode, isCardElement, isCodeNode, isDeleteNode, isEmphasisNode, isInlineCodeNode, isJSX, isLinkNode, isListItemNode, isListNode, isModalElement, isParagraphNode, isPostableObject, isStrongNode, isTableCellNode, isTableNode, isTableRowNode, isTextNode, link, markdownToPlainText, paragraph, parseMarkdown, reviver, root, strikethrough, stringifyMarkdown, strong, tableElementToAscii, tableToAscii, text, toAiMessages, toCardElement, toModalElement, toPlainText, walkAst };
714
+ export { Actions, ActionsComponent, Adapter, AdapterPostableMessage, type AddTaskOptions, BaseFormatConverter, Button, ButtonComponent, Card, CardChild, CardComponent, CardElement, CardLink, CardLinkComponent, CardText, ChatError, type CompletePlanOptions, CustomEmojiMap, DEFAULT_EMOJI_MAP, Divider, DividerComponent, EmojiFormats, EmojiMapConfig, EmojiResolver, EmojiValue, ExternalSelect, ExternalSelectComponent, Field, FieldComponent, Fields, FieldsComponent, type FormatConverter, Image, ImageComponent, LinkButton, LinkButtonComponent, LockError, type MarkdownConverter, MessageHistoryCache, type MessageHistoryConfig, Modal, ModalComponent, NotImplementedError, Plan, type PlanContent, type PlanModel, type PlanModelTask, type PlanTask, type PlanTaskStatus, PostableObject, PostableObjectContext, RadioSelect, RadioSelectComponent, RateLimitError, Section, SectionComponent, Select, SelectComponent, SelectOption, SelectOptionComponent, type StartPlanOptions, StreamChunk, StreamEvent, StreamingMarkdownRenderer, StreamingPlan, type StreamingPlanData, type StreamingPlanOptions, Table, TextComponent, TextInput, TextInputComponent, ThreadHistoryCache, ThreadHistoryConfig, type UpdateTaskInput, WellKnownEmoji, blockquote, cardChildToFallbackText, codeBlock, convertEmojiPlaceholders, createEmoji, defaultEmojiResolver, emoji, emphasis, fromFullStream, fromReactElement, fromReactModalElement, getEmoji, getNodeChildren, getNodeValue, inlineCode, isBlockquoteNode, isCardElement, isCodeNode, isDeleteNode, isEmphasisNode, isInlineCodeNode, isJSX, isLinkNode, isListItemNode, isListNode, isModalElement, isParagraphNode, isStrongNode, isTableCellNode, isTableNode, isTableRowNode, isTextNode, link, markdownToPlainText, paragraph, parseMarkdown, reviver, root, strikethrough, stringifyMarkdown, strong, tableElementToAscii, tableToAscii, text, toCardElement, toModalElement, toPlainText, walkAst };