@ariaflowagents/messaging 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +165 -0
  2. package/dist/adapter/createMessagingRouter.d.ts +37 -0
  3. package/dist/adapter/createMessagingRouter.d.ts.map +1 -0
  4. package/dist/adapter/createMessagingRouter.js +115 -0
  5. package/dist/adapter/createMessagingRouter.js.map +1 -0
  6. package/dist/adapter/session-resolver.d.ts +13 -0
  7. package/dist/adapter/session-resolver.d.ts.map +1 -0
  8. package/dist/adapter/session-resolver.js +18 -0
  9. package/dist/adapter/session-resolver.js.map +1 -0
  10. package/dist/adapter/stream-mapper.d.ts +33 -0
  11. package/dist/adapter/stream-mapper.d.ts.map +1 -0
  12. package/dist/adapter/stream-mapper.js +117 -0
  13. package/dist/adapter/stream-mapper.js.map +1 -0
  14. package/dist/adapter/window-tracker.d.ts +57 -0
  15. package/dist/adapter/window-tracker.d.ts.map +1 -0
  16. package/dist/adapter/window-tracker.js +95 -0
  17. package/dist/adapter/window-tracker.js.map +1 -0
  18. package/dist/errors.d.ts +69 -0
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/errors.js +101 -0
  21. package/dist/errors.js.map +1 -0
  22. package/dist/index.d.ts +11 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +18 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/shared/deduplicator.d.ts +36 -0
  27. package/dist/shared/deduplicator.d.ts.map +1 -0
  28. package/dist/shared/deduplicator.js +80 -0
  29. package/dist/shared/deduplicator.js.map +1 -0
  30. package/dist/shared/format-base.d.ts +44 -0
  31. package/dist/shared/format-base.d.ts.map +1 -0
  32. package/dist/shared/format-base.js +49 -0
  33. package/dist/shared/format-base.js.map +1 -0
  34. package/dist/shared/media-cache.d.ts +96 -0
  35. package/dist/shared/media-cache.d.ts.map +1 -0
  36. package/dist/shared/media-cache.js +111 -0
  37. package/dist/shared/media-cache.js.map +1 -0
  38. package/dist/types.d.ts +428 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/types.js +2 -0
  41. package/dist/types.js.map +1 -0
  42. package/package.json +28 -0
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @module shared/media-cache
3
+ *
4
+ * In-memory LRU cache for downloaded media attachments.
5
+ *
6
+ * Avoids re-downloading the same attachment when multiple handlers
7
+ * or retry logic access the same media ID. Uses a Map-based LRU
8
+ * with TTL expiration (media URLs from Meta are temporary -- typically
9
+ * valid for ~5 minutes).
10
+ */
11
+ // ====================================
12
+ // MediaCache
13
+ // ====================================
14
+ /**
15
+ * In-memory LRU cache for downloaded media.
16
+ *
17
+ * Avoids re-downloading the same attachment when multiple handlers
18
+ * or retry logic access the same media ID. Uses a Map-based LRU
19
+ * with TTL expiration (media URLs from Meta are temporary -- typically
20
+ * valid for ~5 minutes).
21
+ */
22
+ export class MediaCache {
23
+ cache;
24
+ maxSize;
25
+ ttlMs;
26
+ constructor(config) {
27
+ this.maxSize = config?.maxSize ?? 100;
28
+ this.ttlMs = config?.ttlMs ?? 300_000;
29
+ this.cache = new Map();
30
+ }
31
+ /**
32
+ * Get cached media by ID. Returns `undefined` if not found or expired.
33
+ *
34
+ * Accessing an entry refreshes its LRU position (moves it to the end
35
+ * of the eviction queue).
36
+ *
37
+ * @param mediaId - The platform-specific media identifier.
38
+ * @returns The cached media entry, or `undefined`.
39
+ */
40
+ get(mediaId) {
41
+ const entry = this.cache.get(mediaId);
42
+ if (!entry)
43
+ return undefined;
44
+ if (Date.now() - entry.cachedAt > this.ttlMs) {
45
+ this.cache.delete(mediaId);
46
+ return undefined;
47
+ }
48
+ // Move to end (LRU refresh)
49
+ this.cache.delete(mediaId);
50
+ this.cache.set(mediaId, entry);
51
+ return entry;
52
+ }
53
+ /**
54
+ * Store media in the cache.
55
+ *
56
+ * If the cache is at capacity, the least-recently-used entry is evicted.
57
+ *
58
+ * @param mediaId - The platform-specific media identifier.
59
+ * @param media - The media content to cache.
60
+ */
61
+ set(mediaId, media) {
62
+ // If updating an existing key, delete first so it moves to the end
63
+ if (this.cache.has(mediaId)) {
64
+ this.cache.delete(mediaId);
65
+ }
66
+ // Evict if at capacity
67
+ if (this.cache.size >= this.maxSize) {
68
+ const firstKey = this.cache.keys().next().value;
69
+ if (firstKey !== undefined)
70
+ this.cache.delete(firstKey);
71
+ }
72
+ this.cache.set(mediaId, { ...media, cachedAt: Date.now() });
73
+ }
74
+ /**
75
+ * Check if media is cached and not expired.
76
+ *
77
+ * @param mediaId - The platform-specific media identifier.
78
+ * @returns `true` if the media is cached and still valid.
79
+ */
80
+ has(mediaId) {
81
+ return this.get(mediaId) !== undefined;
82
+ }
83
+ /**
84
+ * Wrap a download function with caching.
85
+ *
86
+ * If the media is cached, returns the cached version. Otherwise
87
+ * calls `downloadFn`, caches the result, and returns it.
88
+ *
89
+ * @param mediaId - The platform-specific media identifier.
90
+ * @param downloadFn - A function that downloads the media.
91
+ * @returns The media content (from cache or fresh download).
92
+ */
93
+ async getOrDownload(mediaId, downloadFn) {
94
+ const cached = this.get(mediaId);
95
+ if (cached) {
96
+ return { data: cached.data, mimeType: cached.mimeType, filename: cached.filename };
97
+ }
98
+ const result = await downloadFn();
99
+ this.set(mediaId, result);
100
+ return result;
101
+ }
102
+ /** Return the current number of cached entries. */
103
+ get size() {
104
+ return this.cache.size;
105
+ }
106
+ /** Clear all cached entries. */
107
+ clear() {
108
+ this.cache.clear();
109
+ }
110
+ }
111
+ //# sourceMappingURL=media-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media-cache.js","sourceRoot":"","sources":["../../src/shared/media-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AA8BH,uCAAuC;AACvC,aAAa;AACb,uCAAuC;AAEvC;;;;;;;GAOG;AACH,MAAM,OAAO,UAAU;IACJ,KAAK,CAA2B;IAChC,OAAO,CAAS;IAChB,KAAK,CAAS;IAE/B,YAAY,MAAyB;QACnC,IAAI,CAA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C1D,CAAC;QAED,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,GAAG,KAAK,EAAE,QAAQ,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAC9D,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAC,OAAe;QACjB,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,SAAS,CAAC;IACzC,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CACjB,OAAe,EACf,UAAgF;QAEhF,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACjC,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrF,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,UAAU,EAAE,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC1B,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,mDAAmD;IACnD,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;IAED,gCAAgC;IAChC,KAAK;QACH,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACF"}
@@ -0,0 +1,428 @@
1
+ import type { Hono } from 'hono';
2
+ import type { Runtime, HarnessStreamPart } from '@ariaflowagents/core';
3
+ /** Contact information normalized across platforms. */
4
+ export interface ContactInfo {
5
+ /** Platform-specific contact identifier. */
6
+ id: string;
7
+ /** Display name of the contact. */
8
+ name?: string;
9
+ /** Phone number in E.164 format (if available). */
10
+ phone?: string;
11
+ }
12
+ /** Geographic location data. */
13
+ export interface LocationData {
14
+ /** Latitude in decimal degrees. */
15
+ latitude: number;
16
+ /** Longitude in decimal degrees. */
17
+ longitude: number;
18
+ /** Human-readable location name. */
19
+ name?: string;
20
+ /** Street address or description. */
21
+ address?: string;
22
+ }
23
+ /** A media payload to send to a platform. */
24
+ export interface MediaPayload {
25
+ /** Media type category. */
26
+ type: 'image' | 'video' | 'audio' | 'document' | 'sticker';
27
+ /** The media content: a Buffer, ReadableStream, or a URL string. */
28
+ data: Buffer | ReadableStream | string;
29
+ /** MIME type of the media (e.g. "image/jpeg"). */
30
+ mimeType: string;
31
+ /** Optional filename for the media. */
32
+ filename?: string;
33
+ /** Optional caption to display alongside the media. */
34
+ caption?: string;
35
+ }
36
+ /** A reference to media already hosted on a platform. */
37
+ export interface MediaReference {
38
+ /** Platform-specific media identifier. */
39
+ id: string;
40
+ /** MIME type of the referenced media. */
41
+ mimeType?: string;
42
+ /** Public or temporary URL to access the media. */
43
+ url?: string;
44
+ /** Caption associated with the media. */
45
+ caption?: string;
46
+ /** Original filename. */
47
+ filename?: string;
48
+ }
49
+ /** Handle returned after uploading media to a platform. */
50
+ export interface MediaHandle {
51
+ /** Platform-assigned media identifier. */
52
+ mediaId: string;
53
+ /** URL where the media can be accessed (if available). */
54
+ url?: string;
55
+ }
56
+ /** Downloaded media content. */
57
+ export interface MediaDownload {
58
+ /** Raw media bytes. */
59
+ data: Buffer;
60
+ /** MIME type of the downloaded media. */
61
+ mimeType: string;
62
+ /** Original filename (if available). */
63
+ filename?: string;
64
+ }
65
+ /** Options for uploading media. */
66
+ export interface MediaUploadOptions {
67
+ /** MIME type of the media being uploaded. */
68
+ mimeType: string;
69
+ /** Filename for the uploaded media. */
70
+ filename?: string;
71
+ }
72
+ /** An interactive message with buttons, a list, or a platform-specific flow. */
73
+ export interface InteractiveMessage {
74
+ /** Type of interactive element. */
75
+ type: 'buttons' | 'list' | 'flow';
76
+ /** Header text or media for the interactive message. */
77
+ header?: {
78
+ type: 'text' | 'image' | 'video' | 'document';
79
+ content: string;
80
+ };
81
+ /** Body text of the interactive message. */
82
+ body: string;
83
+ /** Footer text. */
84
+ footer?: string;
85
+ /** Action payload — shape depends on `type`. */
86
+ action: InteractiveAction;
87
+ }
88
+ /** Action configuration for interactive messages. */
89
+ export type InteractiveAction = {
90
+ type: 'buttons';
91
+ buttons: Array<{
92
+ id: string;
93
+ title: string;
94
+ }>;
95
+ } | {
96
+ type: 'list';
97
+ button: string;
98
+ sections: Array<{
99
+ title: string;
100
+ rows: Array<{
101
+ id: string;
102
+ title: string;
103
+ description?: string;
104
+ }>;
105
+ }>;
106
+ } | {
107
+ type: 'flow';
108
+ flowId: string;
109
+ flowToken?: string;
110
+ parameters?: Record<string, unknown>;
111
+ };
112
+ /** A user's reply to an interactive message. */
113
+ export interface InteractiveReply {
114
+ /** Type of interactive element that was replied to. */
115
+ type: string;
116
+ /** Identifier of the selected option. */
117
+ id: string;
118
+ /** Display title of the selected option. */
119
+ title?: string;
120
+ /** Description of the selected option. */
121
+ description?: string;
122
+ /** Raw payload from the platform. */
123
+ payload?: string;
124
+ }
125
+ /** A reaction event on a message. */
126
+ export interface ReactionData {
127
+ /** The message that was reacted to. */
128
+ messageId: string;
129
+ /** The emoji used in the reaction. */
130
+ emoji: string;
131
+ /** Whether this is a new reaction or an unreaction. */
132
+ action: 'react' | 'unreact';
133
+ /** The user who reacted. */
134
+ userId: string;
135
+ }
136
+ /** Context linking a message to a previous message (e.g. reply-to). */
137
+ export interface MessageContext {
138
+ /** The message being replied to or referenced. */
139
+ messageId: string;
140
+ /** The sender of the referenced message. */
141
+ from?: string;
142
+ }
143
+ /** Information about the conversation window. */
144
+ export interface ConversationInfo {
145
+ /** Platform-specific conversation identifier. */
146
+ id: string;
147
+ /** When the current messaging window expires. */
148
+ expirationTimestamp?: Date;
149
+ /** Origin of the conversation (e.g. "user_initiated", "business_initiated"). */
150
+ origin?: string;
151
+ }
152
+ /** Pricing information from the platform. */
153
+ export interface PricingInfo {
154
+ /** Pricing model identifier. */
155
+ model: string;
156
+ /** Message category for billing purposes. */
157
+ category: string;
158
+ }
159
+ /** Error details from a status webhook. */
160
+ export interface StatusError {
161
+ /** Platform-specific error code. */
162
+ code: string;
163
+ /** Short error title. */
164
+ title?: string;
165
+ /** Detailed error message. */
166
+ message?: string;
167
+ }
168
+ /** A normalized inbound message from any messaging platform. */
169
+ export interface InboundMessage {
170
+ /** Platform-specific message identifier. */
171
+ id: string;
172
+ /** The platform this message came from (e.g. "whatsapp", "messenger"). */
173
+ platform: string;
174
+ /** Conversation or thread identifier. */
175
+ threadId: string;
176
+ /** Sender information. */
177
+ from: ContactInfo;
178
+ /** When the message was sent. */
179
+ timestamp: Date;
180
+ /** The type of content in the message. */
181
+ type: 'text' | 'image' | 'video' | 'audio' | 'document' | 'sticker' | 'location' | 'contacts' | 'interactive' | 'reaction' | 'unknown';
182
+ /** Text content (for text messages). */
183
+ text?: string;
184
+ /** Media reference (for media messages). */
185
+ media?: MediaReference;
186
+ /** Location data (for location messages). */
187
+ location?: LocationData;
188
+ /** Contact cards (for contact messages). */
189
+ contacts?: ContactInfo[];
190
+ /** Interactive reply data (for interactive responses). */
191
+ interactive?: InteractiveReply;
192
+ /** Reaction data (for reaction events). */
193
+ reaction?: ReactionData;
194
+ /** Reply context if this message is a reply. */
195
+ context?: MessageContext;
196
+ /** Raw platform-specific message payload. */
197
+ raw?: unknown;
198
+ }
199
+ /** A delivery or read status update from the platform. */
200
+ export interface StatusUpdate {
201
+ /** The message this status applies to. */
202
+ messageId: string;
203
+ /** The delivery status. */
204
+ status: 'sent' | 'delivered' | 'read' | 'failed' | 'deleted' | 'warning';
205
+ /** When this status was reported. */
206
+ timestamp: Date;
207
+ /** The recipient of the original message. */
208
+ recipientId: string;
209
+ /** Thread identifier (same format as InboundMessage.threadId). */
210
+ threadId?: string;
211
+ /** Error details (when status is "failed" or "warning"). */
212
+ error?: StatusError;
213
+ /** Conversation window information. */
214
+ conversation?: ConversationInfo;
215
+ /** Pricing details for the message. */
216
+ pricing?: PricingInfo;
217
+ /** Raw platform-specific status payload. */
218
+ raw?: unknown;
219
+ }
220
+ /** Result returned after successfully sending a message. */
221
+ export interface SendResult {
222
+ /** Platform-assigned identifier for the sent message. */
223
+ messageId: string;
224
+ /** Thread or conversation the message was sent to. */
225
+ threadId: string;
226
+ /** When the message was accepted by the platform. */
227
+ timestamp: Date;
228
+ /** Raw platform-specific response. */
229
+ raw?: unknown;
230
+ }
231
+ /**
232
+ * Converts text between formats for platform-specific rendering.
233
+ *
234
+ * Each platform has its own text formatting rules (WhatsApp uses *bold*,
235
+ * Messenger supports a subset of Markdown, etc.). The converter handles
236
+ * these differences transparently.
237
+ */
238
+ export interface FormatConverter {
239
+ /** Convert Markdown text to plain text (strip all formatting). */
240
+ toPlainText(markdown: string): string;
241
+ /** Convert platform-specific formatted text to Markdown. */
242
+ toMarkdown(text: string): string;
243
+ /** Convert Markdown to the platform's native format. */
244
+ toPlatformFormat(markdown: string): string;
245
+ }
246
+ /**
247
+ * Handler invoked when an inbound message is received.
248
+ * @typeParam T - The raw platform-specific message type.
249
+ */
250
+ export type MessageHandler<T = unknown> = (message: InboundMessage, raw: T) => Promise<void>;
251
+ /** Handler invoked when a delivery/read status update is received. */
252
+ export type StatusHandler = (status: StatusUpdate) => Promise<void>;
253
+ /** Handler invoked when a reaction event is received. */
254
+ export type ReactionHandler = (reaction: ReactionData) => Promise<void>;
255
+ /**
256
+ * The master interface that all vendor messaging packages must implement.
257
+ *
258
+ * Each platform (WhatsApp, Messenger, Telegram, Slack, etc.) provides a
259
+ * concrete `PlatformClient` that normalizes the vendor API into this
260
+ * unified interface. The AriaFlow adapter layer consumes this interface
261
+ * to bridge any platform with `runtime.stream()`.
262
+ *
263
+ * @typeParam TConfig - Platform-specific configuration type.
264
+ * @typeParam TThreadId - Thread identifier type (usually `string`).
265
+ * @typeParam TInbound - Raw inbound message type from the platform.
266
+ * @typeParam TOutbound - Raw outbound message type for the platform.
267
+ */
268
+ export interface PlatformClient<TConfig = unknown, TThreadId = string, TInbound = unknown, TOutbound = unknown> {
269
+ /** The platform identifier (e.g. "whatsapp", "messenger", "telegram"). */
270
+ readonly platform: string;
271
+ /**
272
+ * Handle an incoming webhook request (both GET verification and POST events).
273
+ * The platform client is responsible for signature verification, parsing,
274
+ * and dispatching to registered handlers.
275
+ */
276
+ handleWebhook(request: Request): Promise<Response>;
277
+ /**
278
+ * Register a handler for inbound messages.
279
+ * Multiple handlers can be registered; they are called in order.
280
+ */
281
+ onMessage(handler: MessageHandler<TInbound>): void;
282
+ /**
283
+ * Register a handler for delivery/read status updates.
284
+ */
285
+ onStatus(handler: StatusHandler): void;
286
+ /**
287
+ * Register a handler for reaction events.
288
+ */
289
+ onReaction(handler: ReactionHandler): void;
290
+ /**
291
+ * Send a text message to a thread.
292
+ * @param to - The thread or recipient identifier.
293
+ * @param text - The text content to send.
294
+ * @returns The result of the send operation.
295
+ */
296
+ sendText(to: TThreadId, text: string): Promise<SendResult>;
297
+ /**
298
+ * Send a media message (image, video, audio, document, sticker).
299
+ * @param to - The thread or recipient identifier.
300
+ * @param media - The media payload to send.
301
+ */
302
+ sendMedia(to: TThreadId, media: MediaPayload): Promise<SendResult>;
303
+ /**
304
+ * Send an interactive message (buttons, list, flow).
305
+ * @param to - The thread or recipient identifier.
306
+ * @param msg - The interactive message definition.
307
+ */
308
+ sendInteractive(to: TThreadId, msg: InteractiveMessage): Promise<SendResult>;
309
+ /**
310
+ * Send a raw platform-specific payload. Escape hatch for features
311
+ * not covered by the normalized interface.
312
+ * @param to - The thread or recipient identifier.
313
+ * @param payload - The raw platform-specific payload.
314
+ */
315
+ sendRaw(to: TThreadId, payload: TOutbound): Promise<SendResult>;
316
+ /**
317
+ * Mark a message as read on the platform.
318
+ * @param messageId - The platform-specific message identifier.
319
+ */
320
+ markAsRead(messageId: string): Promise<void>;
321
+ /**
322
+ * Send a typing indicator (composing state) to a thread.
323
+ * @param to - The thread or recipient identifier.
324
+ */
325
+ sendTypingIndicator(to: TThreadId): Promise<void>;
326
+ /**
327
+ * Upload media to the platform for later use.
328
+ * @param file - The file content as a Buffer or ReadableStream.
329
+ * @param options - Upload options including MIME type.
330
+ */
331
+ uploadMedia(file: Buffer | ReadableStream, options: MediaUploadOptions): Promise<MediaHandle>;
332
+ /**
333
+ * Download media from the platform by its identifier.
334
+ * @param mediaId - The platform-specific media identifier.
335
+ */
336
+ downloadMedia(mediaId: string): Promise<MediaDownload>;
337
+ /**
338
+ * Format converter for this platform's text conventions.
339
+ */
340
+ formatConverter: FormatConverter;
341
+ /**
342
+ * Returns a Hono sub-application that handles webhook routes for this platform.
343
+ * Useful for mounting platform webhooks into an existing Hono app.
344
+ */
345
+ webhookRouter(): Hono;
346
+ }
347
+ /**
348
+ * Resolves an inbound message to a session identifier for the AriaFlow runtime.
349
+ */
350
+ export interface SessionResolver {
351
+ /**
352
+ * Map an inbound message to a session and optional user identifier.
353
+ * @param message - The normalized inbound message.
354
+ * @returns Session ID and optional user ID.
355
+ */
356
+ resolve(message: InboundMessage): Promise<{
357
+ sessionId: string;
358
+ userId?: string;
359
+ }>;
360
+ }
361
+ /**
362
+ * Context passed to a response mapper for sending platform messages.
363
+ */
364
+ export interface ResponseContext {
365
+ /** The thread to send responses to. */
366
+ threadId: string;
367
+ /** The platform name. */
368
+ platform: string;
369
+ /** Send a text message to the current thread. */
370
+ sendText(text: string): Promise<SendResult>;
371
+ /** Send an interactive message to the current thread. */
372
+ sendInteractive(msg: InteractiveMessage): Promise<SendResult>;
373
+ /** Send media to the current thread. */
374
+ sendMedia(media: MediaPayload): Promise<SendResult>;
375
+ }
376
+ /**
377
+ * Custom mapper that controls how AriaFlow stream output is sent to the platform.
378
+ * Implement this to customize message formatting, splitting, or interactive elements.
379
+ */
380
+ export interface ResponseMapper {
381
+ /**
382
+ * Map collected stream parts to platform messages.
383
+ * @param parts - The collected stream parts from the runtime.
384
+ * @param context - The response context with send methods bound to the current thread.
385
+ */
386
+ mapResponse(parts: HarnessStreamPart[], context: ResponseContext): Promise<void>;
387
+ }
388
+ /**
389
+ * Error context provided to the onError callback.
390
+ */
391
+ export interface ErrorContext {
392
+ /** The inbound message that triggered the error. */
393
+ message: InboundMessage;
394
+ /** The platform name where the error occurred. */
395
+ platform: string;
396
+ /** The error that was thrown. */
397
+ error: Error;
398
+ }
399
+ /**
400
+ * Configuration for creating a messaging router that bridges
401
+ * platform clients with the AriaFlow runtime.
402
+ */
403
+ export interface MessagingRouterConfig {
404
+ /** The AriaFlow runtime instance to stream from. */
405
+ runtime: Runtime;
406
+ /** Map of platform name to platform client instance. */
407
+ platforms: Record<string, PlatformClient>;
408
+ /** Custom session resolver. Defaults to `{platform}:{threadId}` mapping. */
409
+ sessionResolver?: SessionResolver;
410
+ /** Custom response mapper for controlling how stream output is sent. */
411
+ responseMapper?: ResponseMapper;
412
+ /** Callback for delivery/read status updates. */
413
+ onStatus?: StatusHandler;
414
+ /** Error callback. Invoked when runtime or platform errors occur. */
415
+ onError?: (error: Error, context: ErrorContext) => void;
416
+ /** Fallback message sent when the runtime throws an unrecoverable error. */
417
+ fallbackMessage?: string;
418
+ }
419
+ /**
420
+ * Options for the stream mapper.
421
+ */
422
+ export interface StreamMapperOptions {
423
+ /** Custom response mapper to use instead of the default behavior. */
424
+ responseMapper?: ResponseMapper;
425
+ /** Interval in ms for sending typing indicators during streaming. Default: 5000. */
426
+ typingIntervalMs?: number;
427
+ }
428
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAMvE,uDAAuD;AACvD,MAAM,WAAW,WAAW;IAC1B,4CAA4C;IAC5C,EAAE,EAAE,MAAM,CAAC;IACX,mCAAmC;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mDAAmD;IACnD,KAAK,CAAC,EAAE,MAAM,CAAC;C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AAE,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,YAAY,KAAK,IAAI,CAAC;IACxD,4EAA4E;IAC5E,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,qEAAqE;IACrE,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC,oFAAoF;IACpF,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@ariaflowagents/messaging",
3
+ "version": "0.8.1",
4
+ "description": "Core interfaces and AriaFlow adapter for messaging platforms",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" }
10
+ },
11
+ "publishConfig": { "access": "public" },
12
+ "files": ["dist", "README.md"],
13
+ "scripts": {
14
+ "build": "tsc -p tsconfig.json",
15
+ "clean": "rm -rf dist",
16
+ "test": "bun test",
17
+ "prepublishOnly": "npm run clean && npm run build"
18
+ },
19
+ "dependencies": {
20
+ "@ariaflowagents/core": "^0.8.0",
21
+ "hono": "^4.7.4"
22
+ },
23
+ "devDependencies": {
24
+ "@ariaflowagents/core": "workspace:*",
25
+ "typescript": "^5.8.2",
26
+ "@types/node": "^22.13.4"
27
+ }
28
+ }